diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index c67ee71d48b..e84227bd6b5 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -3,7 +3,7 @@ - [ ] Read the [contribution guidelines](https://github.com/swagger-api/swagger-codegen/blob/master/CONTRIBUTING.md). - [ ] Ran the shell script under `./bin/` to update Petstore sample so that CIs can verify the change. (For instance, only need to run `./bin/{LANG}-petstore.sh` and `./bin/security/{LANG}-petstore.sh` if updating the {LANG} (e.g. php, ruby, python, etc) code generator or {LANG} client's mustache templates). Windows batch files can be found in `.\bin\windows\`. - [ ] Filed the PR against the correct branch: `3.0.0` branch for changes related to OpenAPI spec 3.0. Default: `master`. -- [ ] Copied the [technical committee](https://github.com/swagger-api/swagger-codegen/#swagger-codegen-technical-committee) to review the pull request if your PR is targeting a particular programming langauge. +- [ ] Copied the [technical committee](https://github.com/swagger-api/swagger-codegen/#swagger-codegen-technical-committee) to review the pull request if your PR is targeting a particular programming language. ### Description of the PR diff --git a/.gitignore b/.gitignore index cce9df3dcfd..c31b8389c19 100644 --- a/.gitignore +++ b/.gitignore @@ -90,6 +90,11 @@ samples/client/petstore/silex/SwaggerServer/venodr/ **/vendor/ **/composer.lock +#PHP-Symfony +samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/cache/ +samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/logs/ + + # Perl samples/client/petstore/perl/deep_module_test/ diff --git a/.travis.yml b/.travis.yml index 7ca04a0ad95..f396f23ccd4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,13 +1,14 @@ sudo: required -language: objective-c -osx_image: xcode8.2 +language: java +jdk: + - oraclejdk8 + cache: directories: - $HOME/.m2 - $HOME/.ivy2 - $HOME/.gradle/caches/ - $HOME/.gradle/wrapper/ - - $HOME/.stack - $HOME/samples/client/petstore/php/SwaggerClient-php/vendor - $HOME/samples/client/petstore/ruby/venodr/bundle - $HOME/samples/client/petstore/python/.venv/ @@ -21,13 +22,11 @@ cache: - $HOME/samples/client/petstore/typescript-fetch/builds/es6-target/typings - $HOME/samples/client/petstore/typescript-fetch/builds/with-npm-version/node_modules - $HOME/samples/client/petstore/typescript-fetch/npm/with-npm-version/typings - - $HOME/samples/client/petstore/typescript-angularjs/node_modules - - $HOME/samples/client/petstore/typescript-angularjs/typings - - $HOME/.cocoapods/repos/master - timeout: 1000 -# note: docker is not yet supported in iOS build -#services: -# - docker + - $HOME/samples/client/petstore/typescript-angular/node_modules + - $HOME/samples/client/petstore/typescript-angular/typings + +services: + - docker # comment out the host table change to use the public petstore server addons: @@ -35,60 +34,38 @@ addons: - petstore.swagger.io before_install: - - export SW=`pwd` - - rvm list - - rvm use 2.2.5 - - gem environment - - gem install bundler -N --no-ri --no-rdoc - - gem install cocoapods -v 1.2.1 -N --no-ri --no-rdoc - - gem install xcpretty -N --no-ri --no-rdoc - - pod --version - # comment out below to avoid errors - #- pod repo update - - pod setup --silent > /dev/null + # required when sudo: required for the Ruby petstore tests + - gem install bundler - npm install -g typescript + - npm install -g npm - npm config set registry http://registry.npmjs.org/ - - brew install sbt - - brew install leiningen - - brew install bats - - brew install curl - - brew install python3 - - pip install virtualenv - - mkdir -p ~/.local/bin - - export PATH=$HOME/.local/bin:$PATH - - travis_retry curl --insecure -L https://www.stackage.org/stack/osx-x86_64 | tar xz --strip-components=1 --include '*/stack' -C ~/.local/bin - # start local petstore server - - git clone -b docker --single-branch https://github.com/wing328/swagger-samples - - cd swagger-samples/java/java-jersey-jaxrs - - sudo mvn jetty:run & - - cd $SW - # NOTE: iOS build not support docker at the moment + - sudo pip install virtualenv # to run petstore server locally via docker - #- docker pull swaggerapi/petstore - #- docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore - #- docker ps -a + - docker pull swaggerapi/petstore + - docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore + - docker ps -a + # Add bats test framework and cURL for Bash script integration tests + - sudo add-apt-repository ppa:duggan/bats --yes + - sudo apt-get update -qq + - sudo apt-get install -qq bats + - sudo apt-get install -qq curl + # comment out below as installation failed in travis # Add rebar3 build tool and recent Erlang/OTP for Erlang petstore server tests. # - Travis CI does not support rebar3 [yet](https://github.com/travis-ci/travis-ci/issues/6506#issuecomment-275189490). # - Rely on `kerl` for [pre-compiled versions available](https://docs.travis-ci.com/user/languages/erlang#Choosing-OTP-releases-to-test-against). Rely on installation path chosen by [`travis-erlang-builder`](https://github.com/travis-ci/travis-erlang-builder/blob/e6d016b1a91ca7ecac5a5a46395bde917ea13d36/bin/compile#L18). + # - . ~/otp/18.2.1/activate && erl -version + #- curl -f -L -o ./rebar3 https://s3.amazonaws.com/rebar3/rebar3 && chmod +x ./rebar3 && ./rebar3 version && export PATH="${TRAVIS_BUILD_DIR}:$PATH" # show host table to confirm petstore.swagger.io is mapped to localhost - cat /etc/hosts # show java version - java -version - # show brew version - - brew --version - # show xcpretty version - - xcpretty -v - # show go version - - go version - # show stack version - - stack --version install: # Add Godeps dependencies to GOPATH and PATH - - eval "$(curl -sL https://raw.githubusercontent.com/travis-ci/gimme/master/gimme | GIMME_GO_VERSION=1.4 bash)" - - export GOPATH="${TRAVIS_BUILD_DIR}/Godeps/_workspace" - - export PATH="${TRAVIS_BUILD_DIR}/Godeps/_workspace/bin:$PATH" + - eval "$(curl -sL https://raw.githubusercontent.com/travis-ci/gimme/master/gimme | GIMME_GO_VERSION=1.4 bash)" + - export GOPATH="${TRAVIS_BUILD_DIR}/Godeps/_workspace" + - export PATH="${TRAVIS_BUILD_DIR}/Godeps/_workspace/bin:$PATH" script: # fail fast @@ -101,13 +78,11 @@ script: - /bin/bash ./bin/utils/detect_tab_in_java_class.sh # run integration tests defined in maven pom.xml - mvn -q --batch-mode verify -Psamples -### docker-related tasks have been moved to CircleCI + # Below has been moved to CircleCI # docker: build generator image and push to Docker Hub #- if [ $DOCKER_HUB_USERNAME ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build -t $DOCKER_GENERATOR_IMAGE_NAME ./modules/swagger-generator && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_GENERATOR_IMAGE_NAME:latest $DOCKER_GENERATOR_IMAGE_NAME:$TRAVIS_TAG; fi && if [ ! -z "$TRAVIS_TAG" ] || [ "$TRAVIS_BRANCH" = "master" ]; then docker push $DOCKER_GENERATOR_IMAGE_NAME; fi; fi ## docker: build cli image and push to Docker Hub #- if [ $DOCKER_HUB_USERNAME ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build -t $DOCKER_CODEGEN_CLI_IMAGE_NAME ./modules/swagger-codegen-cli && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_CODEGEN_CLI_IMAGE_NAME:latest $DOCKER_CODEGEN_CLI_IMAGE_NAME:$TRAVIS_TAG; fi && if [ ! -z "$TRAVIS_TAG" ] || [ "$TRAVIS_BRANCH" = "master" ]; then docker push $DOCKER_CODEGEN_CLI_IMAGE_NAME; fi; fi -#env: -# - DOCKER_GENERATOR_IMAGE_NAME=swaggerapi/swagger-generator DOCKER_CODEGEN_CLI_IMAGE_NAME=swaggerapi/swagger-codegen-cli after_success: # push a snapshot version to maven repo @@ -115,3 +90,6 @@ after_success: mvn clean deploy --settings .travis/settings.xml; echo "Finished mvn clean deploy for $TRAVIS_BRANCH"; fi; + +env: + - DOCKER_GENERATOR_IMAGE_NAME=swaggerapi/swagger-generator DOCKER_CODEGEN_CLI_IMAGE_NAME=swaggerapi/swagger-codegen-cli diff --git a/README.md b/README.md index 96a9d2ad0ee..4f4b7676fa7 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ [![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project/badge.svg?style=plastic)](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project) [![PR Stats](http://issuestats.com/github/swagger-api/swagger-codegen/badge/pr)](http://issuestats.com/github/swagger-api/swagger-codegen) [![Issue Stats](http://issuestats.com/github/swagger-api/swagger-codegen/badge/issue)](http://issuestats.com/github/swagger-api/swagger-codegen) -:star::star::star: If you would like to contribute, please refer to [guidelines](https://github.com/swagger-api/swagger-codegen/blob/master/CONTRIBUTING.md) and a list of [open tasks](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aopen+is%3Aissue+label%3A%22Need+community+contribution%22).:star::star::star: +:star::star::star: If you would like to contribute, please refer to [guidelines](https://github.com/swagger-api/swagger-codegen/blob/master/CONTRIBUTING.md) and a list of [open tasks](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22).:star::star::star: :notebook_with_decorative_cover: For more information, please refer to the [Wiki page](https://github.com/swagger-api/swagger-codegen/wiki) and [FAQ](https://github.com/swagger-api/swagger-codegen/wiki/FAQ) :notebook_with_decorative_cover: @@ -24,8 +24,8 @@ ## Overview This is the swagger codegen project, which allows generation of API client libraries (SDK generation), server stubs and documentation automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification). Currently, the following languages/frameworks are supported: -- **API clients**: **ActionScript**, **Ada**, **Apex**, **Bash**, **C#** (.net 2.0, 4.0 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Elixir**, **Eiffel**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx), **Kotlin**, **Lua**, **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations) **Objective-C**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust**, **Scala** (akka, http4s, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x), **Typescript** (Angular1.x, Angular2.x, Fetch, jQuery, Node) -- **Server stubs**: **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed), **Erlang**, **Go**, **Haskell** (Servant), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy, Play Framework), **PHP** (Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Scala** ([Finch](https://github.com/finagle/finch), Scalatra) +- **API clients**: **ActionScript**, **Ada**, **Apex**, **Bash**, **C#** (.net 2.0, 4.0 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Elixir**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java), **Kotlin**, **Lua**, **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations) **Objective-C**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust**, **Scala** (akka, http4s, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x), **Typescript** (Angular1.x, Angular2.x, Fetch, jQuery, Node) +- **Server stubs**: **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed), **Erlang**, **Go**, **Haskell** (Servant), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy, Play Framework), **PHP** (Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust**, **Scala** ([Finch](https://github.com/finagle/finch), Scalatra) - **API documentation generators**: **HTML**, **Confluence Wiki** - **Configuration files**: [**Apache2**](https://httpd.apache.org/) - **Others**: **JMeter** @@ -462,6 +462,10 @@ src/IO.Swagger.Test/Model/AnimalFarmTests.cs The `.swagger-codegen-ignore` file must exist in the root of the output directory. +Upon first code generation, you may also pass the CLI option `--ignore-file-override=/path/to/ignore_file` for greater control over generated outputs. Note that this is a complete override, and will override the `.swagger-codegen-ignore` file in an output directory when regenerating code. + +Editor support for `.swagger-codegen-ignore` files is available in IntelliJ via the [.ignore plugin](https://plugins.jetbrains.com/plugin/7495--ignore). + ### 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: @@ -516,6 +520,7 @@ CONFIG OPTIONS okhttp-gson (default) - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 retrofit - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0) retrofit2 - HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2) + google-api-client - HTTP client: google-api-client 1.23.0. JSON processing: Jackson 2.8.9 ``` Your config file for Java can look like @@ -730,6 +735,7 @@ Please refer to this [page](https://github.com/swagger-api/swagger-codegen/blob/ Companies/Projects using Swagger Codegen ---------------------------------------- Here are some companies/projects using Swagger Codegen in production. To add your company/project to the list, please visit [README.md](https://github.com/swagger-api/swagger-codegen/blob/master/README.md) and click on the icon to edit the page. +- [Accengage](https://www.accengage.com/) - [Activehours](https://www.activehours.com/) - [Acunetix](https://www.acunetix.com/) - [Atlassian](https://www.atlassian.com/) @@ -760,6 +766,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [everystory.us](http://everystory.us) - [Expected Behavior](http://www.expectedbehavior.com/) - [Fastly](https://www.fastly.com/) +- [FINRA](https://github.com/FINRAOS/herd/) - [Flat](https://flat.io) - [Finder](http://en.finder.pl/) - [Fitwell](https://fitwell.co/) @@ -793,6 +800,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [LXL Tech](http://lxltech.com) - [Lyft](https://www.lyft.com/developers) - [MailMojo](https://mailmojo.no/) +- [Metaswitch](https://www.metaswitch.com/) - [Mindera](http://mindera.com/) - [Mporium](http://mporium.com/) - [Neverfail](https://neverfail.com/) @@ -901,6 +909,7 @@ Presentations/Videos/Tutorials/Books - 2017/09/30 - [Swaggerのテンプレートを魔改造した話 #渋谷java](https://www.slideshare.net/int128/swagger-80309224) by [Hidetake Iwata](https://github.com/int128) ([NTT DATA Corporation](http://www.nttdata.com/global/en/)) - 2017/10/04 - [Enterprise-friendly Java client for Microsoft Machine Learning Server](https://blogs.msdn.microsoft.com/mlserver/2017/10/04/enterprise-friendly-java-client-for-microsoft-machine-learning-server/) by [Pratik Palnitkar](https://www.linkedin.com/in/pratikpalnitkar/) ([Microsoft](https://www.microsoft.com/)) - 2017/10/08 - [Generating a REST Ada client with OpenAPI and Swagger Codegen](https://blog.vacs.fr/vacs/blogs/post.html?post=2017/10/08/Generating-a-REST-Ada-client-with-OpenAPI-and-Swagger-Codegen) by [Stephane Carrez](https://github.com/stcarrez) +- 2017/11/08 - [A Beginner's Guide to Code Generation for REST APIs](https://gum.co/swagger_codegen_beginner)(eBook) by [William Cheng](https://twitter.com/wing328) # Swagger Codegen Core Team @@ -967,9 +976,11 @@ Here is a list of template creators: * Dart: @yissachar * Elixir: @niku * Eiffel: @jvelilla + * Erlang: @tsloughter * Groovy: @victorgit * Go: @wing328 * Go (rewritten in 2.3.0): @antihax + * Haskell (http-client): @jonschoning * Java (Feign): @davidkiss * Java (Retrofit): @0legg * Java (Retrofit2): @emilianobonassi @@ -978,6 +989,7 @@ Here is a list of template creators: * Java (RestTemplate): @nbruno * Java (RESTEasy): @gayathrigs * Java (Vertx): @lopesmcc + * Java (Google APIs Client Library): @charlescapps * Javascript/NodeJS: @jfiala * Javascript (Closure-annotated Angular) @achew22 * JMeter: @davidkiss @@ -988,6 +1000,7 @@ Here is a list of template creators: * PowerShell: @beatcracker * R: @ramnov * Rust: @farcaller + * Rust (rust-server): @metaswitch * Scala (scalaz & http4s): @tbrown1979 * Swift: @tkqubo * Swift 3: @hexelon @@ -1018,6 +1031,7 @@ Here is a list of template creators: * PHP Symfony: @ksm2 * PHP Zend Expressive (with Path Handler): @Articus * Ruby on Rails 5: @zlx + * Rust (rust-server): @metaswitch * Scala Finch: @jimschubert * Documentation * HTML Doc 2: @jhitchcock @@ -1029,7 +1043,7 @@ Here is a list of template creators: Here are the requirements to become a core team member: - rank within top 50 in https://github.com/swagger-api/swagger-codegen/graphs/contributors - - to contribute, here are some good [starting points](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aopen+is%3Aissue+label%3A%22Need+community+contribution%22) + - to contribute, here are some good [starting points](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) - regular contributions to the project - about 3 hours per week - for contribution, it can be addressing issues, reviewing PRs submitted by others, submitting PR to fix bugs or make enhancements, etc @@ -1076,7 +1090,7 @@ If you want to join the committee, please kindly apply by sending an email to wi | ObjC | | | Perl | @wing328 (2017/07) | | PHP | @jebentier (2017/07) @dkarlovi (2017/07) @mandrean (2017/08) @jfastnacht (2017/09) @ackintosh (2017/09) | -| Python | @taxpon (2017/07) @frol (2017/07) @mbohlool (2017/07) @cbornet (2017/09) | +| Python | @taxpon (2017/07) @frol (2017/07) @mbohlool (2017/07) @cbornet (2017/09) @kenjones-cisco (2017/11)| | R | | | Ruby | @cliffano (2017/07) @zlx (2017/09) | | Rust | @frol (2017/07) @farcaller (2017/08) | diff --git a/bin/csharp-petstore-net-40.json b/bin/csharp-petstore-net-40.json new file mode 100644 index 00000000000..884f7ea9bc9 --- /dev/null +++ b/bin/csharp-petstore-net-40.json @@ -0,0 +1,3 @@ +{ + "targetFramework": "v4.0" +} diff --git a/bin/csharp-petstore-net-40.sh b/bin/csharp-petstore-net-40.sh new file mode 100755 index 00000000000..fd5d0876d04 --- /dev/null +++ b/bin/csharp-petstore-net-40.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-with-fake-endpoints-models-for-testing.yaml -l csharp -o samples/client/petstore/csharp/SwaggerClientNet40 --additional-properties packageGuid={321C8C3F-0156-40C1-AE42-D59761FB9B6C} -c ./bin/csharp-petstore-net-40.json" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/csharp-petstore.sh b/bin/csharp-petstore.sh index 232f706b7fd..fd5d0876d04 100755 --- a/bin/csharp-petstore.sh +++ b/bin/csharp-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-with-fake-endpoints-models-for-testing.yaml -l csharp -o samples/client/petstore/csharp/SwaggerClient --additional-properties packageGuid={321C8C3F-0156-40C1-AE42-D59761FB9B6C}" +ags="generate $@ -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l csharp -o samples/client/petstore/csharp/SwaggerClientNet40 --additional-properties packageGuid={321C8C3F-0156-40C1-AE42-D59761FB9B6C} -c ./bin/csharp-petstore-net-40.json" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/erlang-petstore-client.sh b/bin/erlang-petstore-client.sh new file mode 100755 index 00000000000..686ecd25629 --- /dev/null +++ b/bin/erlang-petstore-client.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/erlang-client -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l erlang-client -o samples/client/petstore/erlang-client" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-all.sh b/bin/java-petstore-all.sh index cf9bb61db49..4abe8e6c303 100755 --- a/bin/java-petstore-all.sh +++ b/bin/java-petstore-all.sh @@ -16,3 +16,4 @@ ./bin/java-petstore-resttemplate.sh ./bin/java-petstore-resttemplate-withxml.sh ./bin/java-petstore-resteasy.sh +./bin/java-petstore-google-api-client.sh diff --git a/bin/java-petstore-google-api-client.json b/bin/java-petstore-google-api-client.json new file mode 100644 index 00000000000..66df1f8c601 --- /dev/null +++ b/bin/java-petstore-google-api-client.json @@ -0,0 +1,4 @@ +{ + "library": "google-api-client", + "artifactId": "swagger-petstore-google-api-client" +} diff --git a/bin/java-petstore-google-api-client.sh b/bin/java-petstore-google-api-client.sh new file mode 100755 index 00000000000..09c9e14139a --- /dev/null +++ b/bin/java-petstore-google-api-client.sh @@ -0,0 +1,34 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/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/Java/libraries/google-api-client -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-google-api-client.json -o samples/client/petstore/java/google-api-client -DhideGenerationTimestamp=true" + +echo "Removing files and folders under samples/client/petstore/java/google-api-client/src/main" +rm -rf samples/client/petstore/java/google-api-client/src/main +find samples/client/petstore/java/google-api-client -maxdepth 1 -type f ! -name "README.md" -exec rm {} + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/nancyfx-petstore-server-async.sh b/bin/nancyfx-petstore-server-async.sh new file mode 100755 index 00000000000..b07c010731f --- /dev/null +++ b/bin/nancyfx-petstore-server-async.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/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/nancyfx -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l nancyfx -o samples/server/petstore/nancyfx-async --additional-properties packageGuid={768B8DC6-54EE-4D40-9B20-7857E1D742A4},asyncServer=true" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/php-symfony-petstore.sh b/bin/php-symfony-petstore.sh new file mode 100755 index 00000000000..17d9418b386 --- /dev/null +++ b/bin/php-symfony-petstore.sh @@ -0,0 +1,41 @@ +#!/bin/bash + +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 + +# Make sure that the working directory is the root dir +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +cd "${SCRIPT_DIR}/../" + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +# Make sure that we are regenerating the sample by removing any existing target directory +TARGET_DIR="$SCRIPT_DIR/../samples/server/petstore/php-symfony" +if [ -d "$TARGET_DIR" ]; then + rm -rf $TARGET_DIR +fi + +executable="$SCRIPT_DIR/../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 $SCRIPT_DIR/../modules/swagger-codegen/src/main/resources/php-symfony -i $SCRIPT_DIR/../modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l php-symfony -o $TARGET_DIR $@" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/run-all-petstore b/bin/run-all-petstore index be5901e0697..755ab2f749d 100755 --- a/bin/run-all-petstore +++ b/bin/run-all-petstore @@ -8,7 +8,7 @@ echo "Please press CTRL+C to stop or the script will continue in 10 seconds." sleep 10 -for SCRIPT in ./bin/*.sh +for SCRIPT in `ls -l ./bin/*.sh | grep -v all` do if [ -f $SCRIPT -a -x $SCRIPT ] then diff --git a/bin/rust-server-petstore.sh b/bin/rust-server-petstore.sh new file mode 100755 index 00000000000..e7e655d4812 --- /dev/null +++ b/bin/rust-server-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/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/rust-server -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l rust-server -o samples/server/petstore/rust-server -DpackageName=petstore_api" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/swift3-petstore-all.sh b/bin/swift3-petstore-all.sh index 8eb4a7c5f4f..a27fe261859 100755 --- a/bin/swift3-petstore-all.sh +++ b/bin/swift3-petstore-all.sh @@ -42,3 +42,7 @@ java $JAVA_OPTS -jar $executable $ags ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift3 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift3 -c ./bin/swift3-petstore-unwraprequired.json -o samples/client/petstore/swift3/unwraprequired" echo "#### Petstore Swift API client (unwraprequired) ####" java $JAVA_OPTS -jar $executable $ags + +ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift3 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift3 -c ./bin/swift3-petstore-objcCompatible.json -o samples/client/petstore/swift3/objcCompatible" +echo "#### Petstore Swift API client (objcCompatible) ####" +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-angular-v2-petstore-all.sh b/bin/typescript-angular-petstore-all.sh similarity index 68% rename from bin/typescript-angular-v2-petstore-all.sh rename to bin/typescript-angular-petstore-all.sh index ae2ae18719f..c3cdf8ba34f 100755 --- a/bin/typescript-angular-v2-petstore-all.sh +++ b/bin/typescript-angular-petstore-all.sh @@ -38,3 +38,11 @@ java $JAVA_OPTS -jar $executable $ags echo "Typescript Petstore API client (with interfaces generated)" ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-angular -o samples/client/petstore/typescript-angular-v2/with-interfaces -D withInterfaces=true --additional-properties ngVersion=2" java $JAVA_OPTS -jar $executable $ags + +echo "Typescript Petstore API client (v4 { Adding InjectionToken Over OpaqueToken })" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-angular -c bin/typescript-petstore-npm.json -o samples/client/petstore/typescript-angular-v4/npm --additional-properties ngVersion=4" +java $JAVA_OPTS -jar $executable $ags + +echo "Typescript Petstore API client (v4.3 { Adding HttpClientModule over HttpModule })" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-angular -c bin/typescript-petstore-npm.json -o samples/client/petstore/typescript-angular-v4.3/npm --additional-properties ngVersion=4.3" +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/windows/erlang-petstore-client.bat b/bin/windows/erlang-petstore-client.bat new file mode 100755 index 00000000000..228c0c7ca46 --- /dev/null +++ b/bin/windows/erlang-petstore-client.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M +set ags=generate -t modules\swagger-codegen\src\main\resources\erlang-client -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -l erlang-client -o samples\client\petstore\erlang-client + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/jaxrs-spec-petstore-server-interface.bat b/bin/windows/jaxrs-spec-petstore-server-interface.bat new file mode 100644 index 00000000000..5ca4f38101e --- /dev/null +++ b/bin/windows/jaxrs-spec-petstore-server-interface.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate --artifact-id "jaxrs-cxf-client-petstore-client" -i modules\swagger-codegen\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -l jaxrs-spec -o samples\server\petstore\jaxrs-spec-interface -DhideGenerationTimestamp=true,serializableModel=true,interfaceOnly=true + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/jaxrs-spec-petstore-server.bat b/bin/windows/jaxrs-spec-petstore-server.bat new file mode 100644 index 00000000000..30c19a50891 --- /dev/null +++ b/bin/windows/jaxrs-spec-petstore-server.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate --artifact-id "jaxrs-cxf-client-petstore-client" -i modules\swagger-codegen\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -l jaxrs-spec -o samples\server\petstore\jaxrs-spec -DhideGenerationTimestamp=true,serializableModel=true + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/rust-server-petstore.bat b/bin/windows/rust-server-petstore.bat new file mode 100755 index 00000000000..ff565aa1e04 --- /dev/null +++ b/bin/windows/rust-server-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -l rust-server -o samples\server\petstore\rust-server + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/typescript-angular2-petstore-all.bat b/bin/windows/typescript-angular-petstore-all.bat old mode 100755 new mode 100644 similarity index 58% rename from bin/windows/typescript-angular2-petstore-all.bat rename to bin/windows/typescript-angular-petstore-all.bat index 3d1a5179255..dff81b05a62 --- a/bin/windows/typescript-angular2-petstore-all.bat +++ b/bin/windows/typescript-angular-petstore-all.bat @@ -1,3 +1,7 @@ call .\bin\windows\typescript-angular-v2-with-npm.bat call .\bin\windows\typescript-angular-v2-interfaces.bat call .\bin\windows\typescript-angular-v2.bat +call .\bin\windows\typescript-angular-v4-with-npm.bat +call .\bin\windows\typescript-angular-v4.3-with-npm.bat + + diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 556b6ff2f63..ca6b8d4e361 100755 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -11,7 +11,7 @@ codegen="${cli}/target/swagger-codegen-cli.jar" cmdsrc="${cli}/src/main/java/io/swagger/codegen/cmd" pattern="@Command(name = \"$1\"" -if expr "x$1" : 'x[a-z][a-z-]*$' > /dev/null && fgrep -qe "$pattern" "$cmdsrc"/*.java; then +if expr "x$1" : 'x[a-z][a-z-]*$' > /dev/null && fgrep -qe "$pattern" "$cmdsrc"/*.java || expr "$1" = 'help' > /dev/null; then # If ${GEN_DIR} has been mapped elsewhere from default, and that location has not been built if [[ ! -f "${codegen}" ]]; then (cd "${GEN_DIR}" && exec mvn -am -pl "modules/swagger-codegen-cli" -Duser.home=$(dirname MAVEN_CONFIG) package) diff --git a/modules/swagger-codegen-maven-plugin/README.md b/modules/swagger-codegen-maven-plugin/README.md index ad32fc9f41f..34abd375b15 100644 --- a/modules/swagger-codegen-maven-plugin/README.md +++ b/modules/swagger-codegen-maven-plugin/README.md @@ -11,7 +11,7 @@ Add to your `build->plugins` section (default phase is `generate-sources` phase) io.swagger swagger-codegen-maven-plugin - 2.2.2 + 2.2.3 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 a650422f224..b0b08dfe523 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 @@ -154,6 +154,10 @@ public class CodegenConstants { public static final String DOTNET_FRAMEWORK_DESC = "The target .NET framework version."; public static enum MODEL_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case, original} + public static enum ENUM_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case, original, UPPERCASE} + + public static final String ENUM_PROPERTY_NAMING = "enumPropertyNaming"; + public static final String ENUM_PROPERTY_NAMING_DESC = "Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'"; public static final String MODEL_NAME_PREFIX = "modelNamePrefix"; public static final String MODEL_NAME_PREFIX_DESC = "Prefix that will be prepended to all model names. Default is the empty string."; 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 76eccdfa039..7b8cf07c471 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 @@ -9,7 +9,6 @@ import java.util.Objects; import io.swagger.models.ExternalDocs; - public class CodegenModel { public String parent, parentSchema; public List interfaces; 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 1273b96c5c2..71597b6fc8f 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 @@ -12,7 +12,7 @@ import java.util.Arrays; public class CodegenOperation { public final List responseHeaders = new ArrayList(); - public boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams, + public boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams, hasRequiredParams, returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer, isListContainer, isMultipart, hasMore = true, isResponseBinary = false, isResponseFile = false, hasReference = false, @@ -28,6 +28,7 @@ public class CodegenOperation { public List queryParams = new ArrayList(); public List headerParams = new ArrayList(); public List formParams = new ArrayList(); + public List requiredParams = new ArrayList(); public List authMethods; public List tags; public List responses = new ArrayList(); @@ -140,6 +141,15 @@ public class CodegenOperation { return Arrays.asList("PUT", "PATCH").contains(httpMethod.toUpperCase()) && isMemberPath(); } + /** + * Check if body param is allowed for the request method + * + * @return true request method is PUT, PATCH or POST; false otherwise + */ + public boolean isBodyAllowed() { + return Arrays.asList("PUT", "PATCH", "POST").contains(httpMethod.toUpperCase()); + } + /** * Check if act as Restful destroy method * diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java index bb437c9a036..296122899b8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java @@ -14,7 +14,7 @@ public class CodegenParameter { public String example; // example value (x-example) public String jsonSchema; - public boolean isString, isNumeric, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid; + public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid; public boolean isListContainer, isMapContainer; public boolean isFile, notFile; public boolean isEnum; @@ -138,6 +138,7 @@ public class CodegenParameter { output.isLong = this.isLong; output.isDouble = this.isDouble; output.isFloat = this.isFloat; + output.isNumber = this.isNumber; output.isBoolean = this.isBoolean; output.isDate = this.isDate; output.isDateTime = this.isDateTime; @@ -217,6 +218,8 @@ public class CodegenParameter { return false; if (isLong != that.isLong) return false; + if (isNumber != that.isNumber) + return false; if (isFloat != that.isFloat) return false; if (isDouble != that.isDouble) @@ -308,6 +311,7 @@ public class CodegenParameter { result = 31 * result + (isInteger ? 13:31); result = 31 * result + (isLong ? 13:31); result = 31 * result + (isFloat ? 13:31); + result = 31 * result + (isNumber ? 13:31); result = 31 * result + (isDouble ? 13:31); result = 31 * result + (isByteArray ? 13:31); result = 31 * result + (isBinary ? 13:31); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java index a7fa9385cc7..e50364ce1cd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java @@ -39,7 +39,7 @@ public class CodegenProperty implements Cloneable { public boolean hasMore, required, secondaryParam; public boolean hasMoreNonReadOnly; // for model constructor, true if next properyt is not readonly public boolean isPrimitiveType, isContainer, isNotContainer; - public boolean isString, isNumeric, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isFile, isBoolean, isDate, isDateTime, isUuid; + public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBinary, isFile, isBoolean, isDate, isDateTime, isUuid; public boolean isListContainer, isMapContainer; public boolean isEnum; public boolean isReadOnly = false; @@ -118,6 +118,7 @@ public class CodegenProperty implements Cloneable { result = prime * result + ((isNumeric ? 13:31)); result = prime * result + ((isInteger ? 13:31)); result = prime * result + ((isLong ?13:31)); + result = prime * result + ((isNumber ? 13:31)); result = prime * result + ((isFloat ? 13:31)); result = prime * result + ((isDouble ? 13:31)); result = prime * result + ((isByteArray ? 13:31)); @@ -272,6 +273,9 @@ public class CodegenProperty implements Cloneable { if (this.isLong != other.isLong) { return false; } + if (this.isNumber != other.isNumber) { + return false; + } if (this.isFloat != other.isFloat) { return false; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java index 1b2b74214d0..6a0dfa44c4e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java @@ -11,7 +11,7 @@ public class CodegenResponse { public List> examples; public String dataType, baseType, containerType; public boolean hasHeaders; - public boolean isString, isNumeric, isInteger, isLong, isFloat, isDouble, isByteArray, isBoolean, isDate, isDateTime, isUuid; + public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBoolean, isDate, isDateTime, isUuid; public boolean isDefault; public boolean simpleType; public boolean primitiveType; 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 c80f2373bff..c6bc0f0cdb8 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,20 +2,8 @@ package io.swagger.codegen; import javax.annotation.Nullable; import java.io.File; -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.*; 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; @@ -1130,7 +1118,7 @@ public class DefaultCodegen { String datatype = null; if (p instanceof StringProperty && "number".equals(p.getFormat())) { datatype = "BigDecimal"; - } else if (p instanceof ByteArrayProperty) { + } else if ((p instanceof ByteArrayProperty) || (p instanceof StringProperty && "byte".equals(p.getFormat()))) { datatype = "ByteArray"; } else if (p instanceof BinaryProperty) { datatype = "binary"; @@ -1706,20 +1694,7 @@ public class DefaultCodegen { // type is number and without format if (p instanceof DecimalProperty && !(p instanceof DoubleProperty) && !(p instanceof FloatProperty)) { DecimalProperty sp = (DecimalProperty) p; - property.isFloat = true; - /*if (sp.getEnum() != null) { - List _enum = sp.getEnum(); - property._enum = new ArrayList(); - for(Double i : _enum) { - property._enum.add(i.toString()); - } - property.isEnum = true; - - // legacy support - Map allowableValues = new HashMap(); - allowableValues.put("values", _enum); - property.allowableValues = allowableValues; - }*/ + property.isNumber = true; } if (p instanceof DoubleProperty) { DoubleProperty sp = (DoubleProperty) p; @@ -2231,6 +2206,7 @@ public class DefaultCodegen { List headerParams = new ArrayList(); List cookieParams = new ArrayList(); List formParams = new ArrayList(); + List requiredParams = new ArrayList(); if (parameters != null) { for (Parameter param : parameters) { @@ -2253,13 +2229,6 @@ public class DefaultCodegen { } } - // set isPrimitiveType and baseType for allParams - /*if (languageSpecificPrimitives.contains(p.baseType)) { - p.isPrimitiveType = true; - p.baseType = getSwaggerType(p); - }*/ - - allParams.add(p); // Issue #2561 (neilotoole) : Moved setting of isParam flags // from here to fromParameter(). @@ -2280,7 +2249,10 @@ public class DefaultCodegen { } else if (param instanceof FormParameter) { formParams.add(p.copy()); } - if (!p.required) { + + if (p.required) { //required parameters + requiredParams.add(p.copy()); + } else { // optional parameters op.hasOptionalParams = true; } } @@ -2314,6 +2286,7 @@ public class DefaultCodegen { op.headerParams = addHasMore(headerParams); // op.cookieParams = cookieParams; op.formParams = addHasMore(formParams); + op.requiredParams = addHasMore(requiredParams); op.externalDocs = operation.getExternalDocs(); // legacy support op.nickname = op.operationId; @@ -2321,6 +2294,7 @@ public class DefaultCodegen { if (op.allParams.size() > 0) { op.hasParams = true; } + op.hasRequiredParams = op.requiredParams.size() > 0; // set Restful Flag op.isRestfulShow = op.isRestfulShow(); @@ -2373,7 +2347,9 @@ public class DefaultCodegen { } r.dataType = cm.datatype; - if (Boolean.TRUE.equals(cm.isString)) { + if (Boolean.TRUE.equals(cm.isByteArray)) { + r.isByteArray = true; + } else if (Boolean.TRUE.equals(cm.isString)) { r.isString = true; } else if (Boolean.TRUE.equals(cm.isBoolean)) { r.isBoolean = true; @@ -2383,14 +2359,15 @@ public class DefaultCodegen { } else if (Boolean.TRUE.equals(cm.isInteger)) { r.isInteger = true; r.isNumeric = true; + } else if (Boolean.TRUE.equals(cm.isNumber)) { + r.isNumber = true; + r.isNumeric = true; } else if (Boolean.TRUE.equals(cm.isDouble)) { r.isDouble = true; r.isNumeric = true; } else if (Boolean.TRUE.equals(cm.isFloat)) { r.isFloat = true; r.isNumeric = true; - } else if (Boolean.TRUE.equals(cm.isByteArray)) { - r.isByteArray = true; } else if (Boolean.TRUE.equals(cm.isBinary)) { r.isBinary = true; } else if (Boolean.TRUE.equals(cm.isFile)) { @@ -2714,6 +2691,8 @@ public class DefaultCodegen { p.example = "56"; } else if (Boolean.TRUE.equals(p.isFloat)) { p.example = "3.4"; + } else if (Boolean.TRUE.equals(p.isNumber)) { + p.example = "8.14"; } else if (Boolean.TRUE.equals(p.isDouble)) { p.example = "1.2"; } else if (Boolean.TRUE.equals(p.isBinary)) { @@ -2909,7 +2888,7 @@ public class DefaultCodegen { * @return true if the library/module/package of the corresponding type needs to be imported */ protected boolean needToImport(String type) { - return !defaultIncludes.contains(type) + return StringUtils.isNotBlank(type) && !defaultIncludes.contains(type) && !languageSpecificPrimitives.contains(type); } @@ -3384,8 +3363,17 @@ public class DefaultCodegen { * @param library Library template */ public void setLibrary(String library) { - if (library != null && !supportedLibraries.containsKey(library)) - throw new RuntimeException("unknown library: " + library); + if (library != null && !supportedLibraries.containsKey(library)) { + StringBuilder sb = new StringBuilder("Unknown library: " + library + "\nAvailable libraries:"); + if(supportedLibraries.size() == 0) { + sb.append("\n ").append("NONE"); + } else { + for (String lib : supportedLibraries.keySet()) { + sb.append("\n ").append(lib); + } + } + throw new RuntimeException(sb.toString()); + } this.library = library; } @@ -3595,7 +3583,10 @@ public class DefaultCodegen { return; } - if (Boolean.TRUE.equals(property.isString)) { + if (Boolean.TRUE.equals(property.isByteArray)) { + parameter.isByteArray = true; + parameter.isPrimitiveType = true; + } else if (Boolean.TRUE.equals(property.isString)) { parameter.isString = true; parameter.isPrimitiveType = true; } else if (Boolean.TRUE.equals(property.isBoolean)) { @@ -3613,8 +3604,8 @@ public class DefaultCodegen { } else if (Boolean.TRUE.equals(property.isFloat)) { parameter.isFloat = true; parameter.isPrimitiveType = true; - } else if (Boolean.TRUE.equals(property.isByteArray)) { - parameter.isByteArray = true; + } else if (Boolean.TRUE.equals(property.isNumber)) { + parameter.isNumber = true; parameter.isPrimitiveType = true; } else if (Boolean.TRUE.equals(property.isBinary)) { parameter.isByteArray = true; 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 7cf9dec0a22..143fa9568f6 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 @@ -68,9 +68,13 @@ public class InlineModelResolver { Model innerModel = modelFromProperty(op, modelName); String existing = matchGenerated(innerModel); if (existing != null) { - am.setItems(new RefProperty(existing)); + RefProperty refProperty = new RefProperty(existing); + refProperty.setRequired(op.getRequired()); + am.setItems(refProperty); } else { - am.setItems(new RefProperty(modelName)); + RefProperty refProperty = new RefProperty(modelName); + refProperty.setRequired(op.getRequired()); + am.setItems(refProperty); addGenerated(modelName, innerModel); swagger.addDefinition(modelName, innerModel); } @@ -94,9 +98,13 @@ public class InlineModelResolver { Model model = modelFromProperty(op, modelName); String existing = matchGenerated(model); if (existing != null) { - response.setSchema(this.makeRefProperty(existing, property)); + Property refProperty = this.makeRefProperty(existing, property); + refProperty.setRequired(op.getRequired()); + response.setSchema(refProperty); } else { - response.setSchema(this.makeRefProperty(modelName, property)); + Property refProperty = this.makeRefProperty(modelName, property); + refProperty.setRequired(op.getRequired()); + response.setSchema(refProperty); addGenerated(modelName, model); swagger.addDefinition(modelName, model); } @@ -114,9 +122,13 @@ public class InlineModelResolver { Model innerModel = modelFromProperty(op, modelName); String existing = matchGenerated(innerModel); if (existing != null) { - ap.setItems(this.makeRefProperty(existing, op)); + Property refProperty = this.makeRefProperty(existing, op); + refProperty.setRequired(op.getRequired()); + ap.setItems(refProperty); } else { - ap.setItems(this.makeRefProperty(modelName, op)); + Property refProperty = this.makeRefProperty(modelName, op); + refProperty.setRequired(op.getRequired()); + ap.setItems(refProperty); addGenerated(modelName, innerModel); swagger.addDefinition(modelName, innerModel); } @@ -135,9 +147,13 @@ public class InlineModelResolver { Model innerModel = modelFromProperty(op, modelName); String existing = matchGenerated(innerModel); if (existing != null) { - mp.setAdditionalProperties(new RefProperty(existing)); + RefProperty refProperty = new RefProperty(existing); + refProperty.setRequired(op.getRequired()); + mp.setAdditionalProperties(refProperty); } else { - mp.setAdditionalProperties(new RefProperty(modelName)); + RefProperty refProperty = new RefProperty(modelName); + refProperty.setRequired(op.getRequired()); + mp.setAdditionalProperties(refProperty); addGenerated(modelName, innerModel); swagger.addDefinition(modelName, innerModel); } @@ -174,9 +190,13 @@ public class InlineModelResolver { if (existing == null) { swagger.addDefinition(innerModelName, innerModel); addGenerated(innerModelName, innerModel); - m.setItems(new RefProperty(innerModelName)); + RefProperty refProperty = new RefProperty(innerModelName); + refProperty.setRequired(op.getRequired()); + m.setItems(refProperty); } else { - m.setItems(new RefProperty(existing)); + RefProperty refProperty = new RefProperty(existing); + refProperty.setRequired(op.getRequired()); + m.setItems(refProperty); } } } @@ -271,9 +291,13 @@ public class InlineModelResolver { String existing = matchGenerated(model); if (existing != null) { - propsToUpdate.put(key, new RefProperty(existing)); + RefProperty refProperty = new RefProperty(existing); + refProperty.setRequired(op.getRequired()); + propsToUpdate.put(key, refProperty); } else { - propsToUpdate.put(key, new RefProperty(modelName)); + RefProperty refProperty = new RefProperty(modelName); + refProperty.setRequired(op.getRequired()); + propsToUpdate.put(key, refProperty); modelsToAdd.put(modelName, model); addGenerated(modelName, model); swagger.addDefinition(modelName, model); @@ -290,9 +314,13 @@ public class InlineModelResolver { Model innerModel = modelFromProperty(op, modelName); String existing = matchGenerated(innerModel); if (existing != null) { - ap.setItems(new RefProperty(existing)); + RefProperty refProperty = new RefProperty(existing); + refProperty.setRequired(op.getRequired()); + ap.setItems(refProperty); } else { - ap.setItems(new RefProperty(modelName)); + RefProperty refProperty = new RefProperty(modelName); + refProperty.setRequired(op.getRequired()); + ap.setItems(refProperty); addGenerated(modelName, innerModel); swagger.addDefinition(modelName, innerModel); } @@ -310,9 +338,13 @@ public class InlineModelResolver { Model innerModel = modelFromProperty(op, modelName); String existing = matchGenerated(innerModel); if (existing != null) { - mp.setAdditionalProperties(new RefProperty(existing)); + RefProperty refProperty = new RefProperty(existing); + refProperty.setRequired(op.getRequired()); + mp.setAdditionalProperties(refProperty); } else { - mp.setAdditionalProperties(new RefProperty(modelName)); + RefProperty refProperty = new RefProperty(modelName); + refProperty.setRequired(op.getRequired()); + mp.setAdditionalProperties(refProperty); addGenerated(modelName, innerModel); swagger.addDefinition(modelName, innerModel); } @@ -399,7 +431,7 @@ public class InlineModelResolver { /** * Make a RefProperty - * + * * @param ref new property name * @param property Property * @return @@ -412,7 +444,7 @@ public class InlineModelResolver { /** * Copy vendor extensions from Property to another Property - * + * * @param source source property * @param target target property */ 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 dfe4e8ff099..58b4d68fb56 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 @@ -355,7 +355,6 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co for (Map.Entry entry : models.entrySet()) { String swaggerName = entry.getKey(); - CodegenModel model = ModelUtils.getModelByName(swaggerName, models); if (model != null) { for (CodegenProperty var : model.allVars) { @@ -369,7 +368,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co updateCodegenPropertyEnum(var); - // We do this after updateCodegenPropertyEnum to avoid generalities that don't mesh with C#. + // We do these after updateCodegenPropertyEnum to avoid generalities that don't mesh with C#. var.isPrimitiveType = true; } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCppCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCppCodegen.java index 1c44d1587c4..52eb538fc9d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCppCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCppCodegen.java @@ -166,4 +166,14 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg property.nameInCamelCase = nameInCamelCase; return property; } + + /** + * Output the Getter name for boolean property, e.g. isActive + * + * @param name the name of the property + * @return getter name based on naming convention + */ + public String toBooleanGetter(String name) { + return "is" + getterAndSetterCapitalize(name); + } } 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 be53ddf68a6..3904f9d46dc 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 @@ -18,11 +18,20 @@ 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.BooleanProperty; +import io.swagger.models.properties.DateProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.DoubleProperty; import io.swagger.models.properties.FileProperty; +import io.swagger.models.properties.FloatProperty; +import io.swagger.models.properties.IntegerProperty; +import io.swagger.models.properties.LongProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; +import io.swagger.models.properties.StringProperty; public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig { + private static final String UNDEFINED_VALUE = "undefined"; protected String modelPropertyNaming= "camelCase"; protected Boolean supportsES6 = true; @@ -221,6 +230,49 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp return super.getTypeDeclaration(p); } + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + StringProperty sp = (StringProperty) p; + if (sp.getDefault() != null) { + return "\"" + sp.getDefault() + "\""; + } + return UNDEFINED_VALUE; + } else if (p instanceof BooleanProperty) { + return UNDEFINED_VALUE; + } else if (p instanceof DateProperty) { + return UNDEFINED_VALUE; + } else if (p instanceof DateTimeProperty) { + return UNDEFINED_VALUE; + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return UNDEFINED_VALUE; + } else if (p instanceof FloatProperty) { + FloatProperty fp = (FloatProperty) p; + if (fp.getDefault() != null) { + return fp.getDefault().toString(); + } + return UNDEFINED_VALUE; + } else if (p instanceof IntegerProperty) { + IntegerProperty ip = (IntegerProperty) p; + if (ip.getDefault() != null) { + return ip.getDefault().toString(); + } + return UNDEFINED_VALUE; + } else if (p instanceof LongProperty) { + LongProperty lp = (LongProperty) p; + if (lp.getDefault() != null) { + return lp.getDefault().toString(); + } + return UNDEFINED_VALUE; + } else { + return UNDEFINED_VALUE; + } + } + @Override public String getSwaggerType(Property p) { String swaggerType = super.getSwaggerType(p); 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 b40bdff2a9c..00e1e2708be 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 @@ -15,6 +15,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { @SuppressWarnings({"hiding"}) private static final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class); private static final String NET45 = "v4.5"; + private static final String NET40 = "v4.0"; private static final String NET35 = "v3.5"; private static final String NETSTANDARD = "v5.0"; private static final String UWP = "uwp"; @@ -75,6 +76,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { ); frameworks = new ImmutableMap.Builder() .put(NET35, ".NET Framework 3.5 compatible") + .put(NET40, ".NET Framework 4.0 compatible") .put(NET45, ".NET Framework 4.5+ compatible") .put(NETSTANDARD, ".NET Standard 1.3 compatible") .put(UWP, "Universal Windows Platform (IMPORTANT: this will be decommissioned and replaced by v5.0)") @@ -227,7 +229,13 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { setSupportsUWP(Boolean.TRUE); additionalProperties.put("supportsAsync", this.supportsAsync); additionalProperties.put("supportsUWP", this.supportsUWP); - + } else if (NET40.equals(this.targetFramework)) { + setTargetFrameworkNuget("net40"); + setSupportsAsync(Boolean.FALSE); + if (additionalProperties.containsKey("supportsAsync")) { + additionalProperties.remove("supportsAsync"); + } + additionalProperties.put("isNet40", true); } else { setTargetFrameworkNuget("net45"); setSupportsAsync(Boolean.TRUE); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java index 744e0102dfd..b93ee0d6c9e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java @@ -179,8 +179,10 @@ public class CppRestClientCodegen extends AbstractCppCodegen { additionalProperties.put("modelNamespaceDeclarations", modelPackage.split("\\.")); additionalProperties.put("modelNamespace", modelPackage.replaceAll("\\.", "::")); + additionalProperties.put("modelHeaderGuardPrefix", modelPackage.replaceAll("\\.", "_").toUpperCase()); additionalProperties.put("apiNamespaceDeclarations", apiPackage.split("\\.")); additionalProperties.put("apiNamespace", apiPackage.replaceAll("\\.", "::")); + additionalProperties.put("apiHeaderGuardPrefix", apiPackage.replaceAll("\\.", "_").toUpperCase()); additionalProperties.put("declspec", declspec); additionalProperties.put("defaultInclude", defaultInclude); } @@ -312,7 +314,7 @@ public class CppRestClientCodegen extends AbstractCppCodegen { @Override public String toDefaultValue(Property p) { if (p instanceof StringProperty) { - return "U(\"\")"; + return "utility::conversions::to_string_t(\"\")"; } else if (p instanceof BooleanProperty) { return "false"; } else if (p instanceof DateProperty) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangClientCodegen.java new file mode 100644 index 00000000000..ae4d4c9fad8 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangClientCodegen.java @@ -0,0 +1,391 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.parameters.Parameter; + +import java.io.File; +import java.util.*; +import java.io.Writer; +import java.io.IOException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig { + static Logger LOGGER = LoggerFactory.getLogger(ErlangClientCodegen.class); + + protected String packageName = "swagger"; + protected String packageVersion = "1.0.0"; + protected String sourceFolder = "src"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "erlang-client"; + } + + public String getHelp() { + return "Generates an Erlang client library (beta)."; + } + + public ErlangClientCodegen() { + super(); + outputFolder = "generated-code/erlang"; + modelTemplateFiles.put("model.mustache", ".erl"); + apiTemplateFiles.put("api.mustache", ".erl"); + + embeddedTemplateDir = templateDir = "erlang-client"; + + setReservedWordsLowerCase( + Arrays.asList( + "after","and","andalso","band","begin","bnot","bor","bsl","bsr","bxor","case", + "catch","cond","div","end","fun","if","let","not","of","or","orelse","receive", + "rem","try","when","xor" + ) + ); + + instantiationTypes.clear(); + + typeMapping.clear(); + typeMapping.put("enum", "binary()"); + typeMapping.put("date", "calendar:date()"); + typeMapping.put("datetime", "calendar:datetime()"); + typeMapping.put("date-time", "calendar:datetime()"); + typeMapping.put("boolean", "boolean()"); + typeMapping.put("string", "binary()"); + typeMapping.put("integer", "integer()"); + typeMapping.put("int", "integer()"); + typeMapping.put("float", "integer()"); + typeMapping.put("long", "integer()"); + typeMapping.put("double", "float()"); + typeMapping.put("array", "list()"); + typeMapping.put("map", "maps:map()"); + typeMapping.put("number", "integer()"); + typeMapping.put("bigdecimal", "float()"); + typeMapping.put("List", "list()"); + typeMapping.put("object", "maps:map()"); + typeMapping.put("file", "binary()"); + typeMapping.put("binary", "binary()"); + typeMapping.put("bytearray", "binary()"); + typeMapping.put("byte", "binary()"); + typeMapping.put("uuid", "binary()"); + typeMapping.put("password", "binary()"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Erlang application name (convention: lowercase).") + .defaultValue(this.packageName)); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Erlang application version") + .defaultValue(this.packageVersion)); + } + + @Override + public String getTypeDeclaration(String name) { + return name + ":" + name + "()"; + } + + @Override + public String getTypeDeclaration(Property p) { + String swaggerType = getSwaggerType(p); + if (typeMapping.containsKey(swaggerType)) { + return typeMapping.get(swaggerType); + } + return swaggerType; + } + + @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 = getTypeDeclaration(toModelName(snakeCase(swaggerType))); + return type; + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } + else { + setPackageName("swagger"); + } + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); + } + else { + setPackageVersion("1.0.0"); + } + + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); + + additionalProperties.put("length", new Mustache.Lambda() { + @Override + public void execute(Template.Fragment fragment, Writer writer) throws IOException { + writer.write(length(fragment.context())); + } + }); + + additionalProperties.put("qsEncode", new Mustache.Lambda() { + @Override + public void execute(Template.Fragment fragment, Writer writer) throws IOException { + writer.write(qsEncode(fragment.context())); + } + }); + + modelPackage = packageName; + apiPackage = packageName; + + supportingFiles.add(new SupportingFile("rebar.config.mustache","", "rebar.config")); + supportingFiles.add(new SupportingFile("app.src.mustache", "", "src" + File.separator + this.packageName + ".app.src")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + } + + public String qsEncode(Object o) { + String r = new String(); + CodegenParameter q = (CodegenParameter) o; + if (q.isListContainer) { + r += "[{<<\"" + q.baseName + "\">>, X} || X <- " + q.paramName + "]"; + } else { + r += "{<<\"" + q.baseName + "\">>, " + q.paramName + "}"; + } + return r; + } + + @Override + public String escapeReservedWord(String name) + { + // Can't start with an underscore, as our fields need to start with an + // UppercaseLetter so that Go treats them as public/visible. + + // Options? + // - MyName + // - AName + // - TheName + // - XName + // - X_Name + // ... or maybe a suffix? + // - Name_ ... think this will work. + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return camelize(name) + '_'; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + sourceFolder + File.separator; + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separator + sourceFolder + File.separator; + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = sanitizeName(name.replaceAll("-", "_")); + // for reserved word or word starting with number, append _ + if (isReservedWord(name)) + name = escapeReservedWord(name); + + return name; + } + + @Override + public String toParamName(String name) { + return camelize(toVarName(name)); + } + + @Override + public String toModelName(String name) { + return this.packageName + "_" + underscore(name.replaceAll("-", "_")); + } + + @Override + public String toApiName(String name) { + return this.packageName + "_" + underscore(name.replaceAll("-", "_")); + } + + @Override + public String toModelFilename(String name) { + return this.packageName + "_" + 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. PetApi.erl => pet_api.erl + return this.packageName + "_" + underscore(name) + "_api"; + } + + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); + operationId = "call_" + operationId; + } + + return underscore(operationId); + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List os = (List) operations.get("operation"); + List newOs = new ArrayList(); + Pattern pattern = Pattern.compile("(.*)\\{([^\\}]+)\\}(.*)"); + for (CodegenOperation o : os) { + // force http method to lower case + o.httpMethod = o.httpMethod.toLowerCase(); + + if (o.isListContainer) { + o.returnType = "[" + o.returnBaseType + "]"; + } + + ArrayList pathTemplateNames = new ArrayList(); + Matcher matcher = pattern.matcher(o.path); + StringBuffer buffer = new StringBuffer(); + while (matcher.find()) { + String pathTemplateName = matcher.group(2); + matcher.appendReplacement(buffer, "$1" + "\", " + camelize(pathTemplateName) + ", \"" + "$3"); + pathTemplateNames.add(pathTemplateName); + } + ExtendedCodegenOperation eco = new ExtendedCodegenOperation(o); + if (buffer.toString().isEmpty()) { + eco.setReplacedPathName(o.path); + } else { + eco.setReplacedPathName(buffer.toString()); + } + eco.setPathTemplateNames(pathTemplateNames); + newOs.add(eco); + } + operations.put("operation", newOs); + return objs; + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + + String length(Object o) { + return Integer.toString((((ExtendedCodegenOperation) o).allParams).size()); + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + + class ExtendedCodegenOperation extends CodegenOperation { + private List pathTemplateNames = new ArrayList(); + private String replacedPathName; + + public ExtendedCodegenOperation(CodegenOperation o) { + super(); + + // Copy all fields of CodegenOperation + this.responseHeaders.addAll(o.responseHeaders); + this.hasAuthMethods = o.hasAuthMethods; + this.hasConsumes = o.hasConsumes; + this.hasProduces = o.hasProduces; + this.hasParams = o.hasParams; + this.hasOptionalParams = o.hasOptionalParams; + this.returnTypeIsPrimitive = o.returnTypeIsPrimitive; + this.returnSimpleType = o.returnSimpleType; + this.subresourceOperation = o.subresourceOperation; + this.isMapContainer = o.isMapContainer; + this.isListContainer = o.isListContainer; + this.isMultipart = o.isMultipart; + this.hasMore = o.hasMore; + this.isResponseBinary = o.isResponseBinary; + this.hasReference = o.hasReference; + this.isRestfulIndex = o.isRestfulIndex; + this.isRestfulShow = o.isRestfulShow; + this.isRestfulCreate = o.isRestfulCreate; + this.isRestfulUpdate = o.isRestfulUpdate; + this.isRestfulDestroy = o.isRestfulDestroy; + this.isRestful = o.isRestful; + this.path = o.path; + this.operationId = o.operationId; + this.returnType = o.returnType; + this.httpMethod = o.httpMethod; + this.returnBaseType = o.returnBaseType; + this.returnContainer = o.returnContainer; + this.summary = o.summary; + this.unescapedNotes = o.unescapedNotes; + this.notes = o.notes; + this.baseName = o.baseName; + this.defaultResponse = o.defaultResponse; + this.discriminator = o.discriminator; + this.consumes = o.consumes; + this.produces = o.produces; + this.bodyParam = o.bodyParam; + this.allParams = o.allParams; + this.bodyParams = o.bodyParams; + this.pathParams = o.pathParams; + this.queryParams = o.queryParams; + this.headerParams = o.headerParams; + this.formParams = o.formParams; + this.authMethods = o.authMethods; + this.tags = o.tags; + this.responses = o.responses; + this.imports = o.imports; + this.examples = o.examples; + this.externalDocs = o.externalDocs; + this.vendorExtensions = o.vendorExtensions; + this.nickname = o.nickname; + this.operationIdLowerCase = o.operationIdLowerCase; + this.operationIdCamelCase = o.operationIdCamelCase; + } + + public List getPathTemplateNames() { + return pathTemplateNames; + } + + public void setPathTemplateNames(List pathTemplateNames) { + this.pathTemplateNames = pathTemplateNames; + } + + public String getReplacedPathName() { + return replacedPathName; + } + + public void setReplacedPathName(String replacedPathName) { + this.replacedPathName = replacedPathName; + } + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java index f807325c144..612c0b7a68d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java @@ -248,17 +248,30 @@ public class FinchServerCodegen extends DefaultCodegen implements CodegenConfig for (CodegenParameter p : op.allParams) { // TODO: This hacky, should be converted to mappings if possible to keep it clean. // This could also be done using template imports - if(Boolean.TRUE.equals(p.isPrimitiveType)) { + if(p.isPathParam && p.isPrimitiveType) { p.vendorExtensions.put("x-codegen-normalized-path-type", p.dataType.toLowerCase()); p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType); - } else if(Boolean.TRUE.equals(p.isBodyParam)) { + } else if(p.isHeaderParam) { + if(p.required) { + p.vendorExtensions.put("x-codegen-normalized-path-type", "header(\"" + p.baseName + "\")"); + p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType); + } else { + p.vendorExtensions.put("x-codegen-normalized-path-type", "headerOption(\"" + p.baseName + "\")"); + p.vendorExtensions.put("x-codegen-normalized-input-type", "Option["+ p.dataType + "]"); + } + } else if(p.isQueryParam) { + if(p.isContainer || p.isListContainer) { + p.vendorExtensions.put("x-codegen-normalized-path-type", "params(\"" + p.baseName + "\")"); + p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType.replaceAll("^[^\\[]+", "Seq")); + } else { + p.vendorExtensions.put("x-codegen-normalized-path-type", "param(\"" + p.baseName + "\")"); + p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType); + } + } else if(p.isBodyParam) { p.vendorExtensions.put("x-codegen-normalized-path-type", "jsonBody["+ p.dataType + "]"); p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType); - } else if(Boolean.TRUE.equals(p.isContainer) || Boolean.TRUE.equals(p.isListContainer)) { - p.vendorExtensions.put("x-codegen-normalized-path-type", "params(\""+ p.paramName + "\")"); - p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType.replaceAll("^[^\\[]+", "Seq")); - } else if(Boolean.TRUE.equals(p.isFile)) { - p.vendorExtensions.put("x-codegen-normalized-path-type", "fileUpload(\""+ p.paramName + "\")"); + } else if(p.isFile) { + p.vendorExtensions.put("x-codegen-normalized-path-type", "fileUpload(\""+ p.baseName + "\")"); p.vendorExtensions.put("x-codegen-normalized-input-type", "FileUpload"); } else { p.vendorExtensions.put("x-codegen-normalized-path-type", p.dataType); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellHttpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellHttpClientCodegen.java index 23476ddf803..f7a4da78871 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellHttpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellHttpClientCodegen.java @@ -2,7 +2,6 @@ package io.swagger.codegen.languages; import io.swagger.codegen.*; import io.swagger.models.Model; -import io.swagger.models.ModelImpl; import io.swagger.models.Operation; import io.swagger.models.Swagger; import io.swagger.models.properties.*; @@ -10,8 +9,6 @@ import io.swagger.models.properties.*; import java.util.*; import java.util.regex.Pattern; -import org.apache.commons.io.FileUtils; - import io.swagger.models.auth.SecuritySchemeDefinition; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConstants; @@ -24,6 +21,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.lang3.tuple.Pair; import java.util.regex.Matcher; @@ -38,16 +36,18 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC protected String defaultDateFormat = "%Y-%m-%d"; protected Boolean useMonadLogger = false; + protected Boolean genEnums = true; // CLI PROPS public static final String PROP_ALLOW_FROMJSON_NULLS = "allowFromJsonNulls"; public static final String PROP_ALLOW_TOJSON_NULLS = "allowToJsonNulls"; public static final String PROP_DATETIME_FORMAT = "dateTimeFormat"; public static final String PROP_DATE_FORMAT = "dateFormat"; + public static final String PROP_GENERATE_ENUMS = "generateEnums"; public static final String PROP_GENERATE_FORM_URLENCODED_INSTANCES = "generateFormUrlEncodedInstances"; public static final String PROP_GENERATE_LENSES = "generateLenses"; public static final String PROP_GENERATE_MODEL_CONSTRUCTORS = "generateModelConstructors"; - public static final String PROP_INLINE_CONSUMES_CONTENT_TYPES = "inlineConsumesContentTypes"; + public static final String PROP_INLINE_MIME_TYPES = "inlineMimeTypes"; public static final String PROP_MODEL_DERIVING = "modelDeriving"; public static final String PROP_STRICT_FIELDS = "strictFields"; public static final String PROP_USE_MONAD_LOGGER = "useMonadLogger"; @@ -58,21 +58,26 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC private static final Pattern LEADING_UNDERSCORE = Pattern.compile("^_+"); static final String MEDIA_TYPE = "mediaType"; + static final String MIME_NO_CONTENT = "MimeNoContent"; // vendor extensions static final String X_ALL_UNIQUE_PARAMS = "x-allUniqueParams"; static final String X_COLLECTION_FORMAT = "x-collectionFormat"; - static final String X_DUPLICATE = "x-duplicate"; static final String X_HADDOCK_PATH = "x-haddockPath"; static final String X_HAS_BODY_OR_FORM_PARAM = "x-hasBodyOrFormParam"; + static final String X_HAS_ENUM_SECTION = "x-hasEnumSection"; static final String X_HAS_MIME_FORM_URL_ENCODED = "x-hasMimeFormUrlEncoded"; static final String X_HAS_NEW_TAG = "x-hasNewTag"; static final String X_HAS_OPTIONAL_PARAMS = "x-hasOptionalParams"; static final String X_HAS_UNKNOWN_MIME_TYPES = "x-hasUnknownMimeTypes"; static final String X_HAS_UNKNOWN_RETURN = "x-hasUnknownReturn"; static final String X_INLINE_CONTENT_TYPE = "x-inlineContentType"; + static final String X_INLINE_ACCEPT = "x-inlineAccept"; static final String X_IS_BODY_OR_FORM_PARAM = "x-isBodyOrFormParam"; + static final String X_IS_BODY_PARAM = "x-isBodyParam"; static final String X_MEDIA_DATA_TYPE = "x-mediaDataType"; + static final String X_DATA_TYPE = "x-dataType"; + static final String X_ENUM_VALUES = "x-enumValues"; static final String X_MEDIA_IS_JSON = "x-mediaIsJson"; static final String X_MIME_TYPES = "x-mimeTypes"; static final String X_OPERATION_TYPE = "x-operationType"; @@ -82,14 +87,15 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC static final String X_STRICT_FIELDS = "x-strictFields"; static final String X_UNKNOWN_MIME_TYPES = "x-unknownMimeTypes"; static final String X_USE_MONAD_LOGGER = "x-useMonadLogger"; + static final String X_NEWTYPE = "x-newtype"; + static final String X_ENUM = "x-enum"; - protected Map uniqueParamsByName = new HashMap(); + protected ArrayList> unknownMimeTypes = new ArrayList<>(); + protected Map> uniqueParamNameTypes = new HashMap<>(); + protected Map> modelMimeTypes = new HashMap<>(); + protected Map knownMimeDataTypes = new HashMap<>(); protected Set typeNames = new HashSet(); - protected Map knownMimeDataTypes = new HashMap(); - protected Map> modelMimeTypes = new HashMap>(); - protected String lastTag = ""; - protected ArrayList> unknownMimeTypes = new ArrayList>(); public CodegenType getTag() { return CodegenType.CLIENT; @@ -138,7 +144,8 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC "instance", "let", "in", "mdo", "module", "newtype", "proc", "qualified", "rec", - "type", "where", "pure", "return" + "type", "where", "pure", "return", + "Accept", "ContentType" ) ); @@ -212,8 +219,10 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC cliOptions.add(CliOption.newBoolean(PROP_ALLOW_TOJSON_NULLS, "allow emitting JSON Null during model encoding to JSON").defaultValue(Boolean.FALSE.toString())); cliOptions.add(CliOption.newBoolean(PROP_GENERATE_LENSES, "Generate Lens optics for Models").defaultValue(Boolean.TRUE.toString())); cliOptions.add(CliOption.newBoolean(PROP_GENERATE_MODEL_CONSTRUCTORS, "Generate smart constructors (only supply required fields) for models").defaultValue(Boolean.TRUE.toString())); + cliOptions.add(CliOption.newBoolean(PROP_GENERATE_ENUMS, "Generate specific datatypes for swagger enums").defaultValue(Boolean.TRUE.toString())); cliOptions.add(CliOption.newBoolean(PROP_GENERATE_FORM_URLENCODED_INSTANCES, "Generate FromForm/ToForm instances for models that are used by operations that produce or consume application/x-www-form-urlencoded").defaultValue(Boolean.TRUE.toString())); - cliOptions.add(CliOption.newBoolean(PROP_INLINE_CONSUMES_CONTENT_TYPES, "Inline (hardcode) the content-type on operations that do not have multiple content-types (Consumes)").defaultValue(Boolean.FALSE.toString())); + cliOptions.add(CliOption.newBoolean(PROP_INLINE_MIME_TYPES, "Inline (hardcode) the content-type and accept parameters on operations, when there is only 1 option").defaultValue(Boolean.FALSE.toString())); + cliOptions.add(CliOption.newString(PROP_MODEL_DERIVING, "Additional classes to include in the deriving() clause of Models")); cliOptions.add(CliOption.newBoolean(PROP_STRICT_FIELDS, "Add strictness annotations to all model fields").defaultValue((Boolean.TRUE.toString()))); @@ -237,12 +246,15 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC public void setGenerateModelConstructors(Boolean value) { additionalProperties.put(PROP_GENERATE_MODEL_CONSTRUCTORS, value); } - + public void setGenerateEnums(Boolean value) { + additionalProperties.put(PROP_GENERATE_ENUMS, value); + genEnums = value; + } public void setGenerateFormUrlEncodedInstances(Boolean value) { additionalProperties.put(PROP_GENERATE_FORM_URLENCODED_INSTANCES, value); } - public void setInlineConsumesContentTypes (Boolean value) { - additionalProperties.put(PROP_INLINE_CONSUMES_CONTENT_TYPES, value); + public void setInlineMimeTypes(Boolean value) { + additionalProperties.put(PROP_INLINE_MIME_TYPES, value); } public void setGenerateLenses(Boolean value) { @@ -311,16 +323,22 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC setGenerateModelConstructors(true); } + if (additionalProperties.containsKey(PROP_GENERATE_ENUMS)) { + setGenerateEnums(convertPropertyToBoolean(PROP_GENERATE_ENUMS)); + } else { + setGenerateEnums(true); + } + if (additionalProperties.containsKey(PROP_GENERATE_FORM_URLENCODED_INSTANCES)) { setGenerateFormUrlEncodedInstances(convertPropertyToBoolean(PROP_GENERATE_FORM_URLENCODED_INSTANCES)); } else { setGenerateFormUrlEncodedInstances(true); } - if (additionalProperties.containsKey(PROP_INLINE_CONSUMES_CONTENT_TYPES)) { - setInlineConsumesContentTypes(convertPropertyToBoolean(PROP_INLINE_CONSUMES_CONTENT_TYPES)); + if (additionalProperties.containsKey(PROP_INLINE_MIME_TYPES)) { + setInlineMimeTypes(convertPropertyToBoolean(PROP_INLINE_MIME_TYPES)); } else { - setInlineConsumesContentTypes(false); + setInlineMimeTypes(false); } if (additionalProperties.containsKey(PROP_GENERATE_LENSES)) { @@ -515,7 +533,19 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC op.vendorExtensions.put(X_HAS_OPTIONAL_PARAMS, true); } - deduplicateParameter(param); + if (typeMapping.containsKey(param.dataType) + || param.isMapContainer || param.isListContainer + || param.isPrimitiveType || param.isFile || param.isEnum) { + + String dataType = genEnums && param.isEnum ? param.datatypeWithEnum : param.dataType; + + String paramNameType = toDedupedName(toTypeName("Param", param.paramName), dataType, !param.isEnum); + param.vendorExtensions.put(X_PARAM_NAME_TYPE, paramNameType); + + HashMap props = new HashMap<>(); + props.put(X_IS_BODY_PARAM, param.isBodyParam); + addToUniques(X_NEWTYPE, paramNameType, dataType, props); + } } processPathExpr(op); @@ -550,6 +580,17 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC ops.get(0).vendorExtensions.put(X_HAS_NEW_TAG, true); } + updateGlobalAdditionalProps(); + return ret; + } + + @Override + public Map postProcessAllModels(Map objs) { + updateGlobalAdditionalProps(); + return super.postProcessAllModels(objs); + } + + public void updateGlobalAdditionalProps() { additionalProperties.put(X_HAS_UNKNOWN_MIME_TYPES, !unknownMimeTypes.isEmpty()); Collections.sort(unknownMimeTypes, new Comparator>() { @@ -560,19 +601,17 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC }); additionalProperties.put(X_UNKNOWN_MIME_TYPES, unknownMimeTypes); - ArrayList params = new ArrayList<>(uniqueParamsByName.values()); - Collections.sort(params, new Comparator() { + ArrayList> params = new ArrayList<>(uniqueParamNameTypes.values()); + Collections.sort(params, new Comparator>() { @Override - public int compare(CodegenParameter o1, CodegenParameter o2) { + public int compare(Map o1, Map o2) { return - ((String) o1.vendorExtensions.get(X_PARAM_NAME_TYPE)) + ((String) o1.get(X_PARAM_NAME_TYPE)) .compareTo( - (String) o2.vendorExtensions.get(X_PARAM_NAME_TYPE)); + (String) o2.get(X_PARAM_NAME_TYPE)); } }); additionalProperties.put(X_ALL_UNIQUE_PARAMS, params); - - return ret; } @Override @@ -615,12 +654,6 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC prop.name = toVarName(prefix, prop.name); } - //String dataOrNewtype = "data"; - // check if it's a ModelImpl before casting - if (!(mod instanceof ModelImpl)) { - return model; - } - return model; } @@ -661,6 +694,9 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC op.vendorExtensions.put(X_HAS_UNKNOWN_RETURN, true); } else { returnType = "NoContent"; + if(!op.vendorExtensions.containsKey(X_INLINE_ACCEPT)) { + SetNoContent(op, X_INLINE_ACCEPT); + } } } if (returnType.indexOf(" ") >= 0) { @@ -670,9 +706,12 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC } private void processProducesConsumes(CodegenOperation op) { + if (!(Boolean) op.vendorExtensions.get(X_HAS_BODY_OR_FORM_PARAM)) { + SetNoContent(op, X_INLINE_CONTENT_TYPE); + } if (op.hasConsumes) { for (Map m : op.consumes) { - processMediaType(op,m); + processMediaType(op, m); processInlineConsumesContentType(op, m); } @@ -683,12 +722,14 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC if (op.hasProduces) { for (Map m : op.produces) { processMediaType(op,m); + processInlineProducesContentType(op, m); } } } private void processInlineConsumesContentType(CodegenOperation op, Map m) { - if ((boolean) additionalProperties.get(PROP_INLINE_CONSUMES_CONTENT_TYPES) + if (op.vendorExtensions.containsKey(X_INLINE_CONTENT_TYPE)) return; + if ((boolean) additionalProperties.get(PROP_INLINE_MIME_TYPES) && op.consumes.size() == 1) { op.vendorExtensions.put(X_INLINE_CONTENT_TYPE, m); for (CodegenParameter param : op.allParams) { @@ -699,51 +740,80 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC } } - private void deduplicateParameter(CodegenParameter param) { - if (typeMapping.containsKey(param.dataType) || param.isPrimitiveType || param.isListContainer || param.isMapContainer || param.isFile) { - - String paramNameType = toTypeName("Param", param.paramName); - - if (uniqueParamsByName.containsKey(paramNameType)) { - if(!checkParamForDuplicates(paramNameType, param)) { - paramNameType = paramNameType + param.dataType; - if(!checkParamForDuplicates(paramNameType, param)) { - while (typeNames.contains(paramNameType)) { - paramNameType = generateNextName(paramNameType); - if(checkParamForDuplicates(paramNameType, param)) { - break; - } - } - } - - uniqueParamsByName.put(paramNameType, param); - } - } else { - - while (typeNames.contains(paramNameType)) { - paramNameType = generateNextName(paramNameType); - if(checkParamForDuplicates(paramNameType, param)) { - break; - } - } - - uniqueParamsByName.put(paramNameType, param); - } - - param.vendorExtensions.put(X_PARAM_NAME_TYPE, paramNameType); - typeNames.add(paramNameType); + private void processInlineProducesContentType(CodegenOperation op, Map m) { + if ((boolean) additionalProperties.get(PROP_INLINE_MIME_TYPES) + && op.produces.size() == 1) { + op.vendorExtensions.put(X_INLINE_ACCEPT, m); } } - public Boolean checkParamForDuplicates(String paramNameType, CodegenParameter param) { - CodegenParameter lastParam = this.uniqueParamsByName.get(paramNameType); - if (lastParam != null && lastParam.dataType != null && lastParam.dataType.equals(param.dataType)) { - param.vendorExtensions.put(X_DUPLICATE, true); - return true; + private void SetNoContent(CodegenOperation op, String inlineExtentionName) { + Map m = new HashMap<>(); + m.put(X_MEDIA_DATA_TYPE, MIME_NO_CONTENT); + op.vendorExtensions.put(inlineExtentionName, m); + } + + private String toDedupedName(String paramNameType, String dataType, Boolean appendDataType) { + if (appendDataType + && uniqueParamNameTypes.containsKey(paramNameType) + && !isDuplicate(paramNameType, dataType)) { + paramNameType = paramNameType + dataType; + } + + while (typeNames.contains(paramNameType)) { + if (isDuplicate(paramNameType, dataType)) { + break; + } + paramNameType = generateNextName(paramNameType); + } + + typeNames.add(paramNameType); + return paramNameType; + } + + public Boolean isDuplicate(String paramNameType, String dataType) { + Map lastParam = this.uniqueParamNameTypes.get(paramNameType); + if (lastParam != null) { + String comparisonKey = lastParam.containsKey(X_ENUM) ? X_ENUM_VALUES : X_DATA_TYPE; + String lastParamDataType = (String) lastParam.get(comparisonKey); + if (lastParamDataType != null && lastParamDataType.equals(dataType)) { + return true; + } } return false; } + private Pair isDuplicateEnumValues(String enumValues) { + for (Map vs : uniqueParamNameTypes.values()) { + if (enumValues.equals(vs.get(X_ENUM_VALUES))) { + return Pair.of(true, (String) vs.get(X_PARAM_NAME_TYPE)); + } + } + return Pair.of(false, null); + } + + + private void addToUniques(String xGroup, String paramNameType, String dataType, Map props) { + HashMap m = new HashMap<>(); + m.put(X_PARAM_NAME_TYPE, paramNameType); + m.put(X_DATA_TYPE, dataType); + m.put(xGroup, true); + m.putAll(props); + uniqueParamNameTypes.put(paramNameType, m); + } + + private void addEnumToUniques(String paramNameType, String datatype, String enumValues, Map allowableValues, String description) { + HashMap props = new HashMap<>(); + props.put("allowableValues", allowableValues); + if(StringUtils.isNotBlank(description)) { + props.put("description", description); + } + props.put(X_ENUM_VALUES, enumValues); + addToUniques(X_ENUM, paramNameType, datatype, props); + additionalProperties.put(X_HAS_ENUM_SECTION, true); + } + + // build the parameterized path segments, according to pathParams private void processPathExpr(CodegenOperation op) { String xPath = "[\"" + escapeText(op.path) + "\"]"; @@ -835,7 +905,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC private String getMimeDataType(String mimeType) { if (StringUtils.isBlank(mimeType)) { - return "MimeNoContent"; + return MIME_NO_CONTENT; } if (knownMimeDataTypes.containsKey(mimeType)) { return knownMimeDataTypes.get(mimeType); @@ -962,20 +1032,121 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC } @Override - public String toEnumName(CodegenProperty property) { - return "Enum'" + toTypeName("", property.name); + public Map postProcessModels(Map objs) { + List models = (List) objs.get("models"); + for (Object _mo : models) { + Map mo = (Map) _mo; + CodegenModel cm = (CodegenModel) mo.get("model"); + cm.isEnum = genEnums && cm.isEnum; + if(cm.isAlias) { + cm.vendorExtensions.put(X_DATA_TYPE, cm.dataType); + } + for (CodegenProperty var : cm.vars) { + String datatype = genEnums && !StringUtils.isBlank(var.datatypeWithEnum) + ? var.datatypeWithEnum + : var.datatype; + var.vendorExtensions.put(X_DATA_TYPE, datatype); + } + } + return postProcessModelsEnum(objs); + } + + @Override + public Map postProcessModelsEnum(Map objs) { + Map objsEnum = super.postProcessModelsEnum(objs); + if (genEnums) { + List models = (List) objsEnum.get("models"); + for (Object _mo : models) { + Map mo = (Map) _mo; + CodegenModel cm = (CodegenModel) mo.get("model"); + if (cm.isEnum && cm.allowableValues != null) { + updateAllowableValuesNames(cm.classname, cm.allowableValues); + addEnumToUniques(cm.classname, cm.dataType, cm.allowableValues.values().toString(), cm.allowableValues, cm.description); + } + } + } + return objsEnum; + } + + @Override + protected void updateDataTypeWithEnumForMap(CodegenProperty property) { + CodegenProperty baseItem = property.items; + while (baseItem != null && (Boolean.TRUE.equals(baseItem.isMapContainer) || Boolean.TRUE.equals(baseItem.isListContainer))) { + baseItem = baseItem.items; + } + if (baseItem != null) { + + // this replacement is/needs to be language-specific + property.datatypeWithEnum = property.datatypeWithEnum.replace(baseItem.baseType + ")", toEnumName(baseItem) + ")"); + + property.enumName = toEnumName(property); + if (property.defaultValue != null) { + property.defaultValue = property.defaultValue.replace(", " + property.items.baseType, ", " + toEnumName(property.items)); + } + } + } + + @Override + public String toEnumName(CodegenProperty var) { + if (!genEnums) return super.toEnumName(var); + + if (var.items != null && var.items.isEnum) { + return toEnumName(var.items); + } + String paramNameType = "E'" + toTypeName("", var.name); + String enumValues = var._enum.toString(); + + Pair duplicateEnum = isDuplicateEnumValues(enumValues); + if (duplicateEnum.getLeft()) { + paramNameType = duplicateEnum.getRight(); + } else { + paramNameType = toDedupedName(paramNameType, enumValues, false); + var.datatypeWithEnum = paramNameType; + updateCodegenPropertyEnum(var); + addEnumToUniques(paramNameType, var.datatype, enumValues, var.allowableValues, var.description); + } + + return paramNameType; + } + + @Override + public void updateCodegenPropertyEnum(CodegenProperty var) { + super.updateCodegenPropertyEnum(var); + if (!genEnums) return; + updateCodegenPropertyEnumValues(var, var.datatypeWithEnum); + } + + public void updateCodegenPropertyEnumValues(CodegenProperty var, String paramNameType) { + if (var.items != null && var.items.allowableValues != null) { + updateCodegenPropertyEnumValues(var.items, var.items.datatypeWithEnum); + return; + } + if(var.isEnum && var.allowableValues != null) { + updateAllowableValuesNames(paramNameType, var.allowableValues); + } + } + + private void updateAllowableValuesNames(String paramNameType, Map allowableValues) { + if (allowableValues == null) { + return; + } + for (Map enumVar : (List>) allowableValues.get("enumVars")) { + enumVar.put("name", paramNameType + enumVar.get("name")); + } } @Override public String toEnumVarName(String value, String datatype) { + if (!genEnums) return super.toEnumVarName(value, datatype); + List num = new ArrayList<>(Arrays.asList("integer","int","double","long","float")); if (value.length() == 0) { - return "E'Empty"; + return "'Empty"; } // for symbol, e.g. $, # if (getSymbolName(value) != null) { - return "E'" + sanitizeName(getSymbolName(value)); + return "'" + StringUtils.capitalize(sanitizeName(getSymbolName(value))); } // number @@ -984,10 +1155,10 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC varName = varName.replaceAll("-", "Minus_"); varName = varName.replaceAll("\\+", "Plus_"); varName = varName.replaceAll("\\.", "_Dot_"); - return "E'" + sanitizeName(varName); + return "'" + StringUtils.capitalize(sanitizeName(varName)); } - return "E'" + sanitizeName(value); + return "'" + StringUtils.capitalize(sanitizeName(value)); } @Override 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 33066ebeb92..9ef0e34aa99 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 @@ -1,10 +1,13 @@ package io.swagger.codegen.languages; +import static java.util.Collections.sort; + import com.google.common.collect.LinkedListMultimap; import io.swagger.codegen.*; import io.swagger.codegen.languages.features.BeanValidationFeatures; import io.swagger.codegen.languages.features.GzipFeatures; import io.swagger.codegen.languages.features.PerformBeanValidationFeatures; + import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -49,6 +52,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen protected boolean useGzipFeature = false; protected boolean useRuntimeException = false; + public JavaClientCodegen() { super(); outputFolder = "generated-code" + File.separator + "java"; @@ -78,6 +82,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen supportedLibraries.put("resttemplate", "HTTP client: Spring RestTemplate 4.3.9-RELEASE. JSON processing: Jackson 2.8.9"); supportedLibraries.put("resteasy", "HTTP client: Resteasy client 3.1.3.Final. JSON processing: Jackson 2.8.9"); supportedLibraries.put("vertx", "HTTP client: VertX client 3.2.4. JSON processing: Jackson 2.8.9"); + supportedLibraries.put("google-api-client", "HTTP client: Google API client 1.23.0. JSON processing: Jackson 2.8.9"); CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); libraryOption.setEnum(supportedLibraries); @@ -168,10 +173,13 @@ public class JavaClientCodegen extends AbstractJavaCodegen supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); } - supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); - supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); - supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); - supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); + // google-api-client doesn't use the Swagger auth, because it uses Google Credential directly (HttpRequestInitializer) + if (!"google-api-client".equals(getLibrary())) { + supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); + supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); + supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); + supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); + } supportingFiles.add(new SupportingFile( "gradlew.mustache", "", "gradlew") ); supportingFiles.add(new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") ); supportingFiles.add(new SupportingFile( "gradle-wrapper.properties.mustache", @@ -192,7 +200,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen apiDocTemplateFiles.remove("api_doc.mustache"); } - if (!("feign".equals(getLibrary()) || "resttemplate".equals(getLibrary()) || usesAnyRetrofitLibrary())) { + if (!("feign".equals(getLibrary()) || "resttemplate".equals(getLibrary()) || usesAnyRetrofitLibrary() || "google-api-client".equals(getLibrary()))) { supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); @@ -236,6 +244,8 @@ public class JavaClientCodegen extends AbstractJavaCodegen apiTemplateFiles.put("apiImpl.mustache", "Impl.java"); apiTemplateFiles.put("rxApiImpl.mustache", ".java"); supportingFiles.remove(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); + } else if ("google-api-client".equals(getLibrary())) { + additionalProperties.put("jackson", "true"); } else { LOGGER.error("Unknown library option (-l/--library): " + getLibrary()); } @@ -316,10 +326,34 @@ public class JavaClientCodegen extends AbstractJavaCodegen if (operation.returnType == null) { operation.returnType = "Void"; } - if (usesRetrofit2Library() && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")) + if (usesRetrofit2Library() && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")){ operation.path = operation.path.substring(1); + } + + // sorting operation parameters to make sure path params are parsed before query params + if (operation.allParams != null) { + sort(operation.allParams, new Comparator() { + @Override + public int compare(CodegenParameter one, CodegenParameter another) { + if (one.isPathParam && another.isQueryParam) { + return -1; + } + if (one.isQueryParam && another.isPathParam){ + return 1; + } + + return 0; + } + }); + Iterator iterator = operation.allParams.iterator(); + while (iterator.hasNext()){ + CodegenParameter param = iterator.next(); + param.hasMore = iterator.hasNext(); + } + } } } + } // camelize path variables for Feign client diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaPlayFrameworkCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaPlayFrameworkCodegen.java index 452bfdd29e9..45aa089a97e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaPlayFrameworkCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaPlayFrameworkCodegen.java @@ -272,6 +272,12 @@ public class JavaPlayFrameworkCodegen extends AbstractJavaCodegen implements Bea } if (operation.returnType != null) { + if (operation.returnType.equals("Boolean")) { + operation.vendorExtensions.put("missingReturnInfoIfNeeded", "true"); + } + if (operation.returnType.equals("BigDecimal")) { + operation.vendorExtensions.put("missingReturnInfoIfNeeded", "1.0"); + } if (operation.returnType.startsWith("List")) { String rt = operation.returnType; int end = rt.lastIndexOf(">"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/KotlinClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/KotlinClientCodegen.java index fbd9a7ebdb3..e014f8a2504 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/KotlinClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/KotlinClientCodegen.java @@ -23,6 +23,7 @@ public class KotlinClientCodegen extends DefaultCodegen implements CodegenConfig protected String packageName = "io.swagger.client"; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; + protected CodegenConstants.ENUM_PROPERTY_NAMING_TYPE enumPropertyNaming = CodegenConstants.ENUM_PROPERTY_NAMING_TYPE.camelCase; /** * Constructs an instance of `KotlinClientCodegen`. @@ -56,17 +57,26 @@ public class KotlinClientCodegen extends DefaultCodegen implements CodegenConfig )); // this includes hard reserved words defined by https://github.com/JetBrains/kotlin/blob/master/core/descriptors/src/org/jetbrains/kotlin/renderer/KeywordStringsGenerated.java - // as well as select soft (contextual) keywords + // as well as keywords from https://kotlinlang.org/docs/reference/keyword-reference.html reservedWords = new HashSet(Arrays.asList( "abstract", + "annotation", "as", "break", "case", "catch", "class", + "companion", + "const", + "constructor", "continue", + "crossinline", + "data", + "delegate", "do", "else", + "enum", + "external", "false", "final", "finally", @@ -74,20 +84,33 @@ public class KotlinClientCodegen extends DefaultCodegen implements CodegenConfig "fun", "if", "in", + "infix", + "init", + "inline", + "inner", "interface", + "internal", "is", "it", + "lateinit", "lazy", + "noinline", "null", "object", + "open", + "operator", + "out", "override", "package", "private", "protected", "public", + "reified", "return", "sealed", "super", + "suspend", + "tailrec", "this", "throw", "true", @@ -96,6 +119,7 @@ public class KotlinClientCodegen extends DefaultCodegen implements CodegenConfig "typeof", "val", "var", + "vararg", "when", "while" )); @@ -149,12 +173,17 @@ public class KotlinClientCodegen extends DefaultCodegen implements CodegenConfig importMapping.put("LocalDate", "java.time.LocalDate"); importMapping.put("LocalTime", "java.time.LocalTime"); + specialCharReplacements.put(";", "Semicolon"); + cliOptions.clear(); cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC).defaultValue(sourceFolder)); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Client package name (e.g. io.swagger).").defaultValue(this.packageName)); cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, "Client package's organization (i.e. maven groupId).").defaultValue(groupId)); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, "Client artifact id (name of generated jar).").defaultValue(artifactId)); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "Client package version.").defaultValue(artifactVersion)); + + CliOption enumPropertyNamingOpt = new CliOption(CodegenConstants.ENUM_PROPERTY_NAMING, CodegenConstants.ENUM_PROPERTY_NAMING_DESC); + cliOptions.add(enumPropertyNamingOpt.defaultValue(enumPropertyNaming.name())); } public CodegenType getTag() { @@ -193,6 +222,10 @@ public class KotlinClientCodegen extends DefaultCodegen implements CodegenConfig public void processOpts() { super.processOpts(); + if (additionalProperties.containsKey(CodegenConstants.ENUM_PROPERTY_NAMING)) { + setEnumPropertyNaming((String) additionalProperties.get(CodegenConstants.ENUM_PROPERTY_NAMING)); + } + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } else { @@ -255,6 +288,27 @@ public class KotlinClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("infrastructure/Errors.kt.mustache", infrastructureFolder, "Errors.kt")); } + /** + * Sets the naming convention for Kotlin enum properties + * + * @param enumPropertyNamingType The string representation of the naming convention, as defined by {@link CodegenConstants.ENUM_PROPERTY_NAMING_TYPE} + */ + public void setEnumPropertyNaming(final String enumPropertyNamingType) { + try { + this.enumPropertyNaming = CodegenConstants.ENUM_PROPERTY_NAMING_TYPE.valueOf(enumPropertyNamingType); + } catch (IllegalArgumentException ex) { + StringBuilder sb = new StringBuilder(enumPropertyNamingType + " is an invalid enum property naming option. Please choose from:"); + for (CodegenConstants.ENUM_PROPERTY_NAMING_TYPE t : CodegenConstants.ENUM_PROPERTY_NAMING_TYPE.values()) { + sb.append("\n ").append(t.name()); + } + throw new RuntimeException(sb.toString()); + } + } + + public CodegenConstants.ENUM_PROPERTY_NAMING_TYPE getEnumPropertyNaming() { + return this.enumPropertyNaming; + } + @Override public String escapeUnsafeCharacters(String input) { return input.replace("*/", "*_/").replace("/*", "/_*"); @@ -289,7 +343,8 @@ public class KotlinClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String escapeReservedWord(String name) { - return "_" + name; + // TODO: Allow enum escaping as an option (e.g. backticks vs append/prepend underscore vs match model property escaping). + return String.format("`%s`", name); } /** @@ -300,12 +355,25 @@ public class KotlinClientCodegen extends DefaultCodegen implements CodegenConfig * @return capitalized model name */ @Override - public String toModelName(String name) { - if(!name.startsWith("kotlin.") && !name.startsWith("java.")) { - return initialCaps(modelNamePrefix + name + modelNameSuffix); - } else { + public String toModelName(final String name) { + // Allow for explicitly configured kotlin.* and java.* types + if (name.startsWith("kotlin.") || name.startsWith("java.")) { return name; } + + // If importMapping contains name, assume this is a legitimate model name. + if (importMapping.containsKey(name)) { + return importMapping.get(name); + } + + String modifiedName = name.replaceAll("\\.", ""); + modifiedName = sanitizeKotlinSpecificNames(modifiedName); + + if (reservedWords.contains(modifiedName)) { + modifiedName = escapeReservedWord(modifiedName); + } + + return titleCase(modifiedName); } /** @@ -386,4 +454,84 @@ public class KotlinClientCodegen extends DefaultCodegen implements CodegenConfig public Map postProcessModels(Map objs) { return postProcessModelsEnum(super.postProcessModels(objs)); } + + /** + * Return the sanitized variable name for enum + * + * @param value enum variable name + * @param datatype data type + * @return the sanitized variable name for enum + */ + @Override + public String toEnumVarName(String value, String datatype) { + String modified; + if (value.length() == 0) { + modified = "EMPTY"; + } else { + modified = value; + modified = sanitizeKotlinSpecificNames(modified); + } + + switch (getEnumPropertyNaming()) { + case original: + // NOTE: This is provided as a last-case allowance, but will still result in reserved words being escaped. + modified = value; + break; + case camelCase: + // NOTE: Removes hyphens and underscores + modified = camelize(modified, true); + break; + case PascalCase: + // NOTE: Removes hyphens and underscores + String result = camelize(modified); + modified = titleCase(result); + break; + case snake_case: + // NOTE: Removes hyphens + modified = underscore(modified); + break; + case UPPERCASE: + modified = modified.toUpperCase(); + break; + } + + if (reservedWords.contains(modified)) { + return escapeReservedWord(modified); + } + + return modified; + } + + private String titleCase(final String input) { + return input.substring(0, 1).toUpperCase() + input.substring(1); + } + + /** + * Sanitize against Kotlin specific naming conventions, which may differ from those required by {@link DefaultCodegen#sanitizeName}. + * + * @param name string to be sanitize + * @return sanitized string + */ + private String sanitizeKotlinSpecificNames(final String name) { + String word = name; + for (Map.Entry specialCharacters : specialCharReplacements.entrySet()) { + // Underscore is the only special character we'll allow + if (!specialCharacters.getKey().equals("_")) { + word = word.replaceAll("\\Q" + specialCharacters.getKey() + "\\E", specialCharacters.getValue()); + } + } + + // Fallback, replace unknowns with underscore. + word = word.replaceAll("\\W+", "_"); + if (word.matches("\\d.*")) { + word = "_" + word; + } + + // _, __, and ___ are reserved in Kotlin. Treat all names with only underscores consistently, regardless of count. + if (word.matches("^_*$")) { + word = word.replaceAll("\\Q_\\E", "Underscore"); + } + + return word; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java index 5e577b4c3de..daa1866db0e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java @@ -46,6 +46,7 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen { private static final String IMMUTABLE_OPTION = "immutable"; private static final String USE_BASE_PATH = "writeModulePath"; private static final String PACKAGE_CONTEXT = "packageContext"; + private static final String ASYNC_SERVER = "asyncServer"; private static final Map> propertyToSwaggerTypeMapping = createPropertyToSwaggerTypeMapping(); @@ -57,6 +58,9 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen { private final Multimap childrenByParent = ArrayListMultimap.create(); private final BiMap modelNameMapping = HashBiMap.create(); + /** If set to true, we will generate c# async endpoints and service interfaces */ + private boolean asyncServer = false; + public NancyFXServerCodegen() { outputFolder = "generated-code" + File.separator + getName(); apiTemplateFiles.put("api.mustache", ".cs"); @@ -87,6 +91,7 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen { addSwitch(RETURN_ICOLLECTION, RETURN_ICOLLECTION_DESC, returnICollection); addSwitch(IMMUTABLE_OPTION, "Enabled by default. If disabled generates model classes with setters", true); addSwitch(USE_BASE_PATH, "Enabled by default. If disabled, module paths will not mirror api base path", true); + addSwitch(ASYNC_SERVER, "Set to true to enable the generation of async routes/endpoints.", false); typeMapping.putAll(nodaTimeTypesMappings()); languageSpecificPrimitives.addAll(nodaTimePrimitiveTypes()); @@ -128,6 +133,10 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen { setPackageGuid((String) additionalProperties.get(OPTIONAL_PROJECT_GUID)); } + if (additionalProperties.containsKey(ASYNC_SERVER)) { + setAsyncServer(Boolean.valueOf(additionalProperties.get(ASYNC_SERVER).toString())); + } + additionalProperties.put("packageGuid", packageGuid); setupModelTemplate(); @@ -199,7 +208,11 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen { public void setPackageGuid(String packageGuid) { this.packageGuid = packageGuid; } - + + public void setAsyncServer(boolean asyncServer) { + this.asyncServer = asyncServer; + } + @Override public String apiFileFolder() { return outputFolder + File.separator + sourceFolder() + File.separator + API_NAMESPACE; 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 9a60d1a48b4..0954957f19f 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 @@ -67,6 +67,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig languageSpecificPrimitives.add("int"); languageSpecificPrimitives.add("float"); languageSpecificPrimitives.add("list"); + languageSpecificPrimitives.add("dict"); languageSpecificPrimitives.add("bool"); languageSpecificPrimitives.add("str"); languageSpecificPrimitives.add("datetime"); @@ -189,21 +190,16 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig setPackageUrl((String) additionalProperties.get(PACKAGE_URL)); } - String swaggerFolder = packageName; - - modelPackage = swaggerFolder + File.separatorChar + "models"; - apiPackage = swaggerFolder + File.separatorChar + "apis"; - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); 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("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("configuration.mustache", packageName, "configuration.py")); + supportingFiles.add(new SupportingFile("__init__package.mustache", packageName, "__init__.py")); + supportingFiles.add(new SupportingFile("__init__model.mustache", packageName + File.separatorChar + modelPackage, "__init__.py")); + supportingFiles.add(new SupportingFile("__init__api.mustache", packageName + File.separatorChar + apiPackage, "__init__.py")); if(Boolean.FALSE.equals(excludeTests)) { supportingFiles.add(new SupportingFile("__init__test.mustache", testFolder, "__init__.py")); @@ -212,23 +208,42 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml")); supportingFiles.add(new SupportingFile("setup.mustache", "", "setup.py")); - supportingFiles.add(new SupportingFile("api_client.mustache", swaggerFolder, "api_client.py")); + supportingFiles.add(new SupportingFile("api_client.mustache", packageName, "api_client.py")); if ("asyncio".equals(getLibrary())) { - supportingFiles.add(new SupportingFile("asyncio/rest.mustache", swaggerFolder, "rest.py")); + supportingFiles.add(new SupportingFile("asyncio/rest.mustache", packageName, "rest.py")); additionalProperties.put("asyncio", "true"); } else if ("tornado".equals(getLibrary())) { - supportingFiles.add(new SupportingFile("tornado/rest.mustache", swaggerFolder, "rest.py")); + supportingFiles.add(new SupportingFile("tornado/rest.mustache", packageName, "rest.py")); additionalProperties.put("tornado", "true"); } else { - supportingFiles.add(new SupportingFile("rest.mustache", swaggerFolder, "rest.py")); + supportingFiles.add(new SupportingFile("rest.mustache", packageName, "rest.py")); } + + modelPackage = packageName + "." + modelPackage; + apiPackage = packageName + "." + apiPackage; + } private static String dropDots(String str) { return str.replaceAll("\\.", "_"); } + @Override + public String toModelImport(String name) { + String modelImport; + if (StringUtils.startsWithAny(name,"import", "from")) { + modelImport = name; + } else { + modelImport = "from "; + if (!"".equals(modelPackage())) { + modelImport += modelPackage() + "."; + } + modelImport += toModelFilename(name)+ " import " + name; + } + return modelImport; + } + @Override public Map postProcessModels(Map objs) { // process enum in models diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java index 01dd7dff24d..473ad490479 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java @@ -99,8 +99,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("file", "File"); typeMapping.put("binary", "Vec"); typeMapping.put("ByteArray", "String"); - // TODO what should 'object' mapped to - typeMapping.put("object", "Object"); + typeMapping.put("object", "Value"); // no need for rust //importMapping = new HashMap(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustServerCodegen.java new file mode 100755 index 00000000000..301e6532038 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustServerCodegen.java @@ -0,0 +1,963 @@ +package io.swagger.codegen.languages; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Lists; +import com.google.common.collect.Multimap; +import io.swagger.codegen.*; +import io.swagger.models.*; +import io.swagger.models.parameters.BodyParameter; +import io.swagger.models.parameters.Parameter; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.*; +import io.swagger.util.Yaml; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.Map.Entry; +import org.apache.commons.lang3.StringUtils; + +public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { + + private static final Logger LOGGER = LoggerFactory.getLogger(RustServerCodegen.class); + + private HashMap modelXmlNames = new HashMap(); + + protected String apiVersion = "1.0.0"; + protected int serverPort = 8080; + protected String projectName = "swagger-server"; + protected String apiPath = "rust-server"; + protected String packageName; + protected String packageVersion; + protected String externCrateName; + + public RustServerCodegen() { + super(); + + // set the output folder here + outputFolder = "generated-code/rust-server"; + + /* + * Models. You can write model files using the modelTemplateFiles map. + * if you want to create one template for file, you can do so here. + * for multiple files for model, just put another entry in the `modelTemplateFiles` with + * a different extension + */ + modelTemplateFiles.clear(); + + /* + * Api classes. You can write classes for each Api file with the apiTemplateFiles map. + * as with models, add multiple entries with different extensions for multiple files per + * class + */ + apiTemplateFiles.clear(); + + /* + * Template Location. This is the location which templates will be read from. The generator + * will use the resource stream to attempt to read the templates. + */ + embeddedTemplateDir = templateDir = "rust-server"; + + /* + * Reserved words. Override this with reserved words specific to your language + */ + setReservedWordsLowerCase( + Arrays.asList( + // From https://doc.rust-lang.org/grammar.html#keywords + "abstract", "alignof", "as", "become", "box", "break", "const", + "continue", "crate", "do", "else", "enum", "extern", "false", + "final", "fn", "for", "if", "impl", "in", "let", "loop", "macro", + "match", "mod", "move", "mut", "offsetof", "override", "priv", + "proc", "pub", "pure", "ref", "return", "Self", "self", "sizeof", + "static", "struct", "super", "trait", "true", "type", "typeof", + "unsafe", "unsized", "use", "virtual", "where", "while", "yield" + ) + ); + + defaultIncludes = new HashSet( + Arrays.asList( + "map", + "array") + ); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "bool", + "char", + "i8", + "i16", + "i32", + "i64", + "u8", + "u16", + "u32", + "u64", + "isize", + "usize", + "f32", + "f64", + "str") + ); + + instantiationTypes.clear(); + instantiationTypes.put("array", "Vec"); + instantiationTypes.put("map", "Map"); + + typeMapping.clear(); + typeMapping.put("number", "f64"); + typeMapping.put("integer", "i32"); + typeMapping.put("long", "i64"); + typeMapping.put("float", "f32"); + typeMapping.put("double", "f64"); + typeMapping.put("string", "String"); + typeMapping.put("UUID", "uuid::Uuid"); + typeMapping.put("byte", "u8"); + typeMapping.put("ByteArray", "swagger::ByteArray"); + typeMapping.put("binary", "swagger::ByteArray"); + typeMapping.put("boolean", "bool"); + typeMapping.put("date", "chrono::DateTime"); + typeMapping.put("DateTime", "chrono::DateTime"); + typeMapping.put("password", "String"); + typeMapping.put("File", "Box, Error=Error> + Send>"); + typeMapping.put("file", "Box, Error=Error> + Send>"); + typeMapping.put("array", "Vec"); + typeMapping.put("map", "HashMap"); + + importMapping = new HashMap(); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, + "Rust crate name (convention: snake_case).") + .defaultValue("swagger_client")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, + "Rust crate version.") + .defaultValue("1.0.0")); + + /* + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("apiVersion", apiVersion); + additionalProperties.put("serverPort", serverPort); + additionalProperties.put("apiPath", apiPath); + + /* + * Supporting Files. You can write single files for the generator with the + * entire object tree available. If the input file has a suffix of `.mustache + * it will be processed by the template engine. Otherwise, it will be copied + */ + supportingFiles.add(new SupportingFile("swagger.mustache", "api", "swagger.yaml")); + supportingFiles.add(new SupportingFile("Cargo.mustache", "", "Cargo.toml")); + supportingFiles.add(new SupportingFile("cargo-config", ".cargo", "config")); + supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); + supportingFiles.add(new SupportingFile("lib.mustache", "src", "lib.rs")); + supportingFiles.add(new SupportingFile("models.mustache", "src", "models.rs")); + supportingFiles.add(new SupportingFile("server.mustache", "src", "server.rs")); + supportingFiles.add(new SupportingFile("client.mustache", "src", "client.rs")); + supportingFiles.add(new SupportingFile("mimetypes.mustache", "src", "mimetypes.rs")); + supportingFiles.add(new SupportingFile("example-server.mustache", "examples", "server.rs")); + supportingFiles.add(new SupportingFile("example-client.mustache", "examples", "client.rs")); + supportingFiles.add(new SupportingFile("example-server_lib.mustache", "examples/server_lib", "mod.rs")); + supportingFiles.add(new SupportingFile("example-ca.pem", "examples", "ca.pem")); + supportingFiles.add(new SupportingFile("example-server-chain.pem", "examples", "server-chain.pem")); + supportingFiles.add(new SupportingFile("example-server-key.pem", "examples", "server-key.pem")); + writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } + else { + setPackageName("swagger_client"); + } + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); + } + else { + setPackageVersion("1.0.0"); + } + + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); + additionalProperties.put("externCrateName", externCrateName); + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + + // Also set the extern crate name, which has any '-' replace with a '_'. + this.externCrateName = packageName.replace('-', '_'); + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + + @Override + public String apiPackage() { + return apiPath; + } + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType + */ + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + /** + * Configures a friendly name for the generator. This will be used by the generator + * to select the library with the -l flag. + * + * @return the friendly name for the generator + */ + @Override + public String getName() { + return "rust-server"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message + */ + @Override + public String getHelp() { + return "Generates a Rust client/server library (beta) using the swagger-codegen project."; + } + + @Override + public void preprocessSwagger(Swagger swagger) { + Info info = swagger.getInfo(); + List versionComponents = new ArrayList(Arrays.asList(info.getVersion().split("[.]"))); + if (versionComponents.size() < 1) { + versionComponents.add("1"); + } + while (versionComponents.size() < 3) { + versionComponents.add("0"); + } + info.setVersion(StringUtils.join(versionComponents, ".")); + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "default"; + } + return underscore(name); + } + + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping + * those terms here. This logic is only called if a variable matches the reseved words + * + * @return the escaped term + */ + @Override + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; // add an underscore to the name + } + + /** + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated + */ + @Override + public String apiFileFolder() { + return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String toModelName(String name) { + // camelize the model name + // phone_number => PhoneNumber + String camelizedName = camelize(toModelFilename(name)); + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(camelizedName)) { + camelizedName = "Model" + camelizedName; + LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + camelizedName); + } + + // model name starts with number + else if (name.matches("^\\d.*")) { + // e.g. 200Response => Model200Response (after camelize) + camelizedName = "Model" + camelizedName; + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelizedName); + } + + return camelizedName; + + } + + @Override + public String toParamName(String name) { + // should be the same as variable name (stolen from RubyClientCodegen) + return toVarName(name); + } + + @Override + public String toVarName(String name) { + String sanitizedName = super.sanitizeName(name); + // for reserved word or word starting with number, append _ + if (isReservedWord(sanitizedName) || sanitizedName.matches("^\\d.*")) { + sanitizedName = escapeReservedWord(sanitizedName); + } + + return underscore(sanitizedName); + } + + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + operationId = "call_" + operationId; + } + + return camelize(operationId); + } + + @Override + public String toModelFilename(String name) { + if (!StringUtils.isEmpty(modelNamePrefix)) { + name = modelNamePrefix + "_" + name; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + name = name + "_" + modelNameSuffix; + } + + name = sanitizeName(name); + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + name = "model_" + name; // e.g. return => ModelReturn (after camelize) + } + + return underscore(name); + } + + @Override + public String toEnumName(CodegenProperty property) { + return sanitizeName(camelize(property.name)) + "Enum"; + } + + @Override + public String toEnumVarName(String value, String datatype) { + String var = null; + if (value.length() == 0) { + var = "EMPTY"; + } + + // for symbol, e.g. $, # + else if (getSymbolName(value) != null) { + var = getSymbolName(value).toUpperCase(); + } + + // number + else if ("Integer".equals(datatype) || "Long".equals(datatype) || + "Float".equals(datatype) || "Double".equals(datatype)) { + String varName = "NUMBER_" + value; + varName = varName.replaceAll("-", "MINUS_"); + varName = varName.replaceAll("\\+", "PLUS_"); + varName = varName.replaceAll("\\.", "_DOT_"); + var = varName; + } + + // string + var = value.replaceAll("\\W+", "_").toUpperCase(); + if (var.matches("\\d.*")) { + var = "_" + var; + } else { + var = sanitizeName(var); + } + return var; + } + + @Override + public String toEnumValue(String value, String datatype) { + if ("Integer".equals(datatype) || "Long".equals(datatype) || + "Float".equals(datatype) || "Double".equals(datatype)) { + return value; + } else { + return "\"" + escapeText(value) + "\""; + } + } + + @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. PetApi.go => pet_api.go + return underscore(name); + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); + op.vendorExtensions.put("operation_id", underscore(op.operationId)); + op.vendorExtensions.put("uppercase_operation_id", underscore(op.operationId).toUpperCase()); + op.vendorExtensions.put("path", op.path.replace("{", ":").replace("}", "")); + op.vendorExtensions.put("HttpMethod", Character.toUpperCase(op.httpMethod.charAt(0)) + op.httpMethod.substring(1).toLowerCase()); + op.vendorExtensions.put("httpmethod", op.httpMethod.toLowerCase()); + for (CodegenParameter param : op.allParams) { + String example = null; + + if (param.isString) { + if (param.dataFormat != null && param.dataFormat.equals("byte")) { + param.vendorExtensions.put("formatString", "\\\"{:?}\\\""); + example = "swagger::ByteArray(\"" + ((param.example != null) ? param.example : "") + "\".to_string().into_bytes())"; + } else { + param.vendorExtensions.put("formatString", "\\\"{}\\\""); + example = "\"" + ((param.example != null) ? param.example : "") + "\".to_string()"; + } + } else if (param.isPrimitiveType) { + if ((param.isByteArray) || + (param.isBinary)) { + // Binary primitive types don't implement `Display`. + param.vendorExtensions.put("formatString", "{:?}"); + example = "swagger::ByteArray(Vec::from(\"" + ((param.example != null) ? param.example : "") + "\"))"; + } else { + param.vendorExtensions.put("formatString", "{}"); + example = (param.example != null) ? param.example : ""; + } + } else if (param.isListContainer) { + param.vendorExtensions.put("formatString", "{:?}"); + example = (param.example != null) ? param.example : "&Vec::new()"; + } else if (param.isFile) { + param.vendorExtensions.put("formatString", "{:?}"); + op.vendorExtensions.put("hasFile", true); + additionalProperties.put("apiHasFile", true); + example = "Box::new(stream::once(Ok(b\"hello\".to_vec()))) as Box + Send>"; + } else { + param.vendorExtensions.put("formatString", "{:?}"); + if (param.example != null) { + example = "serde_json::from_str::<" + param.dataType + ">(\"" + param.example + "\").expect(\"Failed to parse JSON example\")"; + } + } + + if (param.required) { + if (example != null) { + param.vendorExtensions.put("example", example); + } else if (param.isListContainer) { + // Use the empty list if we don't have an example + param.vendorExtensions.put("example", "&Vec::new()"); + } + else { + // If we don't have an example that we can provide, we need to disable the client example, as it won't build. + param.vendorExtensions.put("example", "???"); + op.vendorExtensions.put("noClientExample", Boolean.TRUE); + } + } else if ((param.dataFormat != null)&&((param.dataFormat.equals("date-time")) || (param.dataFormat.equals("date")))) { + param.vendorExtensions.put("formatString", "{:?}"); + param.vendorExtensions.put("example", "None"); + } else { + // Not required, so override the format string and example + param.vendorExtensions.put("formatString", "{:?}"); + if (param.isFile) { + // Optional file types are wrapped in a future + param.vendorExtensions.put("example", (example != null) ? "Box::new(future::ok(Some(" + example + "))) as Box + Send>" : "None"); + } else { + param.vendorExtensions.put("example", (example != null) ? "Some(" + example + ")" : "None"); + } + } + } + + List consumes = new ArrayList(); + if (operation.getConsumes() != null) { + if (operation.getConsumes().size() > 0) { + // use consumes defined in the operation + consumes = operation.getConsumes(); + } + } else if (swagger != null && swagger.getConsumes() != null && swagger.getConsumes().size() > 0) { + // use consumes defined globally + consumes = swagger.getConsumes(); + LOGGER.debug("No consumes defined in operation. Using global consumes (" + swagger.getConsumes() + ") for " + op.operationId); + } + + boolean consumesXml = false; + // if "consumes" is defined (per operation or using global definition) + if (consumes != null && !consumes.isEmpty()) { + List> c = new ArrayList>(); + for (String key : consumes) { + Map mediaType = new HashMap(); + String mimeType = processMimeType(key); + + if (mimeType.startsWith("Application/Xml")) { + additionalProperties.put("usesXml", true); + consumesXml = true; + } + + mediaType.put("mediaType", mimeType); + c.add(mediaType); + } + op.consumes = c; + op.hasConsumes = true; + } + + List produces = new ArrayList(); + if (operation.getProduces() != null) { + if (operation.getProduces().size() > 0) { + // use produces defined in the operation + produces = operation.getProduces(); + } + } else if (swagger != null && swagger.getProduces() != null && swagger.getProduces().size() > 0) { + // use produces defined globally + produces = swagger.getProduces(); + LOGGER.debug("No produces defined in operation. Using global produces (" + swagger.getProduces() + ") for " + op.operationId); + } + + boolean producesXml = false; + if (produces != null && !produces.isEmpty()) { + List> c = new ArrayList>(); + for (String key : produces) { + Map mediaType = new HashMap(); + String mimeType = processMimeType(key); + + if (mimeType.startsWith("Application/Xml")) { + additionalProperties.put("usesXml", true); + producesXml = true; + } + + mediaType.put("mediaType", mimeType); + c.add(mediaType); + } + op.produces = c; + op.hasProduces = true; + } + + if (op.bodyParam != null) { + + if (paramHasXmlNamespace(op.bodyParam, definitions)){ + op.bodyParam.vendorExtensions.put("has_namespace", "true"); + } + for (String key : definitions.keySet()) { + op.bodyParam.vendorExtensions.put("model_key", key); + } + + op.bodyParam.vendorExtensions.put("uppercase_operation_id", underscore(op.operationId).toUpperCase()); + if (consumesXml) { + op.bodyParam.vendorExtensions.put("consumesXml", true); + } + + } + for (CodegenParameter param : op.bodyParams) { + + if (paramHasXmlNamespace(param, definitions)){ + param.vendorExtensions.put("has_namespace", "true"); + } + + param.vendorExtensions.put("uppercase_operation_id", underscore(op.operationId).toUpperCase()); + + if (consumesXml) { + param.vendorExtensions.put("consumesXml", true); + } + } + for (CodegenParameter param : op.headerParams) { + // Give header params a name in camel case. CodegenParameters don't have a nameInCamelCase property. + param.vendorExtensions.put("typeName", toModelName(param.baseName)); + } + for (CodegenResponse rsp : op.responses) { + rsp.message = camelize(rsp.message.split("[^A-Za-z ]")[0].replace(" ", "_")); + rsp.vendorExtensions.put("uppercase_operation_id", underscore(op.operationId).toUpperCase()); + rsp.vendorExtensions.put("uppercase_message", underscore(rsp.message).toUpperCase()); + if (rsp.dataType != null) { + rsp.vendorExtensions.put("uppercase_data_type", (rsp.dataType.replace("models::", "")).toUpperCase()); + + if (producesXml) { + rsp.vendorExtensions.put("producesXml", true); + } + + // Check whether we're returning an object with a defined XML namespace. + Object property = rsp.schema; + if ((property != null) && (property instanceof RefProperty)){ + + RefProperty refProperty = (RefProperty) property; + String refName = refProperty.get$ref(); + if (refName.indexOf("#/definitions/") == 0) { + refName = refName.substring("#/definitions/".length()); + } + + Model model = definitions.get(refName); + + if ((model != null) && (model instanceof ModelImpl)) { + Xml xml = ((ModelImpl) model).getXml(); + if ((xml != null) && (xml.getNamespace() != null)){ + rsp.vendorExtensions.put("has_namespace", "true"); + } + } + } + } + for (CodegenProperty header : rsp.headers) { + header.nameInCamelCase = toModelName(header.baseName); + } + } + for (CodegenProperty header : op.responseHeaders) { + header.nameInCamelCase = toModelName(header.baseName); + } + + return op; + } + + @Override + public boolean isDataTypeFile(final String dataType) { + return dataType != null && dataType.equals(typeMapping.get("File").toString()); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + String innerType = getTypeDeclaration(inner); + StringBuilder typeDeclaration = new StringBuilder(typeMapping.get("array")).append("<"); + if (inner instanceof RefProperty) { + typeDeclaration.append("models::"); + } + typeDeclaration.append(innerType).append(">"); + return typeDeclaration.toString(); + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + String innerType = getTypeDeclaration(inner); + StringBuilder typeDeclaration = new StringBuilder(typeMapping.get("map")).append("<").append(typeMapping.get("string")).append(", "); + if (inner instanceof RefProperty) { + typeDeclaration.append("models::"); + } + typeDeclaration.append(innerType).append(">"); + return typeDeclaration.toString(); + } else if (p instanceof RefProperty) { + String datatype; + try { + RefProperty r = (RefProperty) p; + datatype = r.get$ref(); + if (datatype.indexOf("#/definitions/") == 0) { + datatype = toModelName(datatype.substring("#/definitions/".length())); + } + } catch (Exception e) { + LOGGER.warn("Error obtaining the datatype from RefProperty:" + p + ". Datatype default to Object"); + datatype = "Object"; + LOGGER.error(e.getMessage(), e); + } + return datatype; + } else if (p instanceof FileProperty) { + return typeMapping.get("File").toString(); + } + return super.getTypeDeclaration(p); + } + + @Override + public CodegenParameter fromParameter(Parameter param, Set imports) { + CodegenParameter parameter = super.fromParameter(param, imports); + if(param instanceof BodyParameter) { + BodyParameter bp = (BodyParameter) param; + Model model = bp.getSchema(); + if (model instanceof RefModel) { + String name = ((RefModel) model).getSimpleRef(); + name = toModelName(name); + // We need to be able to look up the model in the model definitions later. + parameter.vendorExtensions.put("uppercase_data_type", name.toUpperCase()); + + name = "models::" + getTypeDeclaration(name); + parameter.baseType = name; + parameter.dataType = name; + + String refName = ((RefModel) model).get$ref(); + if (refName.indexOf("#/definitions/") == 0) { + refName = refName.substring("#/definitions/".length()); + } + parameter.vendorExtensions.put("refName", refName); + + } else if (model instanceof ModelImpl) { + parameter.vendorExtensions.put("refName", ((ModelImpl) model).getName()); + } + } + return parameter; + } + + @Override + public CodegenProperty fromProperty(String name, Property p) { + CodegenProperty property = super.fromProperty(name, p); + if (p instanceof RefProperty) { + property.datatype = "models::" + property.datatype; + } + return property; + } + + @Override + public String toInstantiationType(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return instantiationTypes.get("array") + "<" + getSwaggerType(inner) + ">"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return instantiationTypes.get("map") + "<" + typeMapping.get("string") + ", " + getSwaggerType(inner) + ">"; + } else { + return null; + } + } + + @Override + public CodegenModel fromModel(String name, Model model) { + return fromModel(name, model, null); + } + + @Override + public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + CodegenModel mdl = super.fromModel(name, model, allDefinitions); + mdl.vendorExtensions.put("upperCaseName", name.toUpperCase()); + if (model instanceof ModelImpl) { + ModelImpl modelImpl = (ModelImpl) model; + mdl.dataType = typeMapping.get(modelImpl.getType()); + } + if (model instanceof ArrayModel) { + ArrayModel am = (ArrayModel) model; + if ((am.getItems() != null) && + (am.getItems().getXml() != null)){ + + // If this model's items require wrapping in xml, squirrel + // away the xml name so we can insert it into the relevant model fields. + String xmlName = am.getItems().getXml().getName(); + if (xmlName != null) { + mdl.vendorExtensions.put("itemXmlName", xmlName); + modelXmlNames.put("models::" + mdl.classname, xmlName); + } + } + mdl.arrayModelType = toModelName(mdl.arrayModelType); + } + + if (mdl.xmlNamespace != null) { + additionalProperties.put("usesXmlNamespaces", true); + } + + return mdl; + } + + @Override + public Map postProcessAllModels(Map objs){ + Map newObjs = super.postProcessAllModels(objs); + + //Index all CodegenModels by model name. + HashMap allModels = new HashMap(); + for (Entry entry : objs.entrySet()) { + String modelName = toModelName(entry.getKey()); + Map inner = (Map) entry.getValue(); + List> models = (List>) inner.get("models"); + for (Map mo : models) { + CodegenModel cm = (CodegenModel) mo.get("model"); + allModels.put(modelName, cm); + } + } + + for (Entry entry : allModels.entrySet()){ + String modelName = entry.getKey(); + CodegenModel model = entry.getValue(); + + for(CodegenProperty prop : model.vars){ + String xmlName = modelXmlNames.get(prop.datatype); + if (xmlName != null){ + prop.vendorExtensions.put("itemXmlName", xmlName); + } + } + } + + return newObjs; + } + + @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); + } + + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + StringProperty dp = (StringProperty) p; + if (dp.getDefault() != null) { + return "\"" + dp.getDefault() + "\".to_string()"; + } + } else if (p instanceof BooleanProperty) { + BooleanProperty dp = (BooleanProperty) p; + if (dp.getDefault() != null) { + if (dp.getDefault().toString().equalsIgnoreCase("false")) + return "false"; + else + return "true"; + } + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof IntegerProperty) { + IntegerProperty dp = (IntegerProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } + + return null; + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + super.postProcessModelProperty(model, property); + if(!languageSpecificPrimitives.contains(property.datatype)) { + // If we use a more qualified model name, then only camelize the actual type, not the qualifier. + if(property.datatype.contains(":")) { + int position = property.datatype.lastIndexOf(":"); + property.datatype = property.datatype.substring(0, position) + camelize(property.datatype.substring(position)); + } else { + property.datatype = camelize(property.datatype, false); + } + } + + // Handle custom unsigned integer formats. + if ("integer".equals(property.baseType)) { + if ("uint32".equals(property.dataFormat)) { + property.datatype = "u32"; + } else if ("uint64".equals(property.dataFormat)) { + property.datatype = "u64"; + } + } + + property.name = underscore(property.name); + + if (!property.required) { + property.defaultValue = (property.defaultValue != null) ? "Some(" + property.defaultValue + ")" : "None"; + } + } + + @Override + public Map postProcessModels(Map objs) { + return super.postProcessModelsEnum(objs); + + } + + private boolean paramHasXmlNamespace(CodegenParameter param, Map definitions){ + Object refName = param.vendorExtensions.get("refName"); + + if ((refName != null) && (refName instanceof String)) { + String name = (String) refName; + Model model = definitions.get(name); + + if ((model != null) && (model instanceof ModelImpl)) { + Xml xml = ((ModelImpl) model).getXml(); + if ((xml != null) && (xml.getNamespace() != null)) { + return true; + } + } + } + return false; + } + + private String processMimeType(String mimeType){ + // Transform mime type into a form that the hyper mime! macro can handle. + String result = ""; + + String[] split_attributes = mimeType.split(";"); + String media = split_attributes[0]; + String[] mediaTypes = media.split("/"); + + if (mediaTypes.length == 2) { + + if (mediaTypes[0].equals("*")){ + result += "Star"; + } else { + result += escapeText(escapeQuotationMark(initialCaps(mediaTypes[0]))); + } + + result += "/"; + + if (mediaTypes[1].equals("*")) { + result += "Star"; + } else { + result += escapeText(escapeQuotationMark(initialCaps(mediaTypes[1]))); + } + } else { + LOGGER.error("Failed to parse media type: " + + mimeType + + ", media types should have exactly one /"); + } + + if (split_attributes.length == 2) { + String attributes = ""; + String[] attrs = split_attributes[1].split(","); + + for (String attr : attrs) { + String[] keyValuePair =attr.split("="); + if (keyValuePair.length == 2) { + attributes += "(\"" + + escapeText(escapeQuotationMark(keyValuePair[0].trim())) + + "\")=(\"" + + escapeText(escapeQuotationMark(keyValuePair[1].trim())) + + "\")"; + } else { + LOGGER.error("Failed to parse parameter attributes: " + + split_attributes[1] + + ", attributes must be a comma separated list of 'key=value' pairs"); + } + } + result += "; " + attributes; + } + + return result; + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java index 918b681d6ed..703555f1153 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java @@ -246,8 +246,6 @@ public class SpringCodegen extends AbstractJavaCodegen additionalProperties.put(SINGLE_CONTENT_TYPES, "true"); this.setSingleContentTypes(true); } - additionalProperties.put("useSpringCloudClient", true); - } else { apiTemplateFiles.put("apiController.mustache", "Controller.java"); supportingFiles.add(new SupportingFile("apiException.mustache", diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SymfonyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SymfonyServerCodegen.java index 87ce66f16a7..ae9cbd81fdf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SymfonyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SymfonyServerCodegen.java @@ -32,7 +32,9 @@ public class SymfonyServerCodegen extends AbstractPhpCodegen implements CodegenC protected String bundleExtensionName; protected String bundleAlias; protected String controllerDirName = "Controller"; + protected String serviceDirName = "Service"; protected String controllerPackage; + protected String servicePackage; protected Boolean phpLegacySupport = Boolean.TRUE; protected HashSet typeHintable; @@ -74,7 +76,9 @@ public class SymfonyServerCodegen extends AbstractPhpCodegen implements CodegenC modelDocPath = docsBasePath + File.separator + modelDirName; outputFolder = "generated-code" + File.separator + "php"; apiTemplateFiles.put("api_controller.mustache", ".php"); - modelTestTemplateFiles.put("model_test.mustache", ".php"); + modelTestTemplateFiles.put("testing/model_test.mustache", ".php"); + apiTestTemplateFiles = new HashMap(); + apiTestTemplateFiles.put("testing/api_test.mustache", ".php"); embeddedTemplateDir = templateDir = "php-symfony"; setReservedWordsLowerCase( @@ -105,13 +109,10 @@ public class SymfonyServerCodegen extends AbstractPhpCodegen implements CodegenC ) ); - //instantiationTypes.put("array", "array"); - //instantiationTypes.put("map", "map"); - defaultIncludes = new HashSet( Arrays.asList( "\\DateTime", - "\\SplFileObject" + "UploadedFile" ) ); @@ -135,7 +136,7 @@ public class SymfonyServerCodegen extends AbstractPhpCodegen implements CodegenC typeMapping.put("boolean", "bool"); typeMapping.put("Date", "\\DateTime"); typeMapping.put("DateTime", "\\DateTime"); - typeMapping.put("file", "\\SplFileObject"); + typeMapping.put("file", "UploadedFile"); typeMapping.put("map", "array"); typeMapping.put("array", "array"); typeMapping.put("list", "array"); @@ -242,6 +243,7 @@ public class SymfonyServerCodegen extends AbstractPhpCodegen implements CodegenC additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); additionalProperties.put("controllerPackage", controllerPackage); + additionalProperties.put("servicePackage", servicePackage); additionalProperties.put("apiTestsPackage", apiTestsPackage); additionalProperties.put("modelTestsPackage", modelTestsPackage); @@ -275,14 +277,28 @@ public class SymfonyServerCodegen extends AbstractPhpCodegen implements CodegenC supportingFiles.add(new SupportingFile("Extension.mustache", dependencyInjectionDir, bundleExtensionName + ".php")); supportingFiles.add(new SupportingFile("ApiPass.mustache", dependencyInjectionDir + File.separator + "Compiler", bundleName + "ApiPass.php")); supportingFiles.add(new SupportingFile("ApiServer.mustache", toPackagePath(apiPackage, srcBasePath), "ApiServer.php")); - supportingFiles.add(new SupportingFile("ModelSerializer.mustache", toPackagePath(modelPackage, srcBasePath), "ModelSerializer.php")); - supportingFiles.add(new SupportingFile("ModelInterface.mustache", toPackagePath(modelPackage, srcBasePath), "ModelInterface.php")); + + // Serialization components + supportingFiles.add(new SupportingFile("serialization/SerializerInterface.mustache", toPackagePath(servicePackage, srcBasePath), "SerializerInterface.php")); + supportingFiles.add(new SupportingFile("serialization/JmsSerializer.mustache", toPackagePath(servicePackage, srcBasePath), "JmsSerializer.php")); + supportingFiles.add(new SupportingFile("serialization/StrictJsonDeserializationVisitor.mustache", toPackagePath(servicePackage, srcBasePath), "StrictJsonDeserializationVisitor.php")); + supportingFiles.add(new SupportingFile("serialization/TypeMismatchException.mustache", toPackagePath(servicePackage, srcBasePath), "TypeMismatchException.php")); + // Validation components + supportingFiles.add(new SupportingFile("validation/ValidatorInterface.mustache", toPackagePath(servicePackage, srcBasePath), "ValidatorInterface.php")); + supportingFiles.add(new SupportingFile("validation/SymfonyValidator.mustache", toPackagePath(servicePackage, srcBasePath), "SymfonyValidator.php")); + + // Testing components + supportingFiles.add(new SupportingFile("testing/phpunit.xml.mustache", getPackagePath(), "phpunit.xml.dist")); + supportingFiles.add(new SupportingFile("testing/pom.xml", getPackagePath(), "pom.xml")); + supportingFiles.add(new SupportingFile("testing/AppKernel.php", toPackagePath(testsPackage, srcBasePath), "AppKernel.php")); + supportingFiles.add(new SupportingFile("testing/test_config.yml", toPackagePath(testsPackage, srcBasePath), "test_config.yml")); + supportingFiles.add(new SupportingFile("routing.mustache", configDir, "routing.yml")); supportingFiles.add(new SupportingFile("services.mustache", configDir, "services.yml")); supportingFiles.add(new SupportingFile("composer.mustache", getPackagePath(), "composer.json")); supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php")); supportingFiles.add(new SupportingFile("README.mustache", getPackagePath(), "README.md")); - supportingFiles.add(new SupportingFile("phpunit.xml.mustache", getPackagePath(), "phpunit.xml.dist")); + supportingFiles.add(new SupportingFile(".travis.yml", getPackagePath(), ".travis.yml")); supportingFiles.add(new SupportingFile(".php_cs", getPackagePath(), ".php_cs")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", getPackagePath(), "git_push.sh")); @@ -329,6 +345,14 @@ public class SymfonyServerCodegen extends AbstractPhpCodegen implements CodegenC if (!typeHint.isEmpty()) { param.vendorExtensions.put("x-parameterType", typeHint); } + + // Quote default values for strings + // @todo: The default values for headers, forms and query params are handled + // in DefaultCodegen fromParameter with no real possibility to override + // the functionality. Thus we are handling quoting of string values here + if (param.dataType.equals("string") && param.defaultValue != null && !param.defaultValue.isEmpty()) { + param.defaultValue = "'"+param.defaultValue+"'"; + } } for (CodegenResponse response : op.responses) { @@ -340,9 +364,6 @@ public class SymfonyServerCodegen extends AbstractPhpCodegen implements CodegenC if (response.dataType != null) { final String dataType = extractSimpleName(response.dataType); response.vendorExtensions.put("x-simpleName", dataType); - // if (!typeMapping.containsValue(dataType)) { - // imports.add(response.dataType.replaceFirst("\\[\\]$", "")); - // } } } @@ -364,19 +385,15 @@ public class SymfonyServerCodegen extends AbstractPhpCodegen implements CodegenC ArrayList modelsArray = (ArrayList) objs.get("models"); Map models = (Map) modelsArray.get(0); CodegenModel model = (CodegenModel) models.get("model"); - HashSet imports = new HashSet<>(); // Simplify model var type for (CodegenProperty var : model.vars) { if (var.datatype != null) { - final String importType = var.datatype.replaceFirst("\\[\\]$", ""); - final String dataType = extractSimpleName(var.datatype); - final boolean isScalarType = typeMapping.containsValue(importType); - var.vendorExtensions.put("x-fullType", var.datatype); - if (!isScalarType) { - var.vendorExtensions.put("x-typeAnnotation", dataType.endsWith("[]") ? "array" : dataType); - imports.add(importType); - var.datatype = dataType; + // Determine if the paramter type is supported as a type hint and make it available + // to the templating engine + String typeHint = getTypeHint(var.datatype); + if (!typeHint.isEmpty()) { + var.vendorExtensions.put("x-parameterType", typeHint); } if (var.isBoolean) { @@ -385,8 +402,6 @@ public class SymfonyServerCodegen extends AbstractPhpCodegen implements CodegenC } } - objs.put("useStatements", new ArrayList<>(imports)); - return objs; } @@ -425,6 +440,7 @@ public class SymfonyServerCodegen extends AbstractPhpCodegen implements CodegenC apiTestsPackage = testsPackage + "\\" + apiDirName; modelTestsPackage = testsPackage + "\\" + modelDirName; controllerPackage = invokerPackage + "\\" + controllerDirName; + servicePackage = invokerPackage + "\\" + serviceDirName; } @Override @@ -485,6 +501,26 @@ public class SymfonyServerCodegen extends AbstractPhpCodegen implements CodegenC } } + @Override + public String toEnumValue(String value, String datatype) { + if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { + return value; + } else { + return "\"" + escapeText(value) + "\""; + } + } + + /** + * Return the regular expression/JSON schema pattern (http://json-schema.org/latest/json-schema-validation.html#anchor33) + * + * @param pattern the pattern (regular expression) + * @return properly-escaped pattern + */ + @Override + public String toRegularExpression(String pattern) { + return escapeText(pattern); + } + public String toApiName(String name) { if (name.isEmpty()) { return "DefaultApiInterface"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java index cab99599846..fefbf143b0c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import java.io.File; +import java.lang.StringBuffer; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; @@ -82,7 +83,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode supportingFiles.add(new SupportingFile("apis.mustache", apiPackage().replace('.', File.separatorChar), "api.ts")); supportingFiles.add(new SupportingFile("index.mustache", getIndexDirectory(), "index.ts")); supportingFiles.add(new SupportingFile("api.module.mustache", getIndexDirectory(), "api.module.ts")); - supportingFiles.add(new SupportingFile("rxjs-operators.mustache", getIndexDirectory(), "rxjs-operators.ts")); + supportingFiles.add(new SupportingFile("rxjs-operators.mustache", getIndexDirectory(), "rxjs-operators.ts")); supportingFiles.add(new SupportingFile("configuration.mustache", getIndexDirectory(), "configuration.ts")); supportingFiles.add(new SupportingFile("variables.mustache", getIndexDirectory(), "variables.ts")); supportingFiles.add(new SupportingFile("encoder.mustache", getIndexDirectory(), "encoder.ts")); @@ -149,7 +150,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode public boolean isDataTypeFile(final String dataType) { return dataType != null && dataType.equals("Blob"); } - + @Override public String getTypeDeclaration(Property p) { Property inner; @@ -247,8 +248,54 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode } } - // Convert path to TypeScript template string, applying URI encoding - op.path = op.path.replaceAll("\\{(.*?)\\}", "\\$\\{encodeURIComponent(String($1))\\}"); + // Prep a string buffer where we're going to set up our new version of the string. + StringBuffer pathBuffer = new StringBuffer(); + + // Set up other variables for tracking the current state of the string. + int insideCurly = 0; + boolean foundUnderscore = false; + + // Iterate through existing string, one character at a time. + for(int i = 0; i < op.path.length(); i++) { + switch(op.path.charAt(i)) { + case '{': + // We entered curly braces, so track that. + insideCurly++; + + // Add the more complicated component instead of just the brace. + pathBuffer.append("${encodeURIComponent(String("); + break; + case '}': + // We exited curly braces, so track that. + insideCurly--; + + // Add the more complicated component instead of just the brace. + pathBuffer.append("))}"); + break; + case '_': + // If we're inside the curly brace, the following character will need to be uppercase. + // Otherwise, just add the character. + if (insideCurly > 0) { + foundUnderscore = true; + } else { + pathBuffer.append(op.path.charAt(i)); + } + break; + default: + // If we previously found an underscore, we need an uppercase letter. + // Otherwise, just add the character. + if (foundUnderscore) { + pathBuffer.append(Character.toUpperCase(op.path.charAt(i))); + foundUnderscore = false; + } else { + pathBuffer.append(op.path.charAt(i)); + } + break; + } + } + + // Overwrite path to TypeScript template string, after applying everything we just did. + op.path = pathBuffer.toString(); } // Add additional filename information for model imports in the services @@ -272,7 +319,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode CodegenModel cm = (CodegenModel) mo.get("model"); mo.put("tsImports", toTsImports(cm,cm.imports)); } - + return result; } 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 960b5117e3f..1a24e1db7e5 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 @@ -51,6 +51,7 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege supportingFiles.add(new SupportingFile("index.mustache", "", "index.ts")); supportingFiles.add(new SupportingFile("api.mustache", "", "api.ts")); supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.ts")); + supportingFiles.add(new SupportingFile("custom.d.mustache", "", "custom.d.ts")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index a8224d1579b..542ccbba287 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -53,13 +53,16 @@ public class {{classname}} { {{/returnType}} * @throws ApiException if fails to make API call {{#isDeprecated}} - * @Deprecated + * @deprecated {{/isDeprecated}} {{#externalDocs}} * {{description}} * @see {{summary}} Documentation {{/externalDocs}} */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#allParams}}{{#required}} diff --git a/modules/swagger-codegen/src/main/resources/Java/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/Java/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/Java/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/ApiClient.mustache new file mode 100644 index 00000000000..70015378163 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/ApiClient.mustache @@ -0,0 +1,112 @@ +package {{invokerPackage}}; + +import {{apiPackage}}.*; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +{{#joda}} + import com.fasterxml.jackson.datatype.joda.JodaModule; +{{/joda}} +{{#java8}} + import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +{{/java8}} +{{#threetenbp}} + import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; +{{/threetenbp}} +{{#threetenbp}} + import org.threeten.bp.*; +{{/threetenbp}} +import com.google.api.client.googleapis.util.Utils; +import com.google.api.client.http.AbstractHttpContent; +import com.google.api.client.http.HttpRequestFactory; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.HttpTransport; +import com.google.api.client.json.Json; + +import java.io.IOException; +import java.io.OutputStream; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +{{>generatedAnnotation}} +public class ApiClient { + private final String basePath; + private final HttpRequestFactory httpRequestFactory; + private final ObjectMapper objectMapper; + + private static final String defaultBasePath = "{{basePath}}"; + + // A reasonable default object mapper. Client can pass in a chosen ObjectMapper anyway, this is just for reasonable defaults. + private static ObjectMapper createDefaultObjectMapper() { + ObjectMapper objectMapper = new ObjectMapper() + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .setDateFormat(new RFC3339DateFormat()); + {{#joda}} + objectMapper.registerModule(new JodaModule()); + {{/joda}} + {{#java8}} + objectMapper.registerModule(new JavaTimeModule()); + {{/java8}} + {{#threetenbp}} + ThreeTenModule module = new ThreeTenModule(); + module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT); + module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME); + module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME); + objectMapper.registerModule(module); + {{/threetenbp}} + return objectMapper; + } + + public ApiClient() { + this(null, null, null, null); + } + + public ApiClient( + String basePath, + HttpTransport httpTransport, + HttpRequestInitializer initializer, + ObjectMapper objectMapper + ) { + this.basePath = basePath == null ? defaultBasePath : ( + basePath.endsWith("/") ? basePath.substring(0, basePath.length() - 1) : basePath + ); + this.httpRequestFactory = (httpTransport == null ? Utils.getDefaultTransport() : httpTransport).createRequestFactory(initializer); + this.objectMapper = (objectMapper == null ? createDefaultObjectMapper() : objectMapper); + } + + public HttpRequestFactory getHttpRequestFactory() { + return httpRequestFactory; + } + + public String getBasePath() { + return basePath; + } + + public ObjectMapper getObjectMapper() { + return objectMapper; + } + + public class JacksonJsonHttpContent extends AbstractHttpContent { + /* A POJO that can be serialized with a com.fasterxml Jackson ObjectMapper */ + private final Object data; + + public JacksonJsonHttpContent(Object data) { + super(Json.MEDIA_TYPE); + this.data = data; + } + + @Override + public void writeTo(OutputStream out) throws IOException { + objectMapper.writeValue(out, data); + } + } + + // Builder pattern to get API instances for this client. + {{#apiInfo}}{{#apis}} + public {{classname}} {{classVarName}}Api() { + return new {{classname}}(this); + } + {{/apis}}{{/apiInfo}} +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/api.mustache new file mode 100644 index 00000000000..a1092d1063e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/api.mustache @@ -0,0 +1,152 @@ +package {{package}}; + +import {{invokerPackage}}.ApiClient; + +{{#imports}}import {{import}}; +{{/imports}} + +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.api.client.http.GenericUrl; +import com.google.api.client.http.HttpContent; +import com.google.api.client.http.HttpMethods; +import com.google.api.client.http.HttpResponse; + +import javax.ws.rs.core.UriBuilder; +import java.io.IOException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.List; +import java.util.ArrayList; + +{{>generatedAnnotation}} +{{#operations}} +public class {{classname}} { + private ApiClient {{localVariablePrefix}}apiClient; + + public {{classname}}() { + this(new ApiClient()); + } + + public {{classname}}(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; + } + + public ApiClient getApiClient() { + return {{localVariablePrefix}}apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; + } + + {{#operation}} + /**{{#summary}} + * {{summary}}{{/summary}}{{#notes}} + * {{notes}}{{/notes}}{{#responses}} + *

{{code}}{{#message}} - {{message}}{{/message}}{{/responses}}{{#allParams}} + * @param {{paramName}} {{description}}{{^description}}The {{paramName}} parameter{{/description}}{{/allParams}}{{#returnType}} + * @return {{returnType}}{{/returnType}} + * @throws IOException if an error occurs while attempting to invoke the API{{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} + + **/ + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws IOException { + {{#returnType}}HttpResponse response = {{/returnType}}{{operationId}}ForHttpResponse({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + TypeReference typeRef = new TypeReference<{{{returnType}}}>() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);{{/returnType}} + } + + /**{{#summary}} + * {{summary}}{{/summary}}{{#notes}} + * {{notes}}{{/notes}}{{#responses}} + *

{{code}}{{#message}} - {{message}}{{/message}}{{/responses}}{{#requiredParams}} + * @param {{paramName}} {{description}}{{^description}}The {{paramName}} parameter{{/description}}{{/requiredParams}} + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param.{{#returnType}} + * @return {{returnType}}{{/returnType}} + * @throws IOException if an error occurs while attempting to invoke the API{{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} + + **/ + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#requiredParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/requiredParams}}{{#hasRequiredParams}}, {{/hasRequiredParams}}Map params) throws IOException { + {{#returnType}}HttpResponse response = {{/returnType}}{{operationId}}ForHttpResponse({{#requiredParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/requiredParams}}{{#hasRequiredParams}}, {{/hasRequiredParams}}params);{{#returnType}} + TypeReference typeRef = new TypeReference<{{{returnType}}}>() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);{{/returnType}} + } + + public HttpResponse {{operationId}}ForHttpResponse({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws IOException { + Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new IllegalArgumentException("Missing the required parameter '{{paramName}}' when calling {{operationId}}"); + } + {{/required}}{{/allParams}} + {{#hasPathParams}} + // create a map of path variables + final Map uriVariables = new HashMap();{{#pathParams}} + uriVariables.put("{{baseName}}", {{{paramName}}});{{/pathParams}} + {{/hasPathParams}} + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "{{{path}}}");{{#hasQueryParams}} + {{#queryParams}}if ({{paramName}} != null) { + uriBuilder = uriBuilder.queryParam("{{baseName}}", {{paramName}}); + }{{#hasMore}}{{/hasMore}}{{/queryParams}}{{/hasQueryParams}} + + String url = uriBuilder{{#hasPathParams}}.buildFromMap(uriVariables).toString();{{/hasPathParams}}{{^hasPathParams}}.build().toString();{{/hasPathParams}} + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.{{httpMethod}}, genericUrl, content).execute(); + } + + public HttpResponse {{operationId}}ForHttpResponse({{#requiredParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/requiredParams}}{{#hasRequiredParams}}, {{/hasRequiredParams}}Map params) throws IOException { + Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new IllegalArgumentException("Missing the required parameter '{{paramName}}' when calling {{operationId}}"); + } + {{/required}}{{/allParams}} + {{#hasPathParams}} + // create a map of path variables + final Map uriVariables = new HashMap();{{#pathParams}} + uriVariables.put("{{baseName}}", {{{paramName}}});{{/pathParams}} + {{/hasPathParams}} + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "{{{path}}}"); + + if (params == null) { + params = new HashMap(); + }{{#queryParams}}{{#required}} + + // Add the required query param '{{paramName}}' to the map of query params + params.put("{{paramName}}", {{paramName}});{{/required}}{{/queryParams}} + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder{{#hasPathParams}}.buildFromMap(uriVariables).toString();{{/hasPathParams}}{{^hasPathParams}}.build().toString();{{/hasPathParams}} + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.{{httpMethod}}, genericUrl, content).execute(); + } + + + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/api_test.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/api_test.mustache new file mode 100644 index 00000000000..365106fbedf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/api_test.mustache @@ -0,0 +1,45 @@ +{{>licenseInfo}} + +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +import org.junit.Test; +import org.junit.Ignore; + +import java.io.IOException; +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +/** + * API tests for {{classname}} + */ +@Ignore +public class {{classname}}Test { + + private final {{classname}} api = new {{classname}}(); + + {{#operations}}{{#operation}} + /** + * {{summary}} + * + * {{notes}} + * + * @throws IOException + * if the Api call fails + */ + @Test + public void {{operationId}}Test() throws IOException { + {{#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/google-api-client/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/build.gradle.mustache new file mode 100644 index 00000000000..ca34bacc3f5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/build.gradle.mustache @@ -0,0 +1,142 @@ +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 22 + } + compileOptions { + {{#java8}} + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + {{/java8}} + {{^java8}} + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + {{/java8}} + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + {{#java8}} + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + {{/java8}} + {{^java8}} + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + {{/java8}} + + install { + repositories.mavenInstaller { + pom.artifactId = '{{artifactId}}' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.15" + jackson_version = "2.8.9" + google_api_client_version = "1.23.0" + jersey_common_version = "2.25.1" + jodatime_version = "2.9.9" + junit_version = "4.12" + {{#threetenbp}} + jackson_threeten_version = "2.6.4" + {{/threetenbp}} +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "com.google.api-client:google-api-client:${google_api_client_version}" + compile "org.glassfish.jersey.core:jersey-common:${jersey_common_version}" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" + compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version" + {{#java8}} + compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" + {{/java8}} + {{#joda}} + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" + compile "joda-time:joda-time:$jodatime_version" + {{/joda}} + {{#threetenbp}} + compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$jackson_threeten_version" + {{/threetenbp}} + {{#withXml}} + compile "com.fasterxml.jackson.dataformat:jackson-dataformat-xml:$jackson_version" + {{/withXml}} + testCompile "junit:junit:$junit_version" +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/build.sbt.mustache new file mode 100644 index 00000000000..8567f06e714 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/build.sbt.mustache @@ -0,0 +1,33 @@ +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.15", + "com.google.api-client" % "google-api-client" % "1.23.0", + "org.glassfish.jersey.core" % "jersey-common" % "2.25.1", + "com.fasterxml.jackson.core" % "jackson-core" % "2.8.9" % "compile", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.8.9" % "compile", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.8.9" % "compile", + {{#withXml}} + "com.fasterxml.jackson.dataformat" % "jackson-dataformat-xml" % "2.8.9" % "compile", + {{/withXml}} + {{#joda}} + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.8.9" % "compile", + {{/joda}} + {{#java8}} + "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.8.9" % "compile", + {{/java8}} + {{#threetenbp}} + "com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.6.4" % "compile", + {{/threetenbp}} + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/pom.mustache new file mode 100644 index 00000000000..a988122bbe8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/pom.mustache @@ -0,0 +1,278 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + {{artifactUrl}} + {{artifactDescription}} + + {{scmConnection}} + {{scmDeveloperConnection}} + {{scmUrl}} + + + 2.2.0 + + + + + {{licenseName}} + {{licenseUrl}} + repo + + + + + + {{developerName}} + {{developerEmail}} + {{developerOrganization}} + {{developerOrganizationUrl}} + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.10 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.1 + + {{#java8}} + 1.8 + 1.8 + {{/java8}} + {{^java8}} + 1.7 + 1.7 + {{/java8}} + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + com.google.api-client + google-api-client + ${google-api-client-version} + + + + org.glassfish.jersey.core + jersey-common + ${jersey-common-version} + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + {{#withXml}} + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + ${jackson-version} + + {{/withXml}} + {{#java8}} + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + + {{/java8}} + {{#joda}} + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson-version} + + + joda-time + joda-time + ${jodatime-version} + + {{/joda}} + {{#threetenbp}} + + com.github.joschi.jackson + jackson-datatype-threetenbp + ${jackson-threetenbp-version} + + {{/threetenbp}} + + + + junit + junit + ${junit-version} + test + + + + UTF-8 + 1.5.15 + 1.23.0 + 2.25.1 + 2.8.9 + {{#joda}} + 2.9.9 + {{/joda}} + {{#threetenbp}} + 2.6.4 + {{/threetenbp}} + 1.0.0 + 4.12 + + diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache index 4175739c37a..e4072aa5ad9 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -306,6 +306,27 @@ public class ApiClient { return this; } + /** + * read timeout (in milliseconds). + * @return Read timeout + */ + public int getReadTimeout() { + return readTimeout; + } + + /** + * Set the read timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + * @param readTimeout Read timeout in milliseconds + * @return API client + */ + public ApiClient setReadTimeout(int readTimeout) { + this.readTimeout = readTimeout; + httpClient.property(ClientProperties.READ_TIMEOUT, readTimeout); + return this; + } + /** * Get the date format used to parse/format date parameters. * @return Date format 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 ce026ab79e4..dd84a7dbd31 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 @@ -50,13 +50,16 @@ public class {{classname}} { {{/returnType}} * @throws ApiException if fails to make API call {{#isDeprecated}} - * @Deprecated + * @deprecated {{/isDeprecated}} {{#externalDocs}} * {{description}} * @see {{summary}} Documentation {{/externalDocs}} */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#allParams}}{{#required}} 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 c61eadb1b1d..0ae00335726 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 @@ -426,7 +426,7 @@ public class ApiClient { } /** - * Set the tempoaray folder path (for downloading files) + * Set the temporary folder path (for downloading files) * * @param tempFolderPath Temporary folder path * @return ApiClient @@ -448,6 +448,7 @@ public class ApiClient { /** * Sets the connect timeout (in milliseconds). * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. * * @param connectionTimeout connection timeout in milliseconds * @return Api client @@ -457,6 +458,50 @@ public class ApiClient { return this; } + /** + * Get read timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getReadTimeout() { + return httpClient.getReadTimeout(); + } + + /** + * Sets the read timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + * + * @param readTimeout read timeout in milliseconds + * @return Api client + */ + public ApiClient setReadTimeout(int readTimeout) { + httpClient.setReadTimeout(readTimeout, TimeUnit.MILLISECONDS); + return this; + } + + /** + * Get write timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getWriteTimeout() { + return httpClient.getWriteTimeout(); + } + + /** + * Sets the write timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + * + * @param writeTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setWriteTimeout(int writeTimeout) { + httpClient.setWriteTimeout(writeTimeout, TimeUnit.MILLISECONDS); + return this; + } + /** * Format the given parameter object into string. * 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 a5241d8acae..ffc68bc7b5a 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 @@ -70,14 +70,20 @@ public class {{classname}} { * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} {{#externalDocs}} * {{description}} * @see {{summary}} Documentation {{/externalDocs}} */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} public 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}}; - + // create path and map variables String {{localVariablePrefix}}localVarPath = "{{{path}}}"{{#pathParams}} .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; @@ -122,7 +128,10 @@ public class {{classname}} { String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarCollectionQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener); } - + + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call {{operationId}}ValidateBeforeCall({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { {{^performBeanValidation}} @@ -132,7 +141,7 @@ public class {{classname}} { throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)"); } {{/required}}{{/allParams}} - + com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); return {{localVariablePrefix}}call; @@ -150,7 +159,7 @@ public class {{classname}} { if (violations.size() == 0) { com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); return {{localVariablePrefix}}call; - + } else { throw new BeanValidationException((Set) violations); } @@ -161,12 +170,8 @@ public class {{classname}} { e.printStackTrace(); throw new ApiException(e.getMessage()); } - + {{/performBeanValidation}} - - - - } /** @@ -175,11 +180,17 @@ public class {{classname}} { * @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 + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} {{#externalDocs}} * {{description}} * @see {{summary}} Documentation {{/externalDocs}} */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { {{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} return {{localVariablePrefix}}resp.getData();{{/returnType}} @@ -191,11 +202,17 @@ public class {{classname}} { * @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 + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} {{#externalDocs}} * {{description}} * @see {{summary}} Documentation {{/externalDocs}} */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null, null); {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); @@ -209,11 +226,17 @@ public class {{classname}} { * @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 + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} {{#externalDocs}} * {{description}} * @see {{summary}} Documentation {{/externalDocs}} */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} 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; diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/resteasy/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/resteasy/api.mustache index 76eeea1e1ec..f3fd01ed61b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/resteasy/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/resteasy/api.mustache @@ -46,13 +46,16 @@ public class {{classname}} { * @return {{{returnType}}}{{/returnType}} * @throws ApiException if fails to make API call {{#isDeprecated}} - * @Deprecated + * @deprecated {{/isDeprecated}} {{#externalDocs}} * {{description}} * @see {{summary}} Documentation {{/externalDocs}} */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#allParams}}{{#required}} 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 5e33aefc1d3..8bc7a22fd76 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache @@ -22,6 +22,16 @@ import javax.validation.constraints.*; import javax.validation.Valid; {{/useBeanValidation}} +{{#appName}} +/** + * {{{appName}}} + * + {{#appDescription}} + *

{{{appDescription}}} + * + {{/appDescription}} + */ +{{/appName}} @Path("{{^useAnnotatedBasePath}}/{{/useAnnotatedBasePath}}{{#useAnnotatedBasePath}}{{contextPath}}{{/useAnnotatedBasePath}}") @Api(value = "/", description = "{{description}}") {{#addConsumesProducesJson}} @@ -32,6 +42,16 @@ public interface {{classname}} { {{#operations}} {{#operation}} + {{#summary}} + /** + * {{summary}} + * + {{#notes}} + * {{notes}} + * + {{/notes}} + */ + {{/summary}} @{{httpMethod}} {{#subresourceOperation}}@Path("{{{path}}}"){{/subresourceOperation}} {{#hasConsumes}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache index d216ed02538..f677e3a835e 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache @@ -25,9 +25,29 @@ import org.springframework.stereotype.Service; {{/useSpringAnnotationConfig}} {{#description}} {{/description}} +{{#appName}} +/** + * {{{appName}}} + * + {{#appDescription}} + *

{{{appDescription}}} + {{/appDescription}} + * + */ +{{/appName}} public class {{classname}}ServiceImpl implements {{classname}} { {{#operations}} {{#operation}} + {{#summary}} + /** + * {{summary}} + * + {{#notes}} + * {{notes}} + * + {{/notes}} + */ + {{/summary}} public {{>returnTypes}} {{nickname}}({{#allParams}}{{>queryParamsImpl}}{{>pathParamsImpl}}{{>headerParamsImpl}}{{>bodyParamsImpl}}{{>formParamsImpl}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { // TODO: Implement... diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache index d32c2e3a964..67a7db05386 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache @@ -42,7 +42,15 @@ import org.springframework.test.context.web.WebAppConfiguration; /** - * API tests for {{classname}} + {{#appName}} + * {{{appName}}} + * + {{/appName}} + {{#appDescription}} + *

{{{appDescription}}} + * + {{/appDescription}} + * API tests for {{classname}} */ {{#generateSpringBootApplication}} @RunWith(SpringJUnit4ClassRunner.class) @@ -91,10 +99,14 @@ public class {{classname}}Test { {{#operations}}{{#operation}} /** + {{#summary}} * {{summary}} * + {{#notes}} * {{notes}} * + {{/notes}} + {{/summary}} * @throws ApiException * if the Api call fails */ diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index bb9bbab729d..e59e0b9064a 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -6,6 +6,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; {{#withXml}} @XmlAccessorType(XmlAccessType.FIELD) @@ -16,6 +17,9 @@ import javax.xml.bind.annotation.XmlEnumValue; {{^parent}}@XmlRootElement(name="{{classname}}"){{/parent}} {{/withXml}} {{#description}} +/** + * {{{description}}} + **/ @ApiModel(description="{{{description}}}") {{/description}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { @@ -28,6 +32,11 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { @XmlElement(name="{{baseName}}"{{#required}}, required = {{required}}{{/required}}) {{/withXml}} @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") +{{#description}} + /** + * {{{description}}} + **/ +{{/description}} private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} {{#vars}} @@ -46,12 +55,22 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{/maximum}} * @return {{name}} **/ + @JsonProperty("{{baseName}}") {{#vendorExtensions.extraAnnotation}} {{{vendorExtensions.extraAnnotation}}} {{/vendorExtensions.extraAnnotation}} -{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { +{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} {{#isEnum}}{{^isListContainer}}{{^isMapContainer}}public {{datatype}} {{getter}}() { + if ({{name}} == null) { + return null; + } + return {{name}}.value(); + }{{/isMapContainer}}{{/isListContainer}}{{/isEnum}}{{#isEnum}}{{#isListContainer}}public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; - } + }{{/isListContainer}}{{/isEnum}}{{#isEnum}}{{#isMapContainer}}public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + }{{/isMapContainer}}{{/isEnum}}{{^isEnum}}public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + }{{/isEnum}} {{^isReadOnly}} public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache index df7a5a3bcb4..02c853a7559 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -4,6 +4,9 @@ {{artifactId}} jar {{artifactId}} + {{#appDescription}} + {{appDescription}} + {{/appDescription}} {{artifactVersion}} src/main/java diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/pom.mustache index 2bc2739b1fe..c7be1d0b172 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/pom.mustache @@ -4,6 +4,9 @@ {{artifactId}} war {{artifactId}} + {{#appDescription}} + {{appDescription}} + {{/appDescription}} {{artifactVersion}} src/main/java diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/queryParams.mustache index 5a9a4398a03..292fbb4600f 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}} @QueryParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{#defaultValue}} @DefaultValue("{{{defaultValue}}}"){{/defaultValue}} @QueryParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pojo.mustache index ad84530e925..73d96a3b16b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pojo.mustache @@ -1,5 +1,6 @@ import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; {{#description}}@ApiModel(description = "{{{description}}}"){{/description}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { @@ -29,6 +30,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali {{#vendorExtensions.extraAnnotation}}{{{vendorExtensions.extraAnnotation}}}{{/vendorExtensions.extraAnnotation}} @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + @JsonProperty("{{baseName}}") {{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } diff --git a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/application.mustache b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/application.mustache index c8a2d02d746..139e83e56cc 100644 --- a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/application.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/application.mustache @@ -17,6 +17,17 @@ play.filters.headers.contentSecurityPolicy=null +{{#useBeanValidation}} +# When using bean validation with the swagger api, the validator will check that every constraint is respected +# This is very useful when testing but could add a lot of overhead if you return a lot of data. Benchmark have +# shown that the time it takes to validate is exponential. +# If this is a concern in your application, or if you don't want to validate the output coming from your API for +# respecting its contract, set the "output" property below to "false". Since there is not a lot of data as input for +# an endpoint, I highly suggest you let the "input" property set to true. +useInputBeanValidation=true +useOutputBeanValidation=true +{{/useBeanValidation}} + {{#handleExceptions}} play.http.errorHandler="swagger.ErrorHandler" {{/handleExceptions}} diff --git a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/conversionBegin.mustache b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/conversionBegin.mustache index ef61e4943bc..19954287202 100644 --- a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/conversionBegin.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/conversionBegin.mustache @@ -1 +1 @@ -{{#isBoolean}}Boolean.valueOf({{/isBoolean}}{{#isInteger}}Integer.parseInt({{/isInteger}}{{#isDouble}}Double.parseDouble({{/isDouble}}{{#isLong}}Long.parseLong({{/isLong}}{{#isFloat}}Float.parseFloat({{/isFloat}}{{#isUuid}}UUID.fromString({{/isUuid}}{{#isDateTime}}OffsetDateTime.parse({{/isDateTime}} \ No newline at end of file +{{#isBoolean}}Boolean.valueOf({{/isBoolean}}{{#isInteger}}Integer.parseInt({{/isInteger}}{{#isDouble}}Double.parseDouble({{/isDouble}}{{#isLong}}Long.parseLong({{/isLong}}{{#isFloat}}Float.parseFloat({{/isFloat}}{{#isUuid}}UUID.fromString({{/isUuid}}{{#isDateTime}}OffsetDateTime.parse({{/isDateTime}}{{#isDate}}LocalDate.parse({{/isDate}}{{#isByteArray}}{{/isByteArray}}{{#isNumber}}new BigDecimal({{/isNumber}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/conversionEnd.mustache b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/conversionEnd.mustache index ece85da5a28..cc6940fb4df 100644 --- a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/conversionEnd.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/conversionEnd.mustache @@ -1 +1 @@ -{{#isBoolean}}){{/isBoolean}}{{#isInteger}}){{/isInteger}}{{#isDouble}}){{/isDouble}}{{#isLong}}){{/isLong}}{{#isFloat}}){{/isFloat}}{{#isUuid}}){{/isUuid}}{{#isDateTime}}){{/isDateTime}} \ No newline at end of file +{{#isBoolean}}){{/isBoolean}}{{#isInteger}}){{/isInteger}}{{#isDouble}}){{/isDouble}}{{#isLong}}){{/isLong}}{{#isFloat}}){{/isFloat}}{{#isUuid}}){{/isUuid}}{{#isDateTime}}){{/isDateTime}}{{#isDate}}){{/isDate}}{{#isByteArray}}.getBytes(){{/isByteArray}}{{#isNumber}}){{/isNumber}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/itemConversionBegin.mustache b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/itemConversionBegin.mustache index 42bcc99d36a..42b024ec340 100644 --- a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/itemConversionBegin.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/itemConversionBegin.mustache @@ -1 +1 @@ -{{#items.isBoolean}}Boolean.valueOf({{/items.isBoolean}}{{#items.isInteger}}Integer.parseInt({{/items.isInteger}}{{#items.isDouble}}Double.parseDouble({{/items.isDouble}}{{#items.isLong}}Long.parseLong({{/items.isLong}}{{#items.isFloat}}Float.parseFloat({{/items.isFloat}}{{#items.isUuid}}UUID.fromString({{/items.isUuid}}{{#items.isDateTime}}OffsetDateTime.parse({{/items.isDateTime}} \ No newline at end of file +{{#items.isBoolean}}Boolean.valueOf({{/items.isBoolean}}{{#items.isInteger}}Integer.parseInt({{/items.isInteger}}{{#items.isDouble}}Double.parseDouble({{/items.isDouble}}{{#items.isLong}}Long.parseLong({{/items.isLong}}{{#items.isFloat}}Float.parseFloat({{/items.isFloat}}{{#items.isUuid}}UUID.fromString({{/items.isUuid}}{{#items.isDateTime}}OffsetDateTime.parse({{/items.isDateTime}}{{#items.isDate}}LocalDate.parse({{/items.isDate}}{{#isByteArray}}{{/isByteArray}}{{#isNumber}}new BigDecimal({{/isNumber}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/itemConversionEnd.mustache b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/itemConversionEnd.mustache index cb202e4325e..66edac4ea93 100644 --- a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/itemConversionEnd.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/itemConversionEnd.mustache @@ -1 +1 @@ -{{#items.isBoolean}}){{/items.isBoolean}}{{#items.isInteger}}){{/items.isInteger}}{{#items.isDouble}}){{/items.isDouble}}{{#items.isLong}}){{/items.isLong}}{{#items.isFloat}}){{/items.isFloat}}{{#items.isUuid}}){{/items.isUuid}}{{#items.isDateTime}}){{/items.isDateTime}} \ No newline at end of file +{{#items.isBoolean}}){{/items.isBoolean}}{{#items.isInteger}}){{/items.isInteger}}{{#items.isDouble}}){{/items.isDouble}}{{#items.isLong}}){{/items.isLong}}{{#items.isFloat}}){{/items.isFloat}}{{#items.isUuid}}){{/items.isUuid}}{{#items.isDateTime}}){{/items.isDateTime}}{{#items.isDate}}){{/items.isDate}}{{#isByteArray}}.getBytes(){{/isByteArray}}{{#isNumber}}){{/isNumber}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/newApi.mustache b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/newApi.mustache index 1c23543a7e7..6862b7402a3 100644 --- a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/newApi.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/newApi.mustache @@ -18,7 +18,14 @@ public class {{classname}}ControllerImp {{#useInterfaces}}implements {{classname {{#useInterfaces}}@Override{{/useInterfaces}} public {{>returnTypes}} {{operationId}}({{#allParams}}{{>pathParams}}{{>queryParams}}{{>bodyParams}}{{>formParams}}{{>headerParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {{#handleExceptions}}throws Exception{{/handleExceptions}} { //Do your magic!!! - {{#returnType}}{{#isResponseFile}}return new FileInputStream("replace this");{{/isResponseFile}}{{^isResponseFile}}return new {{>returnTypesNoVoidNoAbstract}}();{{/isResponseFile}}{{/returnType}} + {{#returnType}} + {{#isResponseFile}} + return new FileInputStream("replace this"); + {{/isResponseFile}} + {{^isResponseFile}} + return new {{>returnTypesNoVoidNoAbstract}}({{#vendorExtensions.missingReturnInfoIfNeeded}}{{vendorExtensions.missingReturnInfoIfNeeded}}{{/vendorExtensions.missingReturnInfoIfNeeded}}); + {{/isResponseFile}} + {{/returnType}} } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/newApiController.mustache b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/newApiController.mustache index 0d7345a93b9..9f20541d056 100644 --- a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/newApiController.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/newApiController.mustache @@ -21,6 +21,7 @@ import com.fasterxml.jackson.core.type.TypeReference; {{#useBeanValidation}} import javax.validation.constraints.*; +import play.Configuration; {{/useBeanValidation}} {{#wrapCalls}} @@ -35,13 +36,19 @@ public class {{classname}}Controller extends Controller { private final {{classname}}ControllerImp{{#useInterfaces}}Interface{{/useInterfaces}} imp; {{/controllerOnly}} private final ObjectMapper mapper; + {{#useBeanValidation}} + private final Configuration configuration; + {{/useBeanValidation}} @Inject - private {{classname}}Controller({{^controllerOnly}}{{classname}}ControllerImp{{#useInterfaces}}Interface{{/useInterfaces}} imp{{/controllerOnly}}) { + private {{classname}}Controller({{#useBeanValidation}}Configuration configuration{{^controllerOnly}}, {{/controllerOnly}}{{/useBeanValidation}}{{^controllerOnly}}{{classname}}ControllerImp{{#useInterfaces}}Interface{{/useInterfaces}} imp{{/controllerOnly}}) { {{^controllerOnly}} this.imp = imp; {{/controllerOnly}} mapper = new ObjectMapper(); + {{#useBeanValidation}} + this.configuration = configuration; + {{/useBeanValidation}} } {{#operation}} @@ -55,12 +62,21 @@ public class {{classname}}Controller extends Controller { if (node{{paramName}} != null) { {{paramName}} = mapper.readValue(node{{paramName}}.toString(), {{#isContainer}}new TypeReference<{{{dataType}}}>(){}{{/isContainer}}{{^isContainer}}{{{dataType}}}.class{{/isContainer}}); {{#useBeanValidation}} - {{#isListContainer}}for ({{{baseType}}} curItem : {{paramName}}) { - curItem.validate(); - }{{/isListContainer}}{{#isMapContainer}}for (Map.Entry entry : {{paramName}}.entrySet()) { - entry.getValue().validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + {{#isListContainer}} + for ({{{baseType}}} curItem : {{paramName}}) { + SwaggerUtils.validate(curItem); + } + {{/isListContainer}} + {{#isMapContainer}} + for (Map.Entry entry : {{paramName}}.entrySet()) { + SwaggerUtils.validate(entry.getValue()); + } + {{/isMapContainer}} + {{^isContainer}} + SwaggerUtils.validate({{paramName}}); + {{/isContainer}} } - {{/isMapContainer}}{{^isContainer}}{{paramName}}.validate();{{/isContainer}} {{/useBeanValidation}} } else { {{#required}} @@ -173,13 +189,30 @@ public class {{classname}}Controller extends Controller { {{/collectionFormat}} {{/headerParams}} {{^controllerOnly}} - {{#returnType}}{{>returnTypesNoVoid}} obj = {{/returnType}}imp.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}{{^isResponseFile}}{{^returnTypeIsPrimitive}}{{#useBeanValidation}} - {{#isListContainer}}for ({{{returnType}}} curItem : obj) { - curItem.validate(); - }{{/isListContainer}}{{#isMapContainer}}for (Map.Entry entry : obj.entrySet()) { - entry.getValue().validate(); + {{#returnType}}{{>returnTypesNoVoid}} obj = {{/returnType}}imp.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{#returnType}} + {{^isResponseFile}} + {{^returnTypeIsPrimitive}} + {{#useBeanValidation}} + if (configuration.getBoolean("useOutputBeanValidation")) { + {{#isListContainer}} + for ({{{returnType}}} curItem : obj) { + SwaggerUtils.validate(curItem); + } + {{/isListContainer}} + {{#isMapContainer}} + for (Map.Entry entry : obj.entrySet()) { + SwaggerUtils.validate(entry.getValue()); + } + {{/isMapContainer}} + {{^returnContainer}} + SwaggerUtils.validate(obj); + {{/returnContainer}} } - {{/isMapContainer}}{{^returnContainer}}obj.validate();{{/returnContainer}}{{/useBeanValidation}}{{/returnTypeIsPrimitive}}{{/isResponseFile}}{{/returnType}} + {{/useBeanValidation}} + {{/returnTypeIsPrimitive}} + {{/isResponseFile}} + {{/returnType}} {{#returnType}} {{^isResponseFile}}JsonNode result = mapper.valueToTree(obj); return ok(result); diff --git a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/pojo.mustache index 25bb4e49c4a..c7ce1c4dadb 100644 --- a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/pojo.mustache @@ -134,22 +134,4 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali } return o.toString().replace("\n", "\n "); } - - {{#useBeanValidation}} - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation<{{classname}}> contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } - {{/useBeanValidation}} } diff --git a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/swaggerUtils.mustache b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/swaggerUtils.mustache index c03add93e1a..8b472f131d0 100644 --- a/modules/swagger-codegen/src/main/resources/JavaPlayFramework/swaggerUtils.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaPlayFramework/swaggerUtils.mustache @@ -9,6 +9,13 @@ import java.lang.annotation.Target; import java.text.SimpleDateFormat; import java.util.*; +{{#useBeanValidation}} +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +{{/useBeanValidation}} + public class SwaggerUtils { {{#wrapCalls}} @@ -19,6 +26,24 @@ public class SwaggerUtils { } {{/wrapCalls}} +{{#useBeanValidation}} + public static void validate(T obj) { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + Set> constraintViolations = validator.validate(obj); + if (constraintViolations.size() > 0) { + StringBuilder errors = new StringBuilder(); + for (ConstraintViolation contraintes : constraintViolations) { + errors.append(String.format("%s.%s %s\n", + contraintes.getRootBeanClass().getSimpleName(), + contraintes.getPropertyPath(), + contraintes.getMessage())); + } + throw new RuntimeException("Bean validation : " + errors); + } + } +{{/useBeanValidation}} + public static List parametersToList(String collectionFormat, String[] values){ List params = new ArrayList<>(); diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/api.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/api.mustache index f2f7c15f1a2..58bfee5f8ba 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/api.mustache @@ -7,12 +7,19 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} - +{{#jdk8-no-delegate}} +import com.fasterxml.jackson.databind.ObjectMapper; +{{/jdk8-no-delegate}} import io.swagger.annotations.*; -{{#jdk8}} +{{#jdk8-no-delegate}} +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; -{{/jdk8}} +{{/jdk8-no-delegate}} import org.springframework.http.ResponseEntity; +{{#useBeanValidation}} +import org.springframework.validation.annotation.Validated; +{{/useBeanValidation}} import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -21,26 +28,54 @@ 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; -{{^useSpringCloudClient}} -import java.io.IOException; -{{/useSpringCloudClient}} +{{#jdk8-no-delegate}} +import javax.servlet.http.HttpServletRequest; +{{/jdk8-no-delegate}} +{{#useBeanValidation}} +import javax.validation.Valid; +import javax.validation.constraints.*; +{{/useBeanValidation}} +{{#jdk8-no-delegate}} +import java.io.IOException; +{{/jdk8-no-delegate}} import java.util.List; -{{#useOptional}} +{{#jdk8-no-delegate}} import java.util.Optional; -{{/useOptional}} +{{/jdk8-no-delegate}} +{{^jdk8-no-delegate}} + {{#useOptional}} +import java.util.Optional; + {{/useOptional}} +{{/jdk8-no-delegate}} {{#async}} import java.util.concurrent.{{^jdk8}}Callable{{/jdk8}}{{#jdk8}}CompletableFuture{{/jdk8}}; {{/async}} -{{#useBeanValidation}} -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; -import javax.validation.Valid; -{{/useBeanValidation}} {{>generatedAnnotation}} @Api(value = "{{{baseName}}}", description = "the {{{baseName}}} API") {{#operations}} public interface {{classname}} { +{{#jdk8}} + + {{^isDelegate}} + Logger log = LoggerFactory.getLogger({{classname}}.class); + + default Optional getObjectMapper() { + return Optional.empty(); + } + + default Optional getRequest() { + return Optional.empty(); + } + + default Optional getAcceptHeader() { + return getRequest().map(r -> r.getHeader("Accept")); + } + {{/isDelegate}} + {{#isDelegate}} + {{classname}}Delegate getDelegate(); + {{/isDelegate}} +{{/jdk8}} {{#operation}} @ApiOperation(value = "{{{summary}}}", nickname = "{{{operationId}}}", notes = "{{{notes}}}"{{#returnBaseType}}, response = {{{returnBaseType}}}.class{{/returnBaseType}}{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { @@ -54,7 +89,9 @@ public interface {{classname}} { @ApiResponse(code = {{{code}}}, message = "{{{message}}}"{{#baseType}}, response = {{{baseType}}}.class{{/baseType}}{{#containerType}}, responseContainer = "{{{containerType}}}"{{/containerType}}){{#hasMore}},{{/hasMore}}{{/responses}} }) {{#implicitHeaders}} @ApiImplicitParams({ - {{#headerParams}}{{>implicitHeader}}{{/headerParams}} + {{#headerParams}} + {{>implicitHeader}} + {{/headerParams}} }) {{/implicitHeaders}} @RequestMapping(value = "{{{path}}}",{{#singleContentTypes}} @@ -63,20 +100,29 @@ public interface {{classname}} { produces = { {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}}{{#hasConsumes}} consumes = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}}{{/singleContentTypes}} method = RequestMethod.{{httpMethod}}) -{{#useSpringCloudClient}} {{#jdk8}}default {{/jdk8}}{{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}){{^jdk8}};{{/jdk8}}{{#jdk8}} { - // do some magic! - return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<{{>returnTypes}}>(HttpStatus.NOT_IMPLEMENTED){{#async}}){{/async}}; + {{^isDelegate}} + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + {{#examples}} + if (getAcceptHeader().get().contains("{{{contentType}}}")) { + try { + return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<>(getObjectMapper().get().readValue("{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{example}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{>exampleReturnTypes}}.class), HttpStatus.NOT_IMPLEMENTED){{#async}}){{/async}}; + } catch (IOException e) { + log.error("Couldn't serialize response for content type {{{contentType}}}", e); + return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR){{#async}}){{/async}}; + } + } + {{/examples}} + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default {{classname}} interface so no example is generated"); + } + return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED){{#async}}){{/async}}; + {{/isDelegate}} + {{#isDelegate}} + return getDelegate().{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{/isDelegate}} }{{/jdk8}} -{{/useSpringCloudClient}} -{{^useSpringCloudClient}} - {{#jdk8}}default {{/jdk8}}{{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}},{{/allParams}} @RequestHeader(value = "Accept", required = false) String accept) throws Exception{{^jdk8}};{{/jdk8}}{{#jdk8}} { - // do some magic! - return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK){{#async}}){{/async}}; - }{{/jdk8}} - -{{/useSpringCloudClient}} {{/operation}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/apiController.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/apiController.mustache index 019c7618e06..4d56cdab40a 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/apiController.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/apiController.mustache @@ -1,16 +1,21 @@ package {{package}}; -{{^jdk8-no-delegate}} +{{^jdk8}} {{#imports}}import {{import}}; {{/imports}} - +{{/jdk8}} +{{^isDelegate}} +import com.fasterxml.jackson.databind.ObjectMapper; +{{/isDelegate}} +{{^jdk8}} import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -{{/jdk8-no-delegate}} +{{/jdk8}} import org.springframework.stereotype.Controller; -{{^jdk8-no-delegate}} +{{^jdk8}} import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,31 +23,35 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; -import java.util.List; -{{#useOptional}} -import java.util.Optional; -{{/useOptional}} -{{#async}} -import java.util.concurrent.Callable; -{{/async}} -{{/jdk8-no-delegate}} -{{^useSpringCloudClient}} -import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; -{{/useSpringCloudClient}} -{{#useBeanValidation}} + {{#useBeanValidation}} import javax.validation.constraints.*; import javax.validation.Valid; -{{/useBeanValidation}} + {{/useBeanValidation}} +{{/jdk8}} +{{^isDelegate}} +import javax.servlet.http.HttpServletRequest; + {{#jdk8}} +import java.util.Optional; + {{/jdk8}} +{{/isDelegate}} +{{^jdk8-no-delegate}} + {{#useOptional}} +import java.util.Optional; + {{/useOptional}} +{{/jdk8-no-delegate}} +{{^jdk8}} + {{^isDelegate}} +import java.io.IOException; + {{/isDelegate}} +import java.util.List; + {{#async}} +import java.util.concurrent.Callable; + {{/async}} +{{/jdk8}} {{>generatedAnnotation}} @Controller {{#operations}} public class {{classname}}Controller implements {{classname}} { - private final ObjectMapper objectMapper; - - public {{classname}}Controller(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } {{#isDelegate}} private final {{classname}}Delegate delegate; @@ -51,48 +60,78 @@ public class {{classname}}Controller implements {{classname}} { public {{classname}}Controller({{classname}}Delegate delegate) { this.delegate = delegate; } + {{#jdk8}} + + @Override + public {{classname}}Delegate getDelegate() { + return delegate; + } + {{/jdk8}} +{{/isDelegate}} +{{^isDelegate}} + {{^jdk8}} + private static final Logger log = LoggerFactory.getLogger({{classname}}Controller.class); + + {{/jdk8}} + private final ObjectMapper objectMapper; + + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public {{classname}}Controller(ObjectMapper objectMapper, HttpServletRequest request) { + this.objectMapper = objectMapper; + this.request = request; + } + {{#jdk8}} + + @Override + public Optional getObjectMapper() { + return Optional.ofNullable(objectMapper); + } + + @Override + public Optional getRequest() { + return Optional.ofNullable(request); + } + {{/jdk8}} {{/isDelegate}} -{{^jdk8-no-delegate}} +{{^jdk8}} {{#operation}} - public {{#async}}Callable<{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}, - {{/allParams}}@RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! -{{#useSpringCloudClient}} - {{^isDelegate}} - {{^async}} - return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK); - {{/async}} - {{#async}} - return new CallablereturnTypes}}>>() { - @Override - public ResponseEntity<{{>returnTypes}}> call() throws Exception { - return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK); - } - }; - {{/async}} - {{/isDelegate}} - {{#isDelegate}} - return delegate.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - {{/isDelegate}} -{{/useSpringCloudClient}} -{{^useSpringCloudClient}} + public {{#async}}Callable<{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) { {{^isDelegate}} {{^async}} + String accept = request.getHeader("Accept"); {{#examples}} - if (accept != null && accept.contains("{{{contentType}}}")) { - return new ResponseEntity<{{>returnTypes}}>(objectMapper.readValue("{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{example}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{>exampleReturnTypes}}.class), HttpStatus.OK); + try { + return new ResponseEntity<{{>returnTypes}}>(objectMapper.readValue("{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{example}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{>exampleReturnTypes}}.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type {{{contentType}}}", e); + return new ResponseEntity<{{>returnTypes}}>(HttpStatus.INTERNAL_SERVER_ERROR); + } } {{/examples}} - return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK); + return new ResponseEntity<{{>returnTypes}}>(HttpStatus.NOT_IMPLEMENTED); {{/async}} {{#async}} return new CallablereturnTypes}}>>() { @Override - public ResponseEntity<{{>returnTypes}}> call() throws Exception { - return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK); + public ResponseEntity<{{>returnTypes}}> call() { + String accept = request.getHeader("Accept"); + {{#examples}} + if (accept != null && accept.contains("{{{contentType}}}")) { + try { + return new ResponseEntity<{{>returnTypes}}>(objectMapper.readValue("{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{example}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{>exampleReturnTypes}}.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type {{{contentType}}}", e); + return new ResponseEntity<{{>returnTypes}}>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + {{/examples}} + return new ResponseEntity<{{>returnTypes}}>(HttpStatus.NOT_IMPLEMENTED); } }; {{/async}} @@ -100,10 +139,9 @@ public class {{classname}}Controller implements {{classname}} { {{#isDelegate}} return delegate.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{/isDelegate}} -{{/useSpringCloudClient}} } {{/operation}} -{{/jdk8-no-delegate}} +{{/jdk8}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/apiDelegate.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/apiDelegate.mustache index eed583ea916..482cdb1b2fb 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/apiDelegate.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/apiDelegate.mustache @@ -2,13 +2,33 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} - -import io.swagger.annotations.*;{{#jdk8}} -import org.springframework.http.HttpStatus;{{/jdk8}} +{{#jdk8}} +import com.fasterxml.jackson.databind.ObjectMapper; +{{/jdk8}} +import io.swagger.annotations.*; +{{#jdk8}} +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +{{/jdk8}} import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; +{{#jdk8}} +import java.io.IOException; +{{/jdk8}} +{{#jdk8}} +import javax.servlet.http.HttpServletRequest; +{{/jdk8}} import java.util.List; +{{#jdk8}} +import java.util.Optional; +{{/jdk8}} +{{^jdk8}} + {{#useOptional}} +import java.util.Optional; + {{/useOptional}} +{{/jdk8}} {{#async}} import java.util.concurrent.{{^jdk8}}Callable{{/jdk8}}{{#jdk8}}CompletableFuture{{/jdk8}}; {{/async}} @@ -16,11 +36,26 @@ import java.util.concurrent.{{^jdk8}}Callable{{/jdk8}}{{#jdk8}}CompletableFuture {{#operations}} /** * A delegate to be called by the {@link {{classname}}Controller}}. - * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. - * Instead, use spring to autowire this class into the {@link {{classname}}Controller}. + * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class. */ {{>generatedAnnotation}} public interface {{classname}}Delegate { +{{#jdk8}} + + Logger log = LoggerFactory.getLogger({{classname}}.class); + + default Optional getObjectMapper() { + return Optional.empty(); + } + + default Optional getRequest() { + return Optional.empty(); + } + + default Optional getAcceptHeader() { + return getRequest().map(r -> r.getHeader("Accept")); + } +{{/jdk8}} {{#operation}} /** @@ -28,8 +63,21 @@ public interface {{classname}}Delegate { */ {{#jdk8}}default {{/jdk8}}{{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{operationId}}({{#allParams}}{{^isFile}}{{{dataType}}}{{/isFile}}{{#isFile}}MultipartFile{{/isFile}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{^jdk8}};{{/jdk8}}{{#jdk8}} { - // do some magic! - return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK){{#async}}){{/async}}; + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + {{#examples}} + if (getAcceptHeader().get().contains("{{{contentType}}}")) { + try { + return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<>(getObjectMapper().get().readValue("{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{example}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{>exampleReturnTypes}}.class), HttpStatus.NOT_IMPLEMENTED){{#async}}){{/async}}; + } catch (IOException e) { + log.error("Couldn't serialize response for content type {{{contentType}}}", e); + return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR){{#async}}){{/async}}; + } + } + {{/examples}} + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default {{classname}} interface so no example is generated"); + } + return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED){{#async}}){{/async}}; }{{/jdk8}} {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/beanValidationCore.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/beanValidationCore.mustache index 84a26690f9b..3e7954e4a87 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/beanValidationCore.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/beanValidationCore.mustache @@ -1,20 +1,20 @@ -{{#pattern}} @Pattern(regexp="{{{pattern}}}"){{/pattern}}{{! +{{#pattern}}@Pattern(regexp="{{{pattern}}}") {{/pattern}}{{! minLength && maxLength set -}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{! +}}{{#minLength}}{{#maxLength}}@Size(min={{minLength}},max={{maxLength}}) {{/maxLength}}{{/minLength}}{{! minLength set, maxLength not -}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{! +}}{{#minLength}}{{^maxLength}}@Size(min={{minLength}}) {{/maxLength}}{{/minLength}}{{! minLength not set, maxLength set -}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{! +}}{{^minLength}}{{#maxLength}}@Size(max={{maxLength}}) {{/maxLength}}{{/minLength}}{{! @Size: minItems && maxItems set -}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{! +}}{{#minItems}}{{#maxItems}}@Size(min={{minItems}},max={{maxItems}}) {{/maxItems}}{{/minItems}}{{! @Size: minItems set, maxItems not -}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{! +}}{{#minItems}}{{^maxItems}}@Size(min={{minItems}}) {{/maxItems}}{{/minItems}}{{! @Size: minItems not set && maxItems set -}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{! +}}{{^minItems}}{{#maxItems}}@Size(max={{maxItems}}) {{/maxItems}}{{/minItems}}{{! check for integer or long / all others=decimal type with @Decimal* isInteger set -}}{{#isInteger}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}}{{/isInteger}}{{! +}}{{#isInteger}}{{#minimum}}@Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}) {{/maximum}}{{/isInteger}}{{! isLong set -}}{{#isLong}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}}{{/isLong}}{{! +}}{{#isLong}}{{#minimum}}@Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}) {{/maximum}}{{/isLong}}{{! Not Integer, not Long => we have a decimal value! -}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin("{{minimum}}"){{/minimum}}{{#maximum}} @DecimalMax("{{maximum}}"){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file +}}{{^isInteger}}{{^isLong}}{{#minimum}}@DecimalMin("{{minimum}}"){{/minimum}}{{#maximum}} @DecimalMax("{{maximum}}") {{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/beanValidationQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/beanValidationQueryParams.mustache index c4ff01d7e55..9cca8cb8874 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/beanValidationQueryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/beanValidationQueryParams.mustache @@ -1 +1 @@ -{{#required}} @NotNull{{/required}}{{>beanValidationCore}} \ No newline at end of file +{{#required}}@NotNull {{/required}}{{>beanValidationCore}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/pathParams.mustache index 62342d01bfa..f2b5c5b2ea8 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/pathParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/pathParams.mustache @@ -1 +1 @@ -{{#isPathParam}}{{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}} {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathVariable("{{baseName}}") {{>optionalDataType}} {{paramName}}{{/isPathParam}} \ No newline at end of file +{{#isPathParam}}{{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathVariable("{{baseName}}") {{>optionalDataType}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache index aa7fdc70c71..4c5a5d60e7f 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache @@ -91,6 +91,10 @@ this.agent = new superagent.agent(); } + /* + * Allow user to override superagent agent + */ + this.requestAgent = null; }; {{#emitJSDoc}} /** @@ -408,6 +412,12 @@ // set header parameters request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); + + // set requestAgent if it is set by user + if (this.requestAgent) { + request.agent(this.requestAgent); + } + // set request timeout request.timeout(this.timeout); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/es6/.babelrc.mustache b/modules/swagger-codegen/src/main/resources/Javascript/es6/.babelrc.mustache index bcb6ee8de93..67b369ed370 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/es6/.babelrc.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/es6/.babelrc.mustache @@ -1,3 +1,3 @@ { - "presets": ["es2015", "stage-0"] -} \ No newline at end of file + "presets": ["env", "stage-0"] +} diff --git a/modules/swagger-codegen/src/main/resources/Javascript/es6/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Javascript/es6/ApiClient.mustache index 17e9000179d..0e2a92da149 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/es6/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/es6/ApiClient.mustache @@ -78,6 +78,12 @@ export default class ApiClient { if (typeof window === 'undefined') { this.agent = new superagent.agent(); } + + /* + * Allow user to override superagent agent + */ + this.requestAgent = null; + } {{#emitJSDoc}}/** @@ -396,6 +402,11 @@ export default class ApiClient { // set header parameters request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); + // set requestAgent if it is set by user + if (this.requestAgent) { + request.agent(this.requestAgent); + } + // set request timeout request.timeout(this.timeout); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/es6/package.mustache b/modules/swagger-codegen/src/main/resources/Javascript/es6/package.mustache index 179f5cd3c73..997c5e24055 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/es6/package.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/es6/package.mustache @@ -12,12 +12,12 @@ }, "dependencies": { "babel": "^6.23.0", - "babel-cli": "^6.24.1", + "babel-cli": "^6.26.0", "superagent": "3.5.2" }, "devDependencies": { - "babel-core": "6.18.0", - "babel-preset-es2015": "^6.24.1", + "babel-core": "6.26.0", + "babel-preset-env": "^1.6.1", "babel-preset-stage-0": "^6.24.1", "expect.js": "~0.3.1", "mocha": "~2.3.4", 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 356c310e1df..804ad41368f 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 @@ -13,6 +13,7 @@ io.swagger.codegen.languages.CsharpDotNet2ClientCodegen io.swagger.codegen.languages.DartClientCodegen io.swagger.codegen.languages.ElixirClientCodegen io.swagger.codegen.languages.EiffelClientCodegen +io.swagger.codegen.languages.ErlangClientCodegen io.swagger.codegen.languages.ErlangServerCodegen io.swagger.codegen.languages.FinchServerCodegen io.swagger.codegen.languages.FlashClientCodegen @@ -56,6 +57,7 @@ io.swagger.codegen.languages.Rails5ServerCodegen io.swagger.codegen.languages.RestbedCodegen io.swagger.codegen.languages.RubyClientCodegen io.swagger.codegen.languages.RustClientCodegen +io.swagger.codegen.languages.RustServerCodegen io.swagger.codegen.languages.ScalaClientCodegen io.swagger.codegen.languages.ScalatraServerCodegen io.swagger.codegen.languages.ScalazClientCodegen 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 a9b0f28edfb..f65b794638f 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 @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/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 index b3c88d4be09..3e868678e81 100644 --- 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 @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/apex/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/apex/git_push.sh.mustache index e153ce23ecf..a2d75234837 100644 --- a/modules/swagger-codegen/src/main/resources/apex/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/apex/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/aspnetcore/enumClass.mustache b/modules/swagger-codegen/src/main/resources/aspnetcore/enumClass.mustache index 3c1d6e15d6a..ce4e3054ea3 100644 --- a/modules/swagger-codegen/src/main/resources/aspnetcore/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/aspnetcore/enumClass.mustache @@ -8,6 +8,6 @@ /// Enum {{name}} for {{{value}}} /// [EnumMember(Value = {{#isLong}}"{{/isLong}}{{#isInteger}}"{{/isInteger}}{{#isFloat}}"{{/isFloat}}{{#isDouble}}"{{/isDouble}}{{{value}}}{{#isLong}}"{{/isLong}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isFloat}}"{{/isFloat}})] - {{name}}{{#isLong}} = {{{value}}}{{/isLong}}{{#isInteger}} = {{{value}}}{{/isInteger}}{{^-last}}, + {{name}}{{#isLong}} = {{{value}}}{{/isLong}}{{#isInteger}} = {{{value}}}{{/isInteger}}{{^isInteger}} = {{-index}}{{/isInteger}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}} } diff --git a/modules/swagger-codegen/src/main/resources/clojure/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/clojure/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/clojure/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/clojure/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/cpprest/api-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/api-header.mustache index 94fc2cc9517..4299c808378 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/api-header.mustache @@ -5,8 +5,8 @@ * {{description}} */ -#ifndef {{classname}}_H_ -#define {{classname}}_H_ +#ifndef {{apiHeaderGuardPrefix}}_{{classname}}_H_ +#define {{apiHeaderGuardPrefix}}_{{classname}}_H_ {{{defaultInclude}}} #include "ApiClient.h" @@ -44,6 +44,6 @@ protected: } {{/apiNamespaceDeclarations}} -#endif /* {{classname}}_H_ */ +#endif /* {{apiHeaderGuardPrefix}}_{{classname}}_H_ */ {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache index dfadeb0d7b5..51884fa1f8a 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache @@ -32,13 +32,13 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r // verify the required parameter '{{paramName}}' is set if ({{paramName}} == nullptr) { - throw ApiException(400, U("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}")); + throw ApiException(400, utility::conversions::to_string_t("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}")); } {{/isContainer}}{{/isPrimitiveType}}{{/required}}{{/allParams}} std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("{{{path}}}"); - {{#pathParams}}boost::replace_all(path, U("{") U("{{baseName}}") U("}"), ApiClient::parameterToString({{{paramName}}})); + utility::string_t path = utility::conversions::to_string_t("{{{path}}}"); + {{#pathParams}}boost::replace_all(path, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("{{baseName}}") + utility::conversions::to_string_t("}"), ApiClient::parameterToString({{{paramName}}})); {{/pathParams}} std::map queryParams; @@ -48,7 +48,7 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r std::unordered_set responseHttpContentTypes; {{#produces}} - responseHttpContentTypes.insert( U("{{mediaType}}") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("{{mediaType}}") ); {{/produces}} utility::string_t responseHttpContentType; @@ -57,27 +57,27 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r if ( responseHttpContentTypes.size() == 0 ) { {{#vendorExtensions.x-codegen-response.isString}} - responseHttpContentType = U("text/plain"); + responseHttpContentType = utility::conversions::to_string_t("text/plain"); {{/vendorExtensions.x-codegen-response.isString}} {{^vendorExtensions.x-codegen-response.isString}} - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); {{/vendorExtensions.x-codegen-response.isString}} } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } {{#vendorExtensions.x-codegen-response.isString}} // plain text - else if( responseHttpContentTypes.find(U("text/plain")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("text/plain")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("text/plain"); + responseHttpContentType = utility::conversions::to_string_t("text/plain"); } {{/vendorExtensions.x-codegen-response.isString}} {{#vendorExtensions.x-codegen-response-ishttpcontent}} @@ -90,15 +90,15 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r {{^vendorExtensions.x-codegen-response-ishttpcontent}} else { - throw ApiException(400, U("{{classname}}->{{operationId}} does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("{{classname}}->{{operationId}} does not produce any supported media type")); } {{/vendorExtensions.x-codegen-response-ishttpcontent}} - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; {{#consumes}} - consumeHttpContentTypes.insert( U("{{mediaType}}") ); + consumeHttpContentTypes.insert( utility::conversions::to_string_t("{{mediaType}}") ); {{/consumes}} {{#allParams}} @@ -108,30 +108,30 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r { {{#isContainer}} {{#isQueryParam}} - queryParams[U("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}}); + queryParams[utility::conversions::to_string_t("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}}); {{/isQueryParam}} {{#isHeaderParam}} - headerParams[U("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}}); + headerParams[utility::conversions::to_string_t("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}}); {{/isHeaderParam}} {{#isFormParam}} {{^isFile}} - formParams[ U("{{baseName}}") ] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}}); + formParams[ utility::conversions::to_string_t("{{baseName}}") ] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}}); {{/isFile}} {{/isFormParam}} {{/isContainer}} {{^isContainer}} {{#isQueryParam}} - queryParams[U("{{baseName}}")] = ApiClient::parameterToString({{paramName}}); + queryParams[utility::conversions::to_string_t("{{baseName}}")] = ApiClient::parameterToString({{paramName}}); {{/isQueryParam}} {{#isHeaderParam}} - headerParams[U("{{baseName}}")] = ApiClient::parameterToString({{paramName}}); + headerParams[utility::conversions::to_string_t("{{baseName}}")] = ApiClient::parameterToString({{paramName}}); {{/isHeaderParam}} {{#isFormParam}} {{#isFile}} - fileParams[ U("{{baseName}}") ] = {{paramName}}; + fileParams[ utility::conversions::to_string_t("{{baseName}}") ] = {{paramName}}; {{/isFile}} {{^isFile}} - formParams[ U("{{baseName}}") ] = ApiClient::parameterToString({{paramName}}); + formParams[ utility::conversions::to_string_t("{{baseName}}") ] = ApiClient::parameterToString({{paramName}}); {{/isFile}} {{/isFormParam}} {{/isContainer}} @@ -144,9 +144,9 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); {{#bodyParam}} web::json::value json; @@ -177,9 +177,9 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r {{/bodyParam}} } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); {{#bodyParam}} std::shared_ptr multipart(new MultipartFormData); {{#isPrimitiveType}} @@ -197,28 +197,28 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r {{/items.isDateTime}}{{^items.isDateTime}}jsonArray.push_back( item.get() ? item->toJson() : web::json::value::null() ); {{/items.isDateTime}}{{/items.isString}}{{/items.isPrimitiveType}} } - multipart->add(ModelBase::toHttpContent(U("{{paramName}}"), web::json::value::array(jsonArray), U("application/json"))); + multipart->add(ModelBase::toHttpContent(utility::conversions::to_string_t("{{paramName}}"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json"))); } {{/isListContainer}} {{^isListContainer}} - {{#isString}}multipart->add(ModelBase::toHttpContent(U("{{paramName}}"), {{paramName}})); + {{#isString}}multipart->add(ModelBase::toHttpContent(utility::conversions::to_string_t("{{paramName}}"), {{paramName}})); {{/isString}} {{^isString}} if({{paramName}}.get()) { - {{paramName}}->toMultipart(multipart, U("{{paramName}}")); + {{paramName}}->toMultipart(multipart, utility::conversions::to_string_t("{{paramName}}")); } {{/isString}} {{/isListContainer}} {{/isPrimitiveType}} httpBody = multipart; - requestHttpContentType += U("; boundary=") + multipart->getBoundary(); + requestHttpContentType += utility::conversions::to_string_t("; boundary=") + multipart->getBoundary(); {{/bodyParam}} } else { - throw ApiException(415, U("{{classname}}->{{operationId}} does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("{{classname}}->{{operationId}} does not consume any supported media type")); } {{#authMethods}} @@ -226,19 +226,19 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r {{#isApiKey}} {{#isKeyInHeader}} { - utility::string_t apiKey = apiConfiguration->getApiKey(U("{{keyParamName}}")); + utility::string_t apiKey = apiConfiguration->getApiKey(utility::conversions::to_string_t("{{keyParamName}}")); if ( apiKey.size() > 0 ) { - headerParams[U("{{keyParamName}}")] = apiKey; + headerParams[utility::conversions::to_string_t("{{keyParamName}}")] = apiKey; } } {{/isKeyInHeader}} {{#isKeyInQuery}} { - utility::string_t apiKey = apiConfiguration->getApiKey(U("{{keyParamName}}")); + utility::string_t apiKey = apiConfiguration->getApiKey(utility::conversions::to_string_t("{{keyParamName}}")); if ( apiKey.size() > 0 ) { - queryParams[U("{{keyParamName}}")] = apiKey; + queryParams[utility::conversions::to_string_t("{{keyParamName}}")] = apiKey; } } {{/isKeyInQuery}} @@ -251,7 +251,7 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r {{/isOAuth}} {{/authMethods}} - return m_ApiClient->callApi(path, U("{{httpMethod}}"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("{{httpMethod}}"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -262,18 +262,18 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling {{operationId}}: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling {{operationId}}: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling {{operationId}}: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling {{operationId}}: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -304,7 +304,7 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r {{{returnType}}} result({{{defaultResponse}}}); {{/returnContainer}} - if(responseHttpContentType == U("application/json")) + if(responseHttpContentType == utility::conversions::to_string_t("application/json")) { web::json::value json = web::json::value::parse(response); @@ -330,18 +330,18 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r {{/vendorExtensions.x-codegen-response.isPrimitiveType}}{{^vendorExtensions.x-codegen-response.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.isString}}result = ModelBase::stringFromJson(json); {{/vendorExtensions.x-codegen-response.isString}}{{^vendorExtensions.x-codegen-response.isString}}result->fromJson(json);{{/vendorExtensions.x-codegen-response.isString}}{{/vendorExtensions.x-codegen-response.isPrimitiveType}}{{/isMapContainer}}{{/isListContainer}} }{{#vendorExtensions.x-codegen-response.isString}} - else if(responseHttpContentType == U("text/plain")) + else if(responseHttpContentType == utility::conversions::to_string_t("text/plain")) { result = response; }{{/vendorExtensions.x-codegen-response.isString}} - // else if(responseHttpContentType == U("multipart/form-data")) + // else if(responseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) // { // TODO multipart response parsing // } else { throw ApiException(500 - , U("error calling {{operationId}}: unsupported response type")); + , utility::conversions::to_string_t("error calling {{operationId}}: unsupported response type")); } return result; diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache index f5194b2185f..72b2c53671b 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache @@ -5,8 +5,8 @@ * This is an API client responsible for stating the HTTP calls */ -#ifndef ApiClient_H_ -#define ApiClient_H_ +#ifndef {{apiHeaderGuardPrefix}}_ApiClient_H_ +#define {{apiHeaderGuardPrefix}}_ApiClient_H_ {{{defaultInclude}}} #include "ApiConfiguration.h" @@ -48,7 +48,7 @@ public: for( size_t i = 0; i < value.size(); i++) { - if( i > 0) ss << U(", "); + if( i > 0) ss << utility::conversions::to_string_t(", "); ss << ApiClient::parameterToString(value[i]); } @@ -75,4 +75,4 @@ protected: } {{/apiNamespaceDeclarations}} -#endif /* ApiClient_H_ */ +#endif /* {{apiHeaderGuardPrefix}}_ApiClient_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache index 9f7c1e4fb1d..fae8c4c70b3 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache @@ -67,17 +67,17 @@ pplx::task ApiClient::callApi( { if (postBody != nullptr && formParams.size() != 0) { - throw ApiException(400, U("Cannot have body and form params")); + throw ApiException(400, utility::conversions::to_string_t("Cannot have body and form params")); } if (postBody != nullptr && fileParams.size() != 0) { - throw ApiException(400, U("Cannot have body and file params")); + throw ApiException(400, utility::conversions::to_string_t("Cannot have body and file params")); } - if (fileParams.size() > 0 && contentType != U("multipart/form-data")) + if (fileParams.size() > 0 && contentType != utility::conversions::to_string_t("multipart/form-data")) { - throw ApiException(400, U("Operations with file parameters must be called with multipart/form-data")); + throw ApiException(400, utility::conversions::to_string_t("Operations with file parameters must be called with multipart/form-data")); } web::http::client::http_client client(m_Configuration->getBaseUrl(), m_Configuration->getHttpConfig()); @@ -103,7 +103,7 @@ pplx::task ApiClient::callApi( uploadData.writeTo(data); auto bodyString = data.str(); auto length = bodyString.size(); - request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, U("multipart/form-data; boundary=") + uploadData.getBoundary()); + request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, utility::conversions::to_string_t("multipart/form-data; boundary=") + uploadData.getBoundary()); } else { @@ -117,7 +117,7 @@ pplx::task ApiClient::callApi( } else { - if (contentType == U("application/json")) + if (contentType == utility::conversions::to_string_t("application/json")) { web::json::value body_data = web::json::value::object(); for (auto& kvp : formParams) @@ -138,7 +138,7 @@ pplx::task ApiClient::callApi( } if (!formParams.empty()) { - request.set_body(formData.query(), U("application/x-www-form-urlencoded")); + request.set_body(formData.query(), utility::conversions::to_string_t("application/x-www-form-urlencoded")); } } } diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-header.mustache index c554fb21bfc..35375760b7a 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-header.mustache @@ -5,8 +5,8 @@ * This class represents a single item of a multipart-formdata request. */ -#ifndef ApiConfiguration_H_ -#define ApiConfiguration_H_ +#ifndef {{apiHeaderGuardPrefix}}_ApiConfiguration_H_ +#define {{apiHeaderGuardPrefix}}_ApiConfiguration_H_ {{{defaultInclude}}} @@ -49,4 +49,4 @@ protected: {{#apiNamespaceDeclarations}} } {{/apiNamespaceDeclarations}} -#endif /* ApiConfiguration_H_ */ +#endif /* {{apiHeaderGuardPrefix}}_ApiConfiguration_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-source.mustache index 6e0d4e9147e..d4a6a660471 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-source.mustache @@ -55,7 +55,7 @@ utility::string_t ApiConfiguration::getApiKey( const utility::string_t& prefix) { return result->second; } - return U(""); + return utility::conversions::to_string_t(""); } void ApiConfiguration::setApiKey( const utility::string_t& prefix, const utility::string_t& apiKey ) diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiexception-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiexception-header.mustache index cc01d446ddf..6a842d64ac9 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/apiexception-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiexception-header.mustache @@ -5,8 +5,8 @@ * This is the exception being thrown in case the api call was not successful */ -#ifndef ApiException_H_ -#define ApiException_H_ +#ifndef {{apiHeaderGuardPrefix}}_ApiException_H_ +#define {{apiHeaderGuardPrefix}}_ApiException_H_ {{{defaultInclude}}} @@ -46,4 +46,4 @@ protected: } {{/apiNamespaceDeclarations}} -#endif /* ApiBase_H_ */ +#endif /* {{apiHeaderGuardPrefix}}_ApiBase_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/cpprest/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/cpprest/git_push.sh.mustache index c7d7c390acf..c7a337655c3 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache index 004971cf7f6..59cf42ae8c0 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache @@ -5,8 +5,8 @@ * This class represents a single item of a multipart-formdata request. */ -#ifndef HttpContent_H_ -#define HttpContent_H_ +#ifndef {{modelHeaderGuardPrefix}}_HttpContent_H_ +#define {{modelHeaderGuardPrefix}}_HttpContent_H_ {{{defaultInclude}}} @@ -54,4 +54,4 @@ protected: } {{/modelNamespaceDeclarations}} -#endif /* HttpContent_H_ */ +#endif /* {{modelHeaderGuardPrefix}}_HttpContent_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/cpprest/ihttpbody-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/ihttpbody-header.mustache index 76e5f211e86..e9c77b263eb 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/ihttpbody-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/ihttpbody-header.mustache @@ -5,8 +5,8 @@ * This is the interface for contents that can be sent to a remote HTTP server. */ -#ifndef IHttpBody_H_ -#define IHttpBody_H_ +#ifndef {{modelHeaderGuardPrefix}}_IHttpBody_H_ +#define {{modelHeaderGuardPrefix}}_IHttpBody_H_ {{{defaultInclude}}} #include @@ -27,4 +27,4 @@ public: } {{/modelNamespaceDeclarations}} -#endif /* IHttpBody_H_ */ +#endif /* {{modelHeaderGuardPrefix}}_IHttpBody_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-header.mustache index 4face5a0dd6..312ebb0dab4 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-header.mustache @@ -5,8 +5,8 @@ * This is a JSON http body which can be submitted via http */ -#ifndef JsonBody_H_ -#define JsonBody_H_ +#ifndef {{modelHeaderGuardPrefix}}_JsonBody_H_ +#define {{modelHeaderGuardPrefix}}_JsonBody_H_ {{{defaultInclude}}} #include "IHttpBody.h" @@ -34,4 +34,4 @@ protected: } {{/modelNamespaceDeclarations}} -#endif /* JsonBody_H_ */ +#endif /* {{modelHeaderGuardPrefix}}_JsonBody_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/cpprest/model-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/model-header.mustache index d15f49a2ad6..a1f265e23c7 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/model-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/model-header.mustache @@ -5,8 +5,8 @@ * {{description}} */ -#ifndef {{classname}}_H_ -#define {{classname}}_H_ +#ifndef {{modelHeaderGuardPrefix}}_{{classname}}_H_ +#define {{modelHeaderGuardPrefix}}_{{classname}}_H_ {{^parent}} {{{defaultInclude}}} @@ -72,6 +72,6 @@ protected: } {{/modelNamespaceDeclarations}} -#endif /* {{classname}}_H_ */ +#endif /* {{modelHeaderGuardPrefix}}_{{classname}}_H_ */ {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache index c2bbe153570..77c92cbaf0c 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache @@ -57,11 +57,11 @@ web::json::value {{classname}}::toJson() const {{^required}} if(m_{{name}}IsSet) { - val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}}); + val[utility::conversions::to_string_t("{{baseName}}")] = ModelBase::toJson(m_{{name}}); } {{/required}} {{#required}} - val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}}); + val[utility::conversions::to_string_t("{{baseName}}")] = ModelBase::toJson(m_{{name}}); {{/required}} {{/isMapContainer}} {{/isListContainer}} @@ -74,12 +74,12 @@ web::json::value {{classname}}::toJson() const jsonArray.push_back(ModelBase::toJson(item)); } {{#required}} - val[U("{{baseName}}")] = web::json::value::array(jsonArray); + val[utility::conversions::to_string_t("{{baseName}}")] = web::json::value::array(jsonArray); {{/required}} {{^required}} if(jsonArray.size() > 0) { - val[U("{{baseName}}")] = web::json::value::array(jsonArray); + val[utility::conversions::to_string_t("{{baseName}}")] = web::json::value::array(jsonArray); } {{/required}} } @@ -90,17 +90,17 @@ web::json::value {{classname}}::toJson() const for( auto& item : m_{{name}} ) { web::json::value tmp = web::json::value::object(); - tmp[U("key")] = ModelBase::toJson(item.first); - tmp[U("value")] = ModelBase::toJson(item.second); + tmp[utility::conversions::to_string_t("key")] = ModelBase::toJson(item.first); + tmp[utility::conversions::to_string_t("value")] = ModelBase::toJson(item.second); jsonArray.push_back(tmp); } {{#required}} - val[U("{{baseName}}")] = web::json::value::array(jsonArray); + val[utility::conversions::to_string_t("{{baseName}}")] = web::json::value::array(jsonArray); {{/required}} {{^required}} if(jsonArray.size() > 0) { - val[U("{{baseName}}")] = web::json::value::array(jsonArray); + val[utility::conversions::to_string_t("{{baseName}}")] = web::json::value::array(jsonArray); } {{/required}} } @@ -111,11 +111,11 @@ web::json::value {{classname}}::toJson() const {{^required}} if(m_{{name}}IsSet) { - val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}}); + val[utility::conversions::to_string_t("{{baseName}}")] = ModelBase::toJson(m_{{name}}); } {{/required}} {{#required}} - val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}}); + val[utility::conversions::to_string_t("{{baseName}}")] = ModelBase::toJson(m_{{name}}); {{/required}} {{/isPrimitiveType}} {{/isMapContainer}} @@ -138,13 +138,13 @@ void {{classname}}::fromJson(web::json::value& val) {{^isListContainer}} {{^isMapContainer}} {{^required}} - if(val.has_field(U("{{baseName}}"))) + if(val.has_field(utility::conversions::to_string_t("{{baseName}}"))) { - {{setter}}(ModelBase::{{baseType}}FromJson(val[U("{{baseName}}")])); + {{setter}}(ModelBase::{{baseType}}FromJson(val[utility::conversions::to_string_t("{{baseName}}")])); } {{/required}} {{#required}} - {{setter}}(ModelBase::{{baseType}}FromJson(val[U("{{baseName}}")])); + {{setter}}(ModelBase::{{baseType}}FromJson(val[utility::conversions::to_string_t("{{baseName}}")])); {{/required}} {{/isMapContainer}} {{/isListContainer}} @@ -154,10 +154,10 @@ void {{classname}}::fromJson(web::json::value& val) m_{{name}}.clear(); std::vector jsonArray; {{^required}} - if(val.has_field(U("{{baseName}}"))) + if(val.has_field(utility::conversions::to_string_t("{{baseName}}"))) { {{/required}} - for( auto& item : val[U("{{baseName}}")].as_array() ) + for( auto& item : val[utility::conversions::to_string_t("{{baseName}}")].as_array() ) { {{#items.isPrimitiveType}} m_{{name}}.push_back(ModelBase::{{items.baseType}}FromJson(item)); @@ -195,26 +195,26 @@ void {{classname}}::fromJson(web::json::value& val) m_{{name}}.clear(); std::vector jsonArray; {{^required}} - if(val.has_field(U("{{baseName}}"))) + if(val.has_field(utility::conversions::to_string_t("{{baseName}}"))) { {{/required}} - for( auto& item : val[U("{{baseName}}")].as_array() ) + for( auto& item : val[utility::conversions::to_string_t("{{baseName}}")].as_array() ) { utility::string_t key; - if(item.has_field(U("key"))) + if(item.has_field(utility::conversions::to_string_t("key"))) { - key = ModelBase::stringFromJson(item[U("key")]); + key = ModelBase::stringFromJson(item[utility::conversions::to_string_t("key")]); } {{#items.isPrimitiveType}} - m_{{name}}.insert(std::pair( key, ModelBase::{{items.baseType}}FromJson(item[U("value")]))); + m_{{name}}.insert(std::pair( key, ModelBase::{{items.baseType}}FromJson(item[utility::conversions::to_string_t("value")]))); {{/items.isPrimitiveType}} {{^items.isPrimitiveType}} {{#items.isString}} - m_{{name}}.insert(std::pair( key, ModelBase::stringFromJson(item[U("value")]))); + m_{{name}}.insert(std::pair( key, ModelBase::stringFromJson(item[utility::conversions::to_string_t("value")]))); {{/items.isString}} {{^items.isString}} {{#items.isDateTime}} - m_{{name}}.insert(std::pair( key, ModelBase::dateFromJson(item[U("value")]))); + m_{{name}}.insert(std::pair( key, ModelBase::dateFromJson(item[utility::conversions::to_string_t("value")]))); {{/items.isDateTime}} {{^items.isDateTime}} if(item.is_null()) @@ -224,7 +224,7 @@ void {{classname}}::fromJson(web::json::value& val) else { {{{items.datatype}}} newItem({{{items.defaultValue}}}); - newItem->fromJson(item[U("value")]); + newItem->fromJson(item[utility::conversions::to_string_t("value")]); m_{{name}}.insert(std::pair( key, newItem )); } {{/items.isDateTime}} @@ -240,20 +240,20 @@ void {{classname}}::fromJson(web::json::value& val) {{^isMapContainer}} {{^isPrimitiveType}} {{^required}} - if(val.has_field(U("{{baseName}}"))) + if(val.has_field(utility::conversions::to_string_t("{{baseName}}"))) { {{#isString}} - {{setter}}(ModelBase::stringFromJson(val[U("{{baseName}}")])); + {{setter}}(ModelBase::stringFromJson(val[utility::conversions::to_string_t("{{baseName}}")])); {{/isString}} {{^isString}} {{#isDateTime}} - {{setter}}(ModelBase::dateFromJson(val[U("{{baseName}}")])); + {{setter}}(ModelBase::dateFromJson(val[utility::conversions::to_string_t("{{baseName}}")])); {{/isDateTime}} {{^isDateTime}} - if(!val[U("{{baseName}}")].is_null()) + if(!val[utility::conversions::to_string_t("{{baseName}}")].is_null()) { {{{datatype}}} newItem({{{defaultValue}}}); - newItem->fromJson(val[U("{{baseName}}")]); + newItem->fromJson(val[utility::conversions::to_string_t("{{baseName}}")]); {{setter}}( newItem ); } {{/isDateTime}} @@ -262,20 +262,20 @@ void {{classname}}::fromJson(web::json::value& val) {{/required}} {{#required}} {{#isString}} - {{setter}}(ModelBase::stringFromJson(val[U("{{baseName}}")])); + {{setter}}(ModelBase::stringFromJson(val[utility::conversions::to_string_t("{{baseName}}")])); {{/isString}} {{^isString}} {{#isDateTime}} {{setter}} - (ModelBase::dateFromJson(val[U("{{baseName}}")])); + (ModelBase::dateFromJson(val[utility::conversions::to_string_t("{{baseName}}")])); {{/isDateTime}} {{^isDateTime}} {{#vendorExtensions.x-codegen-file}} - {{setter}}(ModelBase::fileFromJson(val[U("{{baseName}}")])); + {{setter}}(ModelBase::fileFromJson(val[utility::conversions::to_string_t("{{baseName}}")])); {{/vendorExtensions.x-codegen-file}} {{^vendorExtensions.x-codegen-file}} {{{datatype}}} new{{name}}({{{defaultValue}}}); - new{{name}}->fromJson(val[U("{{baseName}}")]); + new{{name}}->fromJson(val[utility::conversions::to_string_t("{{baseName}}")]); {{setter}}( new{{name}} ); {{/vendorExtensions.x-codegen-file}} {{/isDateTime}} @@ -291,9 +291,9 @@ void {{classname}}::fromJson(web::json::value& val) void {{classname}}::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const { utility::string_t namePrefix = prefix; - if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { - namePrefix += U("."); + namePrefix += utility::conversions::to_string_t("."); } {{#vars}} @@ -303,11 +303,11 @@ void {{classname}}::toMultipart(std::shared_ptr multipart, co {{^required}} if(m_{{name}}IsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}})); } {{/required}} {{#required}} - multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}})); {{/required}} {{/isListContainer}} {{/isMapContainer}} @@ -319,11 +319,11 @@ void {{classname}}::toMultipart(std::shared_ptr multipart, co { jsonArray.push_back(ModelBase::toJson(item)); } - {{#required}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), web::json::value::array(jsonArray), U("application/json"))); + {{#required}}multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json"))); {{/required}}{{^required}} if(jsonArray.size() > 0) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), web::json::value::array(jsonArray), U("application/json"))); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json"))); } {{/required}} } @@ -334,15 +334,15 @@ void {{classname}}::toMultipart(std::shared_ptr multipart, co for( auto& item : m_{{name}} ) { web::json::value tmp = web::json::value::object(); - tmp[U("key")] = ModelBase::toJson(item.first); - tmp[U("value")] = ModelBase::toJson(item.second); + tmp[utility::conversions::to_string_t("key")] = ModelBase::toJson(item.first); + tmp[utility::conversions::to_string_t("value")] = ModelBase::toJson(item.second); jsonArray.push_back(tmp); } - {{#required}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), web::json::value::array(jsonArray), U("application/json"))); + {{#required}}multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json"))); {{/required}}{{^required}} if(jsonArray.size() > 0) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), web::json::value::array(jsonArray), U("application/json"))); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json"))); } {{/required}} } @@ -353,29 +353,29 @@ void {{classname}}::toMultipart(std::shared_ptr multipart, co {{^required}} if(m_{{name}}IsSet) { - {{#isString}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); - {{/isString}}{{^isString}}{{#isDateTime}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); + {{#isString}}multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}})); + {{/isString}}{{^isString}}{{#isDateTime}}multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}})); {{/isDateTime}}{{^isDateTime}}if (m_{{name}}.get()) { - m_{{name}}->toMultipart(multipart, U("{{baseName}}.")); + m_{{name}}->toMultipart(multipart, utility::conversions::to_string_t("{{baseName}}.")); } {{/isDateTime}}{{/isString}} } {{/required}} {{#required}} {{#isString}} - multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}})); {{/isString}} {{^isString}} {{#isDateTime}} - multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}})); {{/isDateTime}} {{^isDateTime}} {{#vendorExtensions.x-codegen-file}} - multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}})); {{/vendorExtensions.x-codegen-file}} {{^vendorExtensions.x-codegen-file}} - m_{{name}}->toMultipart(multipart, U("{{baseName}}.")); + m_{{name}}->toMultipart(multipart, utility::conversions::to_string_t("{{baseName}}.")); {{/vendorExtensions.x-codegen-file}} {{/isDateTime}} {{/isString}} @@ -389,9 +389,9 @@ void {{classname}}::toMultipart(std::shared_ptr multipart, co void {{classname}}::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) { utility::string_t namePrefix = prefix; - if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { - namePrefix += U("."); + namePrefix += utility::conversions::to_string_t("."); } {{#vars}} @@ -399,13 +399,13 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart, {{^isListContainer}} {{^isMapContainer}} {{^required}} - if(multipart->hasContent(U("{{baseName}}"))) + if(multipart->hasContent(utility::conversions::to_string_t("{{baseName}}"))) { - {{setter}}(ModelBase::{{baseType}}FromHttpContent(multipart->getContent(U("{{baseName}}")))); + {{setter}}(ModelBase::{{baseType}}FromHttpContent(multipart->getContent(utility::conversions::to_string_t("{{baseName}}")))); } {{/required}} {{#required}} - {{setter}}(ModelBase::{{baseType}}FromHttpContent(multipart->getContent(U("{{baseName}}")))); + {{setter}}(ModelBase::{{baseType}}FromHttpContent(multipart->getContent(utility::conversions::to_string_t("{{baseName}}")))); {{/required}} {{/isMapContainer}} {{/isListContainer}} @@ -414,11 +414,11 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart, { m_{{name}}.clear(); {{^required}} - if(multipart->hasContent(U("{{baseName}}"))) + if(multipart->hasContent(utility::conversions::to_string_t("{{baseName}}"))) { {{/required}} - web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}")))); + web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("{{baseName}}")))); for( auto& item : jsonArray.as_array() ) { {{#isPrimitiveType}} @@ -456,28 +456,28 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart, { m_{{name}}.clear(); {{^required}} - if(multipart->hasContent(U("{{baseName}}"))) + if(multipart->hasContent(utility::conversions::to_string_t("{{baseName}}"))) { {{/required}} - web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}")))); + web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("{{baseName}}")))); for( auto& item : jsonArray.as_array() ) { utility::string_t key; - if(item.has_field(U("key"))) + if(item.has_field(utility::conversions::to_string_t("key"))) { - key = ModelBase::stringFromJson(item[U("key")]); + key = ModelBase::stringFromJson(item[utility::conversions::to_string_t("key")]); } {{#items.isPrimitiveType}} - m_{{name}}.insert(std::pair( key, ModelBase::{{items.baseType}}FromJson(item[U("value")]))); + m_{{name}}.insert(std::pair( key, ModelBase::{{items.baseType}}FromJson(item[utility::conversions::to_string_t("value")]))); {{/items.isPrimitiveType}} {{^items.isPrimitiveType}} {{#items.isString}} - m_{{name}}.insert(std::pair( key, ModelBase::stringFromJson(item[U("value")]))); + m_{{name}}.insert(std::pair( key, ModelBase::stringFromJson(item[utility::conversions::to_string_t("value")]))); {{/items.isString}} {{^items.isString}} {{#items.isDateTime}} - m_{{name}}.insert(std::pair( key, ModelBase::dateFromJson(item[U("value")]))); + m_{{name}}.insert(std::pair( key, ModelBase::dateFromJson(item[utility::conversions::to_string_t("value")]))); {{/items.isDateTime}} {{^items.isDateTime}} if(item.is_null()) @@ -487,7 +487,7 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart, else { {{{items.datatype}}} newItem({{{items.defaultValue}}}); - newItem->fromJson(item[U("value")]); + newItem->fromJson(item[utility::conversions::to_string_t("value")]); m_{{name}}.insert(std::pair( key, newItem )); } {{/items.isDateTime}} @@ -503,20 +503,20 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart, {{^isMapContainer}} {{^isPrimitiveType}} {{^required}} - if(multipart->hasContent(U("{{baseName}}"))) + if(multipart->hasContent(utility::conversions::to_string_t("{{baseName}}"))) { {{#isString}} - {{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}")))); + {{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("{{baseName}}")))); {{/isString}} {{^isString}} {{#isDateTime}} - {{setter}}(ModelBase::dateFromHttpContent(multipart->getContent(U("{{baseName}}")))); + {{setter}}(ModelBase::dateFromHttpContent(multipart->getContent(utility::conversions::to_string_t("{{baseName}}")))); {{/isDateTime}} {{^isDateTime}} - if(multipart->hasContent(U("{{baseName}}"))) + if(multipart->hasContent(utility::conversions::to_string_t("{{baseName}}"))) { {{{datatype}}} newItem({{{defaultValue}}}); - newItem->fromMultiPart(multipart, U("{{baseName}}.")); + newItem->fromMultiPart(multipart, utility::conversions::to_string_t("{{baseName}}.")); {{setter}}( newItem ); } {{/isDateTime}} @@ -525,19 +525,19 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart, {{/required}} {{#required}} {{#isString}} - {{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}")))); + {{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("{{baseName}}")))); {{/isString}} {{^isString}} {{#isDateTime}} - {{setter}}(ModelBase::dateFromHttpContent(multipart->getContent(U("{{baseName}}")))); + {{setter}}(ModelBase::dateFromHttpContent(multipart->getContent(utility::conversions::to_string_t("{{baseName}}")))); {{/isDateTime}} {{^isDateTime}} {{#vendorExtensions.x-codegen-file}} - {{setter}}(multipart->getContent(U("{{baseName}}"))); + {{setter}}(multipart->getContent(utility::conversions::to_string_t("{{baseName}}"))); {{/vendorExtensions.x-codegen-file}} {{^vendorExtensions.x-codegen-file}} {{{datatype}}} new{{name}}({{{defaultValue}}}); - new{{name}}->fromMultiPart(multipart, U("{{baseName}}.")); + new{{name}}->fromMultiPart(multipart, utility::conversions::to_string_t("{{baseName}}.")); {{setter}}( new{{name}} ); {{/vendorExtensions.x-codegen-file}} {{/isDateTime}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/modelbase-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/modelbase-header.mustache index a74dfffbb74..909aa0520b3 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/modelbase-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/modelbase-header.mustache @@ -5,8 +5,8 @@ * This is the base class for all model classes */ -#ifndef ModelBase_H_ -#define ModelBase_H_ +#ifndef {{modelHeaderGuardPrefix}}_ModelBase_H_ +#define {{modelHeaderGuardPrefix}}_ModelBase_H_ {{{defaultInclude}}} #include "HttpContent.h" @@ -51,13 +51,13 @@ public: static bool boolFromJson(web::json::value& val); static std::shared_ptr fileFromJson(web::json::value& val); - static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::string_t& value, const utility::string_t& contentType = U("")); - static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::datetime& value, const utility::string_t& contentType = U("")); + static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::string_t& value, const utility::string_t& contentType = utility::conversions::to_string_t("")); + static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::datetime& value, const utility::string_t& contentType = utility::conversions::to_string_t("")); static std::shared_ptr toHttpContent( const utility::string_t& name, std::shared_ptr value ); - static std::shared_ptr toHttpContent( const utility::string_t& name, const web::json::value& value, const utility::string_t& contentType = U("application/json") ); - static std::shared_ptr toHttpContent( const utility::string_t& name, int32_t value, const utility::string_t& contentType = U("") ); - static std::shared_ptr toHttpContent( const utility::string_t& name, int64_t value, const utility::string_t& contentType = U("") ); - static std::shared_ptr toHttpContent( const utility::string_t& name, double value, const utility::string_t& contentType = U("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, const web::json::value& value, const utility::string_t& contentType = utility::conversions::to_string_t("application/json") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, int32_t value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, int64_t value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, double value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); static int64_t int64_tFromHttpContent(std::shared_ptr val); static int32_t int32_tFromHttpContent(std::shared_ptr val); @@ -77,4 +77,4 @@ public: } {{/modelNamespaceDeclarations}} -#endif /* ModelBase_H_ */ +#endif /* {{modelHeaderGuardPrefix}}_ModelBase_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/cpprest/modelbase-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/modelbase-source.mustache index 6df224f185a..8d15ede7b1f 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/modelbase-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/modelbase-source.mustache @@ -39,10 +39,10 @@ web::json::value ModelBase::toJson(bool value) { web::json::value ModelBase::toJson( std::shared_ptr content ) { web::json::value value; - value[U("ContentDisposition")] = ModelBase::toJson(content->getContentDisposition()); - value[U("ContentType")] = ModelBase::toJson(content->getContentType()); - value[U("FileName")] = ModelBase::toJson(content->getFileName()); - value[U("InputStream")] = web::json::value::string( ModelBase::toBase64(content->getData()) ); + value[utility::conversions::to_string_t("ContentDisposition")] = ModelBase::toJson(content->getContentDisposition()); + value[utility::conversions::to_string_t("ContentType")] = ModelBase::toJson(content->getContentType()); + value[utility::conversions::to_string_t("FileName")] = ModelBase::toJson(content->getFileName()); + value[utility::conversions::to_string_t("InputStream")] = web::json::value::string( ModelBase::toBase64(content->getData()) ); return value; } @@ -50,21 +50,21 @@ std::shared_ptr ModelBase::fileFromJson(web::json::value& val) { std::shared_ptr content(new HttpContent); - if(val.has_field(U("ContentDisposition"))) + if(val.has_field(utility::conversions::to_string_t("ContentDisposition"))) { - content->setContentDisposition( ModelBase::stringFromJson(val[U("ContentDisposition")]) ); + content->setContentDisposition( ModelBase::stringFromJson(val[utility::conversions::to_string_t("ContentDisposition")]) ); } - if(val.has_field(U("ContentType"))) + if(val.has_field(utility::conversions::to_string_t("ContentType"))) { - content->setContentType( ModelBase::stringFromJson(val[U("ContentType")]) ); + content->setContentType( ModelBase::stringFromJson(val[utility::conversions::to_string_t("ContentType")]) ); } - if(val.has_field(U("FileName"))) + if(val.has_field(utility::conversions::to_string_t("FileName"))) { - content->setFileName( ModelBase::stringFromJson(val[U("FileName")]) ); + content->setFileName( ModelBase::stringFromJson(val[utility::conversions::to_string_t("FileName")]) ); } - if(val.has_field(U("InputStream"))) + if(val.has_field(utility::conversions::to_string_t("InputStream"))) { - content->setData( ModelBase::fromBase64( ModelBase::stringFromJson(val[U("InputStream")]) ) ); + content->setData( ModelBase::fromBase64( ModelBase::stringFromJson(val[utility::conversions::to_string_t("InputStream")]) ) ); } return content; @@ -79,7 +79,7 @@ std::shared_ptr ModelBase::toHttpContent( const utility::string_t& { std::shared_ptr content(new HttpContent); content->setName( name ); - content->setContentDisposition( U("form-data") ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); content->setContentType( contentType ); content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(value) ) ) ); return content; @@ -88,7 +88,7 @@ std::shared_ptr ModelBase::toHttpContent( const utility::string_t& { std::shared_ptr content( new HttpContent ); content->setName( name ); - content->setContentDisposition( U("form-data") ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); content->setContentType( contentType ); content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(value.to_string(utility::datetime::ISO_8601) ) ) ) ); return content; @@ -107,7 +107,7 @@ std::shared_ptr ModelBase::toHttpContent( const utility::string_t& { std::shared_ptr content( new HttpContent ); content->setName( name ); - content->setContentDisposition( U("form-data") ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); content->setContentType( contentType ); content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(value.serialize()) ) ) ); return content; @@ -116,7 +116,7 @@ std::shared_ptr ModelBase::toHttpContent( const utility::string_t& { std::shared_ptr content( new HttpContent ); content->setName( name ); - content->setContentDisposition( U("form-data") ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); content->setContentType( contentType ); std::stringstream* valueAsStringStream = new std::stringstream(); (*valueAsStringStream) << value; @@ -127,7 +127,7 @@ std::shared_ptr ModelBase::toHttpContent( const utility::string_t& { std::shared_ptr content( new HttpContent ); content->setName( name ); - content->setContentDisposition( U("form-data") ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); content->setContentType( contentType ); std::stringstream* valueAsStringStream = new std::stringstream(); (*valueAsStringStream) << value; @@ -138,7 +138,7 @@ std::shared_ptr ModelBase::toHttpContent( const utility::string_t& { std::shared_ptr content( new HttpContent ); content->setName( name ); - content->setContentDisposition( U("form-data") ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); content->setContentType( contentType ); std::stringstream* valueAsStringStream = new std::stringstream(); (*valueAsStringStream) << value; @@ -244,12 +244,12 @@ std::shared_ptr ModelBase::fromBase64( const utility::string_t& en result->write( outBuf, 1 ); return result; default: - throw web::json::json_exception( U( "Invalid Padding in Base 64!" ) ); + throw web::json::json_exception( utility::conversions::to_string_t( "Invalid Padding in Base 64!" ).c_str() ); } } else { - throw web::json::json_exception( U( "Non-Valid Character in Base 64!" ) ); + throw web::json::json_exception( utility::conversions::to_string_t( "Non-Valid Character in Base 64!" ).c_str() ); } ++cursor; } @@ -277,7 +277,7 @@ float ModelBase::floatFromJson(web::json::value& val) } utility::string_t ModelBase::stringFromJson(web::json::value& val) { - return val.is_string() ? val.as_string() : U(""); + return val.is_string() ? val.as_string() : utility::conversions::to_string_t(""); } utility::datetime ModelBase::dateFromJson(web::json::value& val) diff --git a/modules/swagger-codegen/src/main/resources/cpprest/multipart-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/multipart-header.mustache index 917b8cf3cc5..17dba42a34a 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/multipart-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/multipart-header.mustache @@ -5,8 +5,8 @@ * This class represents a container for building a application/x-multipart-formdata requests. */ -#ifndef MultipartFormData_H_ -#define MultipartFormData_H_ +#ifndef {{modelHeaderGuardPrefix}}_MultipartFormData_H_ +#define {{modelHeaderGuardPrefix}}_MultipartFormData_H_ {{{defaultInclude}}} #include "IHttpBody.h" @@ -47,4 +47,4 @@ protected: } {{/modelNamespaceDeclarations}} -#endif /* MultipartFormData_H_ */ +#endif /* {{modelHeaderGuardPrefix}}_MultipartFormData_H_ */ 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 bc5905954eb..91fe1d8b323 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 @@ -15,8 +15,8 @@ mono nuget.exe install src/{{packageName}}/packages.config -o packages; echo "[INFO] Copy DLLs to the 'bin' folder" mkdir -p bin; -cp packages/Newtonsoft.Json.10.0.3/lib/{{targetFrameworkNuget}}/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; -cp packages/RestSharp.105.1.0/lib/{{targetFrameworkNuget}}/RestSharp.dll bin/RestSharp.dll; +cp packages/Newtonsoft.Json.{{#isNet40}}4.5.11{{/isNet40}}{{^isNet40}}10.0.3{{/isNet40}}/lib/{{targetFrameworkNuget}}/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; +cp packages/RestSharp.105.1.0/lib/{{#isNet40}}net4{{/isNet40}}{{^isNet40}}{{targetFrameworkNuget}}{{/isNet40}}/RestSharp.dll bin/RestSharp.dll; {{#generatePropertyChanged}} cp packages/Fody.1.29.4/Fody.dll bin/Fody.dll cp packages/PropertyChanged.Fody.1.51.3/PropertyChanged.Fody.dll bin/PropertyChanged.Fody.dll diff --git a/modules/swagger-codegen/src/main/resources/csharp/compile.mustache b/modules/swagger-codegen/src/main/resources/csharp/compile.mustache index 2ef0e06e902..dab5acb5869 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/compile.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/compile.mustache @@ -15,8 +15,8 @@ if not exist ".\nuget.exe" powershell -Command "(new-object System.Net.WebClient if not exist ".\bin" mkdir bin -copy packages\Newtonsoft.Json.10.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll -copy packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll bin\RestSharp.dll +copy packages\Newtonsoft.Json.{{#isNet40}}4.5.11{{/isNet40}}{{^isNet40}}10.0.3{{/isNet40}}\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll +copy packages\RestSharp.105.1.0\lib\{{#isNet40}}net4{{/isNet40}}{{^isNet40}}{{targetFrameworkNuget}}{{/isNet40}}\RestSharp.dll bin\RestSharp.dll {{#generatePropertyChanged}} copy packages\Fody.1.29.4\Fody.dll bin\Fody.dll copy packages\PropertyChanged.Fody.1.51.3\PropertyChanged.Fody.dll bin\PropertyChanged.Fody.dll diff --git a/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache b/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache new file mode 100644 index 00000000000..015e7142dbc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache @@ -0,0 +1,17 @@ + ///

+ /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} + /// + {{#description}} + /// {{description}} + {{/description}} + [JsonConverter(typeof(StringEnumConverter))] + {{>visibility}} enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} + { + {{#allowableValues}}{{#enumVars}} + /// + /// Enum {{name}} for {{{value}}} + /// + [EnumMember(Value = {{#isLong}}"{{/isLong}}{{#isInteger}}"{{/isInteger}}{{#isFloat}}"{{/isFloat}}{{#isDouble}}"{{/isDouble}}{{{value}}}{{#isLong}}"{{/isLong}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isFloat}}"{{/isFloat}})] + {{name}}{{#isLong}} = {{{value}}}{{/isLong}}{{#isInteger}} = {{{value}}}{{/isInteger}}{{^isInteger}} = {{-index}}{{/isInteger}}{{^-last}}, + {{/-last}}{{/enumVars}}{{/allowableValues}} + } diff --git a/modules/swagger-codegen/src/main/resources/csharp/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/csharp/git_push.sh.mustache index a9b0f28edfb..f65b794638f 100755 --- a/modules/swagger-codegen/src/main/resources/csharp/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache index 9d91ab60e0e..a7cf4473385 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache @@ -14,6 +14,6 @@ /// Enum {{name}} for value: {{{value}}} /// {{#isString}}[EnumMember(Value = "{{{value}}}")]{{/isString}} - {{name}}{{^isString}} = {{{value}}}{{/isString}}{{^-last}}, + {{name}}{{^isString}} = {{{value}}}{{/isString}}{{#isString}} = {{-index}}{{/isString}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}} }{{! NOTE: This model's enumVars is modified to look like CodegenProperty}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelInnerEnum.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelInnerEnum.mustache index 12ba61de347..bede8a16b5e 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelInnerEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelInnerEnum.mustache @@ -15,7 +15,7 @@ /// Enum {{name}} for value: {{{value}}} /// {{#isString}}[EnumMember(Value = "{{{value}}}")]{{/isString}} - {{name}}{{^isString}} = {{{value}}}{{/isString}}{{^-last}}, + {{name}}{{^isString}} = {{{value}}}{{/isString}}{{#isString}} = {{-index}}{{/isString}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}} } {{/isContainer}} 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 10218bf15c5..feb72290656 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache @@ -1,7 +1,7 @@ - + {{#generatePropertyChanged}} 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 1403975d651..8e102af48aa 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 @@ -2,5 +2,5 @@ - + diff --git a/modules/swagger-codegen/src/main/resources/dart/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/dart/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/dart/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/elixir/request_builder.ex.mustache b/modules/swagger-codegen/src/main/resources/elixir/request_builder.ex.mustache index 8b0480496c8..191832e9bdb 100644 --- a/modules/swagger-codegen/src/main/resources/elixir/request_builder.ex.mustache +++ b/modules/swagger-codegen/src/main/resources/elixir/request_builder.ex.mustache @@ -10,13 +10,13 @@ defmodule {{moduleName}}.RequestBuilder do ## Parameters - request (Map) - Collected request options - - m (String) - Request method + - m (atom) - Request method ## Returns Map """ - @spec method(map(), String.t) :: map() + @spec method(map(), atom) :: map() def method(request, m) do Map.put_new(request, :method, m) end @@ -51,7 +51,7 @@ defmodule {{moduleName}}.RequestBuilder do Map """ - @spec add_optional_params(map(), %{optional(:atom) => :atom}, keyword()) :: map() + @spec add_optional_params(map(), %{optional(atom) => atom}, keyword()) :: map() def add_optional_params(request, _, []), do: request def add_optional_params(request, definitions, [{key, value} | tail]) do case definitions do @@ -78,7 +78,7 @@ defmodule {{moduleName}}.RequestBuilder do Map """ - @spec add_param(map(), :atom, :atom, any()) :: map() + @spec add_param(map(), atom, atom, any()) :: map() def add_param(request, :body, :body, value), do: Map.put(request, :body, value) def add_param(request, :body, key, value) do request @@ -103,25 +103,20 @@ defmodule {{moduleName}}.RequestBuilder do ## Parameters - - env (Tesla.Env) - The response object - - struct - The shape of the struct to deserialize into + - arg1 (Tesla.Env.t | term) - The response object + - arg2 (:false | struct | [struct]) - The shape of the struct to deserialize into ## Returns {:ok, struct} on success - {:error, info} on failure + {:error, term} on failure """ - @spec decode(Tesla.Env.t) :: {:ok, struct()} | {:error, Tesla.Env.t} + @spec decode(Tesla.Env.t | term()) :: {:ok, struct()} | {:error, Tesla.Env.t} | {:error, term()} def decode(%Tesla.Env{status: 200, body: body}), do: Poison.decode(body) - def decode(response) do - {:error, response} - end - @spec decode(Tesla.Env.t, struct()) :: {:ok, struct()} | {:error, Tesla.Env.t} + def decode(response), do: {:error, response} + + @spec decode(Tesla.Env.t | term(), :false | struct() | [struct()]) :: {:ok, struct()} | {:error, Tesla.Env.t} | {:error, term()} def decode(%Tesla.Env{status: 200} = env, false), do: {:ok, env} - def decode(%Tesla.Env{status: 200, body: body}, struct) do - Poison.decode(body, as: struct) - end - def decode(response, _struct) do - {:error, response} - end + def decode(%Tesla.Env{status: 200, body: body}, struct), do: Poison.decode(body, as: struct) + def decode(response, _struct), do: {:error, response} end diff --git a/modules/swagger-codegen/src/main/resources/erlang-client/README.mustache b/modules/swagger-codegen/src/main/resources/erlang-client/README.mustache new file mode 100644 index 00000000000..f3eab0b5528 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-client/README.mustache @@ -0,0 +1,5 @@ +# Swagger client server library for Erlang + +## Overview + +An Erlang client stub generated by [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) given an OpenAPI/Swagger spec. diff --git a/modules/swagger-codegen/src/main/resources/erlang-client/api.mustache b/modules/swagger-codegen/src/main/resources/erlang-client/api.mustache new file mode 100644 index 00000000000..a14ee991912 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-client/api.mustache @@ -0,0 +1,48 @@ +-module({{classname}}_api). + +-export([{{#operations}}{{#operation}}{{^-first}}, + {{/-first}}{{operationId}}/{{#length}}{{allParams}}{{/length}}{{/operation}}{{/operations}}]). + +-define(BASE_URL, <<"{{{basePath}}}">>). + +{{#operations}} + {{#operation}} +%% @doc {{summary}} +{{^notes.isEmpty}} +%% {{notes}} +{{/notes.isEmpty}} +-spec {{operationId}}({{#allParams}}{{^-first}}, {{/-first}}{{dataType}}{{/allParams}}) -> {{#returnType}}{ok, list(), {{returnType}}} | {error, string()}{{/returnType}}{{^returnType}}ok | {error, integer()}{{/returnType}}. +{{operationId}}({{#allParams}}{{^-first}}, {{/-first}}{{paramName}}{{/allParams}}) -> + Method = {{httpMethod}}, + Path = ["{{{replacedPathName}}}"], + QS = {{#queryParams.isEmpty}}[]{{/queryParams.isEmpty}}{{^queryParams.isEmpty}}lists:flatten([{{#queryParams}}{{^-first}}, {{/-first}}{{#qsEncode}}{{this}}{{/qsEncode}}{{/queryParams}}]){{/queryParams.isEmpty}}, + Headers = [{{^headerParams.isEmpty}}{{#headerParams}}{{^-first}}, {{/-first}}{<<"{{baseName}}">>, {{paramName}}}{{/headerParams}}{{/headerParams.isEmpty}}], + Body1 = {{^formParams.isEmpty}}{form, [{{#formParams}}{{^-first}}, {{/-first}}{<<"{{baseName}}">>, {{paramName}}}{{/formParams}}]}{{/formParams.isEmpty}}{{#formParams.isEmpty}}{{#bodyParams.isEmpty}}[]{{/bodyParams.isEmpty}}{{^bodyParams.isEmpty}}{{#bodyParams}}{{paramName}}{{/bodyParams}}{{/bodyParams.isEmpty}}{{/formParams.isEmpty}}, + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of +{{#returnType}} + {{#responses}} +{{#isDefault}} + {ok, {{code}}, RespHeaders, ClientRef} -> + {ok, Body} = hackney:body(ClientRef), + {ok, RespHeaders, jsx:decode(Body, [returns_maps, {labels, attempt_atom}])}{{#hasMore}}; {{/hasMore}} +{{/isDefault}} +{{^isDefault}} + {ok, {{code}}, _RespHeaders, _ClientRef} -> + {error, "{{message}}"}{{#hasMore}}; {{/hasMore}} +{{/isDefault}} + {{/responses}} +{{/returnType}} +{{^returnType}} + {ok, 200, _RespHeaders, _ClientRef} -> + ok; + {ok, Status, _RespHeaders, _ClientRef} -> + {error, Status} +{{/returnType}} + end. + + {{/operation}} + +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/erlang-client/app.src.mustache b/modules/swagger-codegen/src/main/resources/erlang-client/app.src.mustache new file mode 100644 index 00000000000..8cf0543467a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-client/app.src.mustache @@ -0,0 +1,17 @@ +{application, {{packageName}}, + [{description, {{#appDescription}}"{{appDescription}}"{{/appDescription}}{{^appDescription}}"Swagger client library"{{/appDescription}}}, + {vsn, "{{apiVersion}}"}, + {registered, []}, + {applications, + [kernel, + stdlib, + ssl, + hackney + ]}, + {env, []}, + {modules, []}, + + {maintainers, []}, + {licenses, [{{#licenseInfo}}"{{licenseInfo}}"{{/licenseInfo}}]}, + {links, [{{#infoUrl}}"{{infoUrl}}"{{/infoUrl}}]} +]}. diff --git a/modules/swagger-codegen/src/main/resources/erlang-client/model.mustache b/modules/swagger-codegen/src/main/resources/erlang-client/model.mustache new file mode 100644 index 00000000000..da0e8672ca0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-client/model.mustache @@ -0,0 +1,21 @@ +{{#models}} +{{#model}} +-module({{classname}}). + +-export_type([{{classname}}/0, + encode/1, + decode/1]). + +-type {{classname}}() :: + #{ {{#vars}}'{{name}}' {{#required}}:={{/required}}{{^required}}=>{{/required}} {{{datatype}}}{{#hasMore}}, + {{/hasMore}}{{/vars}} + }. + +encode(#{ {{#vars}}'{{name}}' := {{{nameInCamelCase}}}{{#hasMore}}, + {{/hasMore}}{{/vars}} + }) -> + #{ {{#vars}}'{{baseName}}' => {{{nameInCamelCase}}}{{#hasMore}}, + {{/hasMore}}{{/vars}} + } +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/erlang-client/rebar.config.mustache b/modules/swagger-codegen/src/main/resources/erlang-client/rebar.config.mustache new file mode 100644 index 00000000000..abe84a1a9f3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-client/rebar.config.mustache @@ -0,0 +1,3 @@ +{erl_opts, [debug_info, warnings_as_errors, warn_untyped_record]}. + +{deps, [jsx, hackney]}. diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/api.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/api.mustache index d948bbae4b2..ed49d5a0a78 100644 --- a/modules/swagger-codegen/src/main/resources/erlang-server/api.mustache +++ b/modules/swagger-codegen/src/main/resources/erlang-server/api.mustache @@ -4,6 +4,8 @@ -export([request_param_info/2]). -export([populate_request/3]). -export([validate_response/4]). +%% exported to silence swagger complains +-export([get_value/3, validate_response_body/4]). -type operation_id() :: atom(). -type request_param() :: atom(). @@ -212,7 +214,7 @@ validate(Rule = {enum, Values}, Name, Value, _ValidatorState) -> end; validate(Rule = {max, Max}, Name, Value, _ValidatorState) -> - case Value >= Max of + case Value =< Max of true -> ok; false -> validation_error(Rule, Name) end; @@ -224,7 +226,7 @@ validate(Rule = {exclusive_max, ExclusiveMax}, Name, Value, _ValidatorState) -> end; validate(Rule = {min, Min}, Name, Value, _ValidatorState) -> - case Value =< Min of + case Value >= Min of true -> ok; false -> validation_error(Rule, Name) end; @@ -290,6 +292,8 @@ validation_error(ViolatedRule, Name) -> validation_error(ViolatedRule, Name, Info) -> throw({wrong_param, Name, ViolatedRule, Info}). +-spec get_value(body | qs_val | header | binding, Name :: any(), Req0 :: cowboy_req:req()) -> + {Value :: any(), Req :: cowboy_req:req()}. get_value(body, _Name, Req0) -> {ok, Body, Req} = cowboy_req:body(Req0), Value = prepare_body(Body), diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/auth.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/auth.mustache index bf988fac348..c81f989fd38 100644 --- a/modules/swagger-codegen/src/main/resources/erlang-server/auth.mustache +++ b/modules/swagger-codegen/src/main/resources/erlang-server/auth.mustache @@ -24,8 +24,12 @@ authorize_api_key(LogicHandler, OperationID, From, KeyParam, Req0) -> ApiKey ), case Result of + {{#authMethods}} + {{#isApiKey}} {true, Context} -> {true, Context, Req}; + {{/isApiKey}} + {{/authMethods}} false -> AuthHeader = <<"">>, {false, AuthHeader, Req} diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/handler.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/handler.mustache index 4c0bebc5ff4..4ed2e21a2ae 100644 --- a/modules/swagger-codegen/src/main/resources/erlang-server/handler.mustache +++ b/modules/swagger-codegen/src/main/resources/erlang-server/handler.mustache @@ -94,13 +94,15 @@ is_authorized( end; {{/isApiKey}} {{/authMethods}} +{{/operation}}{{/operations}} {{^authMethods}} is_authorized(Req, State) -> - {true, Req, State}; + {true, Req, State}. {{/authMethods}} -{{/operation}}{{/operations}} +{{#authMethods}} is_authorized(Req, State) -> {{false, <<"">>}, Req, State}. +{{/authMethods}} -spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) -> { diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/logic_handler.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/logic_handler.mustache index cb4ba201bf4..8baf9b81c20 100644 --- a/modules/swagger-codegen/src/main/resources/erlang-server/logic_handler.mustache +++ b/modules/swagger-codegen/src/main/resources/erlang-server/logic_handler.mustache @@ -1,11 +1,7 @@ -module({{packageName}}_logic_handler). -export([handle_request/4]). -{{#authMethods}} - {{#isApiKey}} -export([authorize_api_key/3]). - {{/isApiKey}} -{{/authMethods}} -type context() :: #{binary() => any()}. -type handler_response() ::{ Status :: cowboy:http_status(), @@ -48,3 +44,9 @@ authorize_api_key(Handler, OperationID, ApiKey) -> Handler:authorize_api_key(OperationID, ApiKey). {{/isApiKey}} {{/authMethods}} +{{^authMethods}} +-spec authorize_api_key(Handler :: atom(), OperationID :: {{packageName}}_api:operation_id(), ApiKey :: binary()) -> + Result :: false. +authorize_api_key(_Handler, _OperationID, _ApiKey) -> + false. +{{/authMethods}} diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/server.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/server.mustache index 90a6388ea5d..348a473e9e3 100644 --- a/modules/swagger-codegen/src/main/resources/erlang-server/server.mustache +++ b/modules/swagger-codegen/src/main/resources/erlang-server/server.mustache @@ -9,6 +9,7 @@ -spec child_spec( ID :: any(), #{ ip => inet:ip_address(), port => inet:port_number(), + logic_handler => module(), net_opts => [] }) -> supervisor:child_spec(). diff --git a/modules/swagger-codegen/src/main/resources/flash/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/flash/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/flash/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/flash/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__model.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__model.mustache index 764211e2120..98b56e3d154 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__model.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__model.mustache @@ -1,6 +1,7 @@ # coding: utf-8 +# flake8: noqa from __future__ import absolute_import # import models into model package -{{#models}}{{#model}}from .{{classFilename}} import {{classname}}{{/model}} +{{#models}}{{#model}}from {{modelPackage}}.{{classFilename}} import {{classname}}{{/model}} {{/models}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__test.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__test.mustache index 77b10c3a012..9cea80bc630 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__test.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__test.mustache @@ -1,8 +1,10 @@ -from flask_testing import TestCase -from ..encoder import JSONEncoder -import connexion import logging +import connexion +from flask_testing import TestCase + +from {{packageName}}.encoder import JSONEncoder + class BaseTestCase(TestCase): diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/__main__.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/__main__.mustache index efbea8409c5..10756347223 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/__main__.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/__main__.mustache @@ -6,11 +6,16 @@ {{/supportPython2}} import connexion -from .encoder import JSONEncoder + +from {{packageName}} import encoder + + +def main(): + app = connexion.App(__name__, specification_dir='./swagger/') + app.app.json_encoder = encoder.JSONEncoder + app.add_api('swagger.yaml', arguments={'title': '{{appName}}'}) + app.run(port={{serverPort}}) if __name__ == '__main__': - app = connexion.App(__name__, specification_dir='./swagger/') - app.app.json_encoder = JSONEncoder - app.add_api('swagger.yaml', arguments={'title': '{{appDescription}}'}) - app.run(port={{serverPort}}) + main() diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/base_model_.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/base_model_.mustache index 6e3464c7019..54517a06d53 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/base_model_.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/base_model_.mustache @@ -1,38 +1,39 @@ -from pprint import pformat +import pprint + +import six {{^supportPython2}} -from typing import TypeVar, Type +import typing {{/supportPython2}} -from six import iteritems -from ..util import deserialize_model + +from {{packageName}} import util {{^supportPython2}} -T = TypeVar('T') +T = typing.TypeVar('T') {{/supportPython2}} class Model(object): - # swaggerTypes: The key is attribute name and the value is attribute type. + # swaggerTypes: The key is attribute name and the + # value is attribute type. swagger_types = {} - # attributeMap: The key is attribute name and the value is json key in definition. + # attributeMap: The key is attribute name and the + # value is json key in definition. attribute_map = {} @classmethod - def from_dict(cls{{^supportPython2}}: Type[T]{{/supportPython2}}, dikt){{^supportPython2}} -> T{{/supportPython2}}: - """ - Returns the dict as a model - """ - return deserialize_model(dikt, cls) + def from_dict(cls{{^supportPython2}}: typing.Type[T]{{/supportPython2}}, dikt){{^supportPython2}} -> T{{/supportPython2}}: + """Returns the dict as a model""" + return util.deserialize_model(dikt, cls) def to_dict(self): - """ - Returns the model properties as a dict + """Returns the model properties as a dict :rtype: dict """ result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -53,27 +54,20 @@ class Model(object): return result def to_str(self): - """ - Returns the string representation of the model + """Returns the string representation of the model :rtype: str """ - return pformat(self.to_dict()) + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """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 \ No newline at end of file + """Returns true if both objects are not equal""" + return not self == other diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache index 8fc01dbd7ac..b865222c7d2 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache @@ -1,18 +1,18 @@ import connexion -{{#imports}}{{import}} +import six + +{{#imports}}{{import}} # noqa: E501 {{/imports}} -from datetime import date, datetime -from typing import List, Dict -from six import iteritems -from ..util import deserialize_date, deserialize_datetime +from {{packageName}} import util {{#operations}} {{#operation}} -def {{operationId}}({{#allParams}}{{paramName}}{{^required}}=None{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}): - """ - {{#summary}}{{.}}{{/summary}}{{^summary}}{{operationId}}{{/summary}} - {{#notes}}{{.}}{{/notes}} +def {{operationId}}({{#allParams}}{{paramName}}{{^required}}=None{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}): # noqa: E501 + """{{#summary}}{{.}}{{/summary}}{{^summary}}{{operationId}}{{/summary}} + + {{#notes}}{{.}}{{/notes}} # noqa: E501 + {{#allParams}} :param {{paramName}}: {{description}} {{^isContainer}} @@ -55,15 +55,15 @@ def {{operationId}}({{#allParams}}{{paramName}}{{^required}}=None{{/required}}{{ {{#allParams}} {{^isContainer}} {{#isDate}} - {{paramName}} = deserialize_date({{paramName}}) + {{paramName}} = util.deserialize_date({{paramName}}) {{/isDate}} {{#isDateTime}} - {{paramName}} = deserialize_datetime({{paramName}}) + {{paramName}} = util.deserialize_datetime({{paramName}}) {{/isDateTime}} {{^isPrimitiveType}} {{^isFile}} if connexion.request.is_json: - {{paramName}} = {{baseType}}.from_dict(connexion.request.get_json()) + {{paramName}} = {{baseType}}.from_dict(connexion.request.get_json()) # noqa: E501 {{/isFile}} {{/isPrimitiveType}} {{/isContainer}} @@ -71,15 +71,15 @@ def {{operationId}}({{#allParams}}{{paramName}}{{^required}}=None{{/required}}{{ {{#items}} {{#isDate}} if connexion.request.is_json: - {{paramName}} = [deserialize_date(s) for s in connexion.request.get_json()] + {{paramName}} = [util.deserialize_date(s) for s in connexion.request.get_json()] # noqa: E501 {{/isDate}} {{#isDateTime}} if connexion.request.is_json: - {{paramName}} = [deserialize_datetime(s) for s in connexion.request.get_json()] + {{paramName}} = [util.deserialize_datetime(s) for s in connexion.request.get_json()] # noqa: E501 {{/isDateTime}} {{#complexType}} if connexion.request.is_json: - {{paramName}} = [{{complexType}}.from_dict(d) for d in connexion.request.get_json()] + {{paramName}} = [{{complexType}}.from_dict(d) for d in connexion.request.get_json()] # noqa: E501 {{/complexType}} {{/items}} {{/isListContainer}} @@ -87,15 +87,15 @@ def {{operationId}}({{#allParams}}{{paramName}}{{^required}}=None{{/required}}{{ {{#items}} {{#isDate}} if connexion.request.is_json: - {{paramName}} = {k: deserialize_date(v) for k, v in iteritems(connexion.request.get_json())} + {{paramName}} = {k: util.deserialize_date(v) for k, v in six.iteritems(connexion.request.get_json())} # noqa: E501 {{/isDate}} {{#isDateTime}} if connexion.request.is_json: - {{paramName}} = {k: deserialize_datetime(v) for k, v in iteritems(connexion.request.get_json())} + {{paramName}} = {k: util.deserialize_datetime(v) for k, v in six.iteritems(connexion.request.get_json())} # noqa: E501 {{/isDateTime}} {{#complexType}} if connexion.request.is_json: - {{paramName}} = {k: {{baseType}}.from_dict(v) for k, v in iteritems(connexion.request.get_json())} + {{paramName}} = {k: {{baseType}}.from_dict(v) for k, v in six.iteritems(connexion.request.get_json())} # noqa: E501 {{/complexType}} {{/items}} {{/isMapContainer}} diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/controller_test.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/controller_test.mustache index 7b202bb9126..a41b12f2c21 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/controller_test.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/controller_test.mustache @@ -2,20 +2,20 @@ from __future__ import absolute_import -{{#imports}}{{import}} -{{/imports}} -from . import BaseTestCase -from six import BytesIO from flask import json +from six import BytesIO + +{{#imports}}{{import}} # noqa: E501 +{{/imports}} +from {{packageName}}.test import BaseTestCase class {{#operations}}Test{{classname}}(BaseTestCase): - """ {{classname}} integration test stubs """ + """{{classname}} integration test stubs""" {{#operation}} def test_{{operationId}}(self): - """ - Test case for {{{operationId}}} + """Test case for {{{operationId}}} {{{summary}}} """ @@ -31,15 +31,17 @@ class {{#operations}}Test{{classname}}(BaseTestCase): {{#formParams}} {{#-first}}data = dict({{/-first}}{{^-first}} {{/-first}}{{paramName}}={{{example}}}{{#hasMore}},{{/hasMore}}{{#-last}}){{/-last}} {{/formParams}} - response = self.client.open('{{#contextPath}}{{{.}}}{{/contextPath}}{{{path}}}'{{#pathParams}}{{#-first}}.format({{/-first}}{{paramName}}={{{example}}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}){{/hasMore}}{{/pathParams}}, - method='{{httpMethod}}'{{#bodyParam}}, - data=json.dumps({{paramName}}){{^consumes}}, - content_type='application/json'{{/consumes}}{{/bodyParam}}{{#headerParams}}{{#-first}}, - headers=headers{{/-first}}{{/headerParams}}{{#formParams}}{{#-first}}, - data=data{{/-first}}{{/formParams}}{{#consumes}}{{#-first}}, - content_type='{{{mediaType}}}'{{/-first}}{{/consumes}}{{#queryParams}}{{#-first}}, - query_string=query_string{{/-first}}{{/queryParams}}) - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '{{#contextPath}}{{{.}}}{{/contextPath}}{{{path}}}'{{#pathParams}}{{#-first}}.format({{/-first}}{{paramName}}={{{example}}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}){{/hasMore}}{{/pathParams}}, + method='{{httpMethod}}'{{#bodyParam}}, + data=json.dumps({{paramName}}){{^consumes}}, + content_type='application/json'{{/consumes}}{{/bodyParam}}{{#headerParams}}{{#-first}}, + headers=headers{{/-first}}{{/headerParams}}{{#formParams}}{{#-first}}, + data=data{{/-first}}{{/formParams}}{{#consumes}}{{#-first}}, + content_type='{{{mediaType}}}'{{/-first}}{{/consumes}}{{#queryParams}}{{#-first}}, + query_string=query_string{{/-first}}{{/queryParams}}) + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/encoder.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/encoder.mustache index 996d74f21e7..e303a0e41a7 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/encoder.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/encoder.mustache @@ -1,6 +1,8 @@ -from six import iteritems -from {{modelPackage}}.base_model_ import Model from connexion.apps.flask_app import FlaskJSONEncoder +import six + +from {{modelPackage}}.base_model_ import Model + class JSONEncoder(FlaskJSONEncoder): include_nulls = False @@ -8,11 +10,11 @@ class JSONEncoder(FlaskJSONEncoder): def default(self, o): if isinstance(o, Model): dikt = {} - for attr, _ in iteritems(o.swagger_types): + for attr, _ in six.iteritems(o.swagger_types): value = getattr(o, attr) if value is None and not self.include_nulls: continue attr = o.attribute_map[attr] dikt[attr] = value return dikt - return FlaskJSONEncoder.default(self, o) \ No newline at end of file + return FlaskJSONEncoder.default(self, o) diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/git_push.sh.mustache index e153ce23ecf..f65b794638f 100755 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/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 @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/model.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/model.mustache index 761492870bf..ba289ef4f8c 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/model.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/model.mustache @@ -1,73 +1,74 @@ # coding: utf-8 from __future__ import absolute_import -{{#imports}}{{import}} +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from {{modelPackage}}.base_model_ import Model +{{#imports}}{{import}} # noqa: F401,E501 {{/imports}} -from .base_model_ import Model -from datetime import date, datetime -from typing import List, Dict -from ..util import deserialize_model +from {{packageName}} import util {{#models}} {{#model}} class {{classname}}(Model): - """ - 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. + """{{#allowableValues}} -{{#allowableValues}} """ allowed enum values """ {{#enumVars}} - {{name}} = {{{value}}} -{{/enumVars}} -{{/allowableValues}} + {{name}} = {{{value}}}{{^-last}} +{{/-last}} +{{/enumVars}}{{/allowableValues}} - def __init__(self{{#vars}}, {{name}}{{^supportPython2}}: {{datatype}}{{/supportPython2}}={{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{/vars}}): - """ - {{classname}} - a model defined in Swagger + def __init__(self{{#vars}}, {{name}}{{^supportPython2}}: {{datatype}}{{/supportPython2}}={{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{/vars}}): # noqa: E501 + """{{classname}} - a model defined in Swagger {{#vars}} - :param {{name}}: The {{name}} of this {{classname}}. + :param {{name}}: The {{name}} of this {{classname}}. # noqa: E501 :type {{name}}: {{datatype}} {{/vars}} """ self.swagger_types = { - {{#vars}}'{{name}}': {{{datatype}}}{{#hasMore}}, - {{/hasMore}}{{/vars}} +{{#vars}} + '{{name}}': {{{datatype}}}{{#hasMore}},{{/hasMore}} +{{/vars}} } self.attribute_map = { - {{#vars}}'{{name}}': '{{baseName}}'{{#hasMore}}, - {{/hasMore}}{{/vars}} - } - {{#vars}} + '{{name}}': '{{baseName}}'{{#hasMore}},{{/hasMore}} +{{/vars}} + } +{{#vars}}{{#-first}} +{{/-first}} self._{{name}} = {{name}} {{/vars}} @classmethod def from_dict(cls, dikt){{^supportPython2}} -> '{{classname}}'{{/supportPython2}}: - """ - Returns the dict as a model + """Returns the dict as a model :param dikt: A dict. :type: dict - :return: The {{name}} of this {{classname}}. + :return: The {{name}} of this {{classname}}. # noqa: E501 :rtype: {{classname}} """ - return deserialize_model(dikt, cls) -{{#vars}}{{#-first}} + return util.deserialize_model(dikt, cls){{#vars}}{{#-first}} + {{/-first}} @property def {{name}}(self){{^supportPython2}} -> {{datatype}}{{/supportPython2}}: - """ - Gets the {{name}} of this {{classname}}. + """Gets the {{name}} of this {{classname}}. + {{#description}} - {{{description}}} + {{{description}}} # noqa: E501 {{/description}} :return: The {{name}} of this {{classname}}. @@ -77,31 +78,31 @@ class {{classname}}(Model): @{{name}}.setter def {{name}}(self, {{name}}{{^supportPython2}}: {{datatype}}{{/supportPython2}}): - """ - Sets the {{name}} of this {{classname}}. + """Sets the {{name}} of this {{classname}}. + {{#description}} - {{{description}}} + {{{description}}} # noqa: E501 {{/description}} :param {{name}}: The {{name}} of this {{classname}}. :type {{name}}: {{datatype}} """ {{#isEnum}} - allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] + allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] # noqa: E501 {{#isContainer}} {{#isListContainer}} if not set({{{name}}}).issubset(set(allowed_values)): raise ValueError( - "Invalid values for `{{{name}}}` [{0}], must be a subset of [{1}]" - .format(", ".join(map(str, set({{{name}}})-set(allowed_values))), + "Invalid values for `{{{name}}}` [{0}], must be a subset of [{1}]" # noqa: E501 + .format(", ".join(map(str, set({{{name}}}) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) {{/isListContainer}} {{#isMapContainer}} if not set({{{name}}}.keys()).issubset(set(allowed_values)): raise ValueError( - "Invalid keys in `{{{name}}}` [{0}], must be a subset of [{1}]" - .format(", ".join(map(str, set({{{name}}}.keys())-set(allowed_values))), + "Invalid keys in `{{{name}}}` [{0}], must be a subset of [{1}]" # noqa: E501 + .format(", ".join(map(str, set({{{name}}}.keys()) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) {{/isMapContainer}} @@ -117,42 +118,44 @@ class {{classname}}(Model): {{^isEnum}} {{#required}} if {{name}} is None: - raise ValueError("Invalid value for `{{name}}`, must not be `None`") + raise ValueError("Invalid value for `{{name}}`, must not be `None`") # noqa: E501 {{/required}} {{#hasValidation}} {{#maxLength}} if {{name}} is not None and len({{name}}) > {{maxLength}}: - raise ValueError("Invalid value for `{{name}}`, length must be less than or equal to `{{maxLength}}`") + raise ValueError("Invalid value for `{{name}}`, length must be less than or equal to `{{maxLength}}`") # noqa: E501 {{/maxLength}} {{#minLength}} if {{name}} is not None and len({{name}}) < {{minLength}}: - raise ValueError("Invalid value for `{{name}}`, length must be greater than or equal to `{{minLength}}`") + raise ValueError("Invalid value for `{{name}}`, length must be greater than or equal to `{{minLength}}`") # noqa: E501 {{/minLength}} {{#maximum}} - if {{name}} is not None and {{name}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}: - raise ValueError("Invalid value for `{{name}}`, must be a value less than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}`{{maximum}}`") + if {{name}} is not None and {{name}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}: # noqa: E501 + raise ValueError("Invalid value for `{{name}}`, must be a value less than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}`{{maximum}}`") # noqa: E501 {{/maximum}} {{#minimum}} - if {{name}} is not None and {{name}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}: - raise ValueError("Invalid value for `{{name}}`, must be a value greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}`{{minimum}}`") + if {{name}} is not None and {{name}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}: # noqa: E501 + raise ValueError("Invalid value for `{{name}}`, must be a value greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}`{{minimum}}`") # noqa: E501 {{/minimum}} {{#pattern}} - if {{name}} is not None and 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}}}`") + if {{name}} is not None and not re.search('{{{vendorExtensions.x-regex}}}', {{name}}{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): # noqa: E501 + raise ValueError("Invalid value for `{{name}}`, must be a follow pattern or equal to `{{{pattern}}}`") # noqa: E501 {{/pattern}} {{#maxItems}} if {{name}} is not None and len({{name}}) > {{maxItems}}: - raise ValueError("Invalid value for `{{name}}`, number of items must be less than or equal to `{{maxItems}}`") + raise ValueError("Invalid value for `{{name}}`, number of items must be less than or equal to `{{maxItems}}`") # noqa: E501 {{/maxItems}} {{#minItems}} if {{name}} is not None and len({{name}}) < {{minItems}}: - raise ValueError("Invalid value for `{{name}}`, number of items must be greater than or equal to `{{minItems}}`") + raise ValueError("Invalid value for `{{name}}`, number of items must be greater than or equal to `{{minItems}}`") # noqa: E501 {{/minItems}} {{/hasValidation}} {{/isEnum}} - self._{{name}} = {{name}} + self._{{name}} = {{name}}{{^-last}} +{{/-last}} {{/vars}} + {{/model}} -{{/models}} +{{/models}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/setup.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/setup.mustache index dd2dea6aeed..56f8bc1ec17 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/setup.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/setup.mustache @@ -26,6 +26,8 @@ setup( packages=find_packages(), package_data={'': ['swagger/swagger.yaml']}, include_package_data=True, + entry_points={ + 'console_scripts': ['{{packageName}}={{packageName}}.__main__:main']}, long_description="""\ {{appDescription}} """ diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/tox.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/tox.mustache index 5ad8fe6c031..3efa994317d 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/tox.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/tox.mustache @@ -4,7 +4,7 @@ envlist = {{#supportPython2}}py27, {{/supportPython2}}py35 [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/flaskConnexion/util.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/util.mustache index 40c72d43ebd..527d1424c3d 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/util.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/util.mustache @@ -1,11 +1,11 @@ -from typing import GenericMeta -from datetime import datetime, date -from six import integer_types, iteritems +import datetime + +import six +import typing def _deserialize(data, klass): - """ - Deserializes dict, list, str into an object. + """Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. @@ -15,15 +15,15 @@ def _deserialize(data, klass): if data is None: return None - if klass in integer_types or klass in (float, str, bool): + if klass in six.integer_types or klass in (float, str, bool): return _deserialize_primitive(data, klass) elif klass == object: return _deserialize_object(data) - elif klass == date: + elif klass == datetime.date: return deserialize_date(data) - elif klass == datetime: + elif klass == datetime.datetime: return deserialize_datetime(data) - elif type(klass) == GenericMeta: + elif type(klass) == typing.GenericMeta: if klass.__extra__ == list: return _deserialize_list(data, klass.__args__[0]) if klass.__extra__ == dict: @@ -33,8 +33,7 @@ def _deserialize(data, klass): def _deserialize_primitive(data, klass): - """ - Deserializes to primitive type. + """Deserializes to primitive type. :param data: data to deserialize. :param klass: class literal. @@ -45,15 +44,14 @@ def _deserialize_primitive(data, klass): try: value = klass(data) except UnicodeEncodeError: - value = unicode(data) + value = six.u(data) except TypeError: value = data return value def _deserialize_object(value): - """ - Return a original value. + """Return a original value. :return: object. """ @@ -61,8 +59,7 @@ def _deserialize_object(value): def deserialize_date(string): - """ - Deserializes string to date. + """Deserializes string to date. :param string: str. :type string: str @@ -77,8 +74,7 @@ def deserialize_date(string): def deserialize_datetime(string): - """ - Deserializes string to datetime. + """Deserializes string to datetime. The string should be in iso8601 datetime format. @@ -95,8 +91,7 @@ def deserialize_datetime(string): def deserialize_model(data, klass): - """ - Deserializes list or dict to model. + """Deserializes list or dict to model. :param data: dict, list. :type data: dict | list @@ -108,7 +103,7 @@ def deserialize_model(data, klass): if not instance.swagger_types: return data - for attr, attr_type in iteritems(instance.swagger_types): + for attr, attr_type in six.iteritems(instance.swagger_types): if data is not None \ and instance.attribute_map[attr] in data \ and isinstance(data, (list, dict)): @@ -119,8 +114,7 @@ def deserialize_model(data, klass): def _deserialize_list(data, boxed_type): - """ - Deserializes a list and its elements. + """Deserializes a list and its elements. :param data: list to deserialize. :type data: list @@ -133,10 +127,8 @@ def _deserialize_list(data, boxed_type): for sub_data in data] - def _deserialize_dict(data, boxed_type): - """ - Deserializes a dict and its elements. + """Deserializes a dict and its elements. :param data: dict to deserialize. :type data: dict @@ -146,4 +138,4 @@ def _deserialize_dict(data, boxed_type): :rtype: dict """ return {k: _deserialize(v, boxed_type) - for k, v in iteritems(data)} + for k, v in six.iteritems(data)} diff --git a/modules/swagger-codegen/src/main/resources/go/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/go/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/go/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/go/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/haskell-http-client/API.mustache b/modules/swagger-codegen/src/main/resources/haskell-http-client/API.mustache index 0ed4d1093a2..d86611826c7 100644 --- a/modules/swagger-codegen/src/main/resources/haskell-http-client/API.mustache +++ b/modules/swagger-codegen/src/main/resources/haskell-http-client/API.mustache @@ -74,10 +74,11 @@ import qualified Prelude as P -- {{/vendorExtensions.x-hasUnknownReturn}} {{operationId}} :: {{#vendorExtensions.x-hasBodyOrFormParam}}(Consumes {{{vendorExtensions.x-operationType}}} {{>_contentType}}{{#allParams}}{{#isBodyParam}}{{#required}}, MimeRender {{>_contentType}} {{#vendorExtensions.x-paramNameType}}{{{.}}}{{/vendorExtensions.x-paramNameType}}{{^vendorExtensions.x-paramNameType}}{{{dataType}}}{{/vendorExtensions.x-paramNameType}}{{/required}}{{/isBodyParam}}{{/allParams}}) - => {{^vendorExtensions.x-inlineContentType}}contentType -- ^ request content-type ('MimeType') - -> {{/vendorExtensions.x-inlineContentType}}{{/vendorExtensions.x-hasBodyOrFormParam}}{{#allParams}}{{#required}}{{#vendorExtensions.x-paramNameType}}{{{.}}}{{/vendorExtensions.x-paramNameType}}{{^vendorExtensions.x-paramNameType}}{{{dataType}}}{{/vendorExtensions.x-paramNameType}} -- ^ "{{{paramName}}}"{{#description}} - {{/description}} {{{description}}} - -> {{/required}}{{/allParams}}{{requestType}} {{{vendorExtensions.x-operationType}}} {{#vendorExtensions.x-hasBodyOrFormParam}}{{>_contentType}}{{/vendorExtensions.x-hasBodyOrFormParam}}{{^vendorExtensions.x-hasBodyOrFormParam}}MimeNoContent{{/vendorExtensions.x-hasBodyOrFormParam}} {{vendorExtensions.x-returnType}} -{{operationId}} {{#vendorExtensions.x-hasBodyOrFormParam}}{{^vendorExtensions.x-inlineContentType}}_ {{/vendorExtensions.x-inlineContentType}}{{/vendorExtensions.x-hasBodyOrFormParam}}{{#allParams}}{{#required}}{{#isBodyParam}}{{{paramName}}}{{/isBodyParam}}{{^isBodyParam}}({{{vendorExtensions.x-paramNameType}}} {{{paramName}}}){{/isBodyParam}} {{/required}}{{/allParams}}= + => {{^vendorExtensions.x-inlineContentType}}ContentType contentType -- ^ request content-type ('MimeType') + -> {{/vendorExtensions.x-inlineContentType}}{{/vendorExtensions.x-hasBodyOrFormParam}}{{^vendorExtensions.x-inlineAccept}}Accept accept -- ^ request accept ('MimeType') + -> {{/vendorExtensions.x-inlineAccept}}{{#allParams}}{{#required}}{{#vendorExtensions.x-paramNameType}}{{{.}}}{{/vendorExtensions.x-paramNameType}}{{^vendorExtensions.x-paramNameType}}{{{dataType}}}{{/vendorExtensions.x-paramNameType}} -- ^ "{{{paramName}}}"{{#description}} - {{{.}}}{{/description}}{{^required}}{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}{{/required}} + -> {{/required}}{{/allParams}}{{requestType}} {{{vendorExtensions.x-operationType}}} {{>_contentType}} {{vendorExtensions.x-returnType}} {{>_accept}} +{{operationId}} {{^vendorExtensions.x-inlineContentType}}_ {{/vendorExtensions.x-inlineContentType}}{{^vendorExtensions.x-inlineAccept}} _ {{/vendorExtensions.x-inlineAccept}}{{#allParams}}{{#required}}{{#isBodyParam}}{{{paramName}}}{{/isBodyParam}}{{^isBodyParam}}({{{vendorExtensions.x-paramNameType}}} {{{paramName}}}){{/isBodyParam}} {{/required}}{{/allParams}}= _mkRequest "{{httpMethod}}" {{{vendorExtensions.x-path}}}{{#authMethods}} `_hasAuthType` (P.Proxy :: P.Proxy {{name}}){{/authMethods}}{{#allParams}}{{#required}}{{#isHeaderParam}} `setHeader` {{>_headerColl}} ("{{{baseName}}}", {{{paramName}}}){{/isHeaderParam}}{{#isQueryParam}} @@ -108,14 +109,12 @@ instance Produces {{{vendorExtensions.x-operationType}}} {{{x-mediaDataType}}} -- * Parameter newtypes +{{#x-allUniqueParams}}{{#x-newtype}} +newtype {{{x-paramNameType}}} = {{{x-paramNameType}}} { un{{{x-paramNameType}}} :: {{{x-dataType}}} } deriving (P.Eq, P.Show{{#x-isBodyParam}}, A.ToJSON{{/x-isBodyParam}}){{/x-newtype}}{{/x-allUniqueParams}} -{{#x-allUniqueParams}} -newtype {{{vendorExtensions.x-paramNameType}}} = {{{vendorExtensions.x-paramNameType}}} { un{{{vendorExtensions.x-paramNameType}}} :: {{{dataType}}} } deriving (P.Eq, P.Show{{#isBodyParam}}, A.ToJSON{{/isBodyParam}}) -{{/x-allUniqueParams}} +{{#authMethods}}{{#-first}}-- * Auth Methods --- * Auth Methods - -{{#authMethods}}{{#isBasic}}-- ** {{name}} +{{/-first}}{{#isBasic}}-- ** {{name}} data {{name}} = {{name}} B.ByteString B.ByteString -- ^ username password deriving (P.Eq, P.Show, P.Typeable) diff --git a/modules/swagger-codegen/src/main/resources/haskell-http-client/Client.mustache b/modules/swagger-codegen/src/main/resources/haskell-http-client/Client.mustache index 8282ec5724d..643b7425d3f 100644 --- a/modules/swagger-codegen/src/main/resources/haskell-http-client/Client.mustache +++ b/modules/swagger-codegen/src/main/resources/haskell-http-client/Client.mustache @@ -49,11 +49,10 @@ dispatchLbs :: (Produces req accept, MimeType contentType) => NH.Manager -- ^ http-client Connection manager -> {{configType}} -- ^ config - -> {{requestType}} req contentType res -- ^ request - -> accept -- ^ "accept" 'MimeType' + -> {{requestType}} req contentType res accept -- ^ request -> IO (NH.Response BCL.ByteString) -- ^ response -dispatchLbs manager config request accept = do - initReq <- _toInitRequest config request accept +dispatchLbs manager config request = do + initReq <- _toInitRequest config request dispatchInitUnsafe manager config initReq -- ** Mime @@ -74,21 +73,26 @@ data MimeError = -- | send a request returning the 'MimeResult' dispatchMime - :: (Produces req accept, MimeUnrender accept res, MimeType contentType) + :: forall req contentType res accept. (Produces req accept, MimeUnrender accept res, MimeType contentType) => NH.Manager -- ^ http-client Connection manager -> {{configType}} -- ^ config - -> {{requestType}} req contentType res -- ^ request - -> accept -- ^ "accept" 'MimeType' + -> {{requestType}} req contentType res accept -- ^ request -> IO (MimeResult res) -- ^ response -dispatchMime manager config request accept = do - httpResponse <- dispatchLbs manager config request accept +dispatchMime manager config request = do + httpResponse <- dispatchLbs manager config request + let statusCode = NH.statusCode . NH.responseStatus $ httpResponse parsedResult <- runConfigLogWithExceptions "Client" config $ - do case mimeUnrender' accept (NH.responseBody httpResponse) of - Left s -> do + do if (statusCode >= 400 && statusCode < 600) + then do + let s = "error statusCode: " ++ show statusCode _log "Client" levelError (T.pack s) pure (Left (MimeError s httpResponse)) - Right r -> pure (Right r) + else case mimeUnrender (P.Proxy :: P.Proxy accept) (NH.responseBody httpResponse) of + Left s -> do + _log "Client" levelError (T.pack s) + pure (Left (MimeError s httpResponse)) + Right r -> pure (Right r) return (MimeResult parsedResult httpResponse) -- | like 'dispatchMime', but only returns the decoded http body @@ -96,11 +100,10 @@ dispatchMime' :: (Produces req accept, MimeUnrender accept res, MimeType contentType) => NH.Manager -- ^ http-client Connection manager -> {{configType}} -- ^ config - -> {{requestType}} req contentType res -- ^ request - -> accept -- ^ "accept" 'MimeType' + -> {{requestType}} req contentType res accept -- ^ request -> IO (Either MimeError res) -- ^ response -dispatchMime' manager config request accept = do - MimeResult parsedResult _ <- dispatchMime manager config request accept +dispatchMime' manager config request = do + MimeResult parsedResult _ <- dispatchMime manager config request return parsedResult -- ** Unsafe @@ -110,11 +113,10 @@ dispatchLbsUnsafe :: (MimeType accept, MimeType contentType) => NH.Manager -- ^ http-client Connection manager -> {{configType}} -- ^ config - -> {{requestType}} req contentType res -- ^ request - -> accept -- ^ "accept" 'MimeType' + -> {{requestType}} req contentType res accept -- ^ request -> IO (NH.Response BCL.ByteString) -- ^ response -dispatchLbsUnsafe manager config request accept = do - initReq <- _toInitRequest config request accept +dispatchLbsUnsafe manager config request = do + initReq <- _toInitRequest config request dispatchInitUnsafe manager config initReq -- | dispatch an InitRequest @@ -158,17 +160,16 @@ newtype InitRequest req contentType res accept = InitRequest _toInitRequest :: (MimeType accept, MimeType contentType) => {{configType}} -- ^ config - -> {{requestType}} req contentType res -- ^ request - -> accept -- ^ "accept" 'MimeType' + -> {{requestType}} req contentType res accept -- ^ request -> IO (InitRequest req contentType res accept) -- ^ initialized request -_toInitRequest config req0 accept = +_toInitRequest config req0 = runConfigLogWithExceptions "Client" config $ do parsedReq <- P.liftIO $ NH.parseRequest $ BCL.unpack $ BCL.append (configHost config) (BCL.concat (rUrlPath req0)) req1 <- P.liftIO $ _applyAuthMethods req0 config P.when (configValidateAuthMethods config && (not . null . rAuthTypes) req1) - (E.throwString $ "AuthMethod not configured: " <> (show . head . rAuthTypes) req1) - let req2 = req1 & _setContentTypeHeader & flip _setAcceptHeader accept + (E.throw $ AuthMethodException $ "AuthMethod not configured: " <> (show . head . rAuthTypes) req1) + let req2 = req1 & _setContentTypeHeader & _setAcceptHeader reqHeaders = ("User-Agent", WH.toHeader (configUserAgent config)) : paramsHeaders (rParams req2) reqQuery = NH.renderQuery True (paramsQuery (rParams req2)) pReq = parsedReq { NH.method = (rMethod req2) @@ -185,7 +186,7 @@ _toInitRequest config req0 accept = pure (InitRequest outReq) -- | modify the underlying Request -modifyInitRequest :: InitRequest req contentType res accept -> (NH.Request -> NH.Request) -> InitRequest req contentType res accept +modifyInitRequest :: InitRequest req contentType res accept -> (NH.Request -> NH.Request) -> InitRequest req contentType res accept modifyInitRequest (InitRequest req) f = InitRequest (f req) -- | modify the underlying Request (monadic) diff --git a/modules/swagger-codegen/src/main/resources/haskell-http-client/Core.mustache b/modules/swagger-codegen/src/main/resources/haskell-http-client/Core.mustache index ab870973a21..b40ec37d0d7 100644 --- a/modules/swagger-codegen/src/main/resources/haskell-http-client/Core.mustache +++ b/modules/swagger-codegen/src/main/resources/haskell-http-client/Core.mustache @@ -23,6 +23,7 @@ import {{title}}.Logging import qualified Control.Arrow as P (left) import qualified Control.DeepSeq as NF +import qualified Control.Exception.Safe as E import qualified Data.Aeson as A import qualified Data.ByteString as B import qualified Data.ByteString.Base64.Lazy as BL64 @@ -122,8 +123,15 @@ withNoLogging p = p { configLogExecWithContext = runNullLogExec} -- * {{requestType}} --- | Represents a request. The "req" type variable is the request type. The "res" type variable is the response type. -data {{requestType}} req contentType res = {{requestType}} +-- | Represents a request. +-- +-- Type Variables: +-- +-- * req - request operation +-- * contentType - 'MimeType' associated with request body +-- * res - response model +-- * accept - 'MimeType' associated with response body +data {{requestType}} req contentType res accept = {{requestType}} { rMethod :: NH.Method -- ^ Method of {{requestType}} , rUrlPath :: [BCL.ByteString] -- ^ Endpoint of {{requestType}} , rParams :: Params -- ^ params of {{requestType}} @@ -132,22 +140,22 @@ data {{requestType}} req contentType res = {{requestType}} deriving (P.Show) -- | 'rMethod' Lens -rMethodL :: Lens_' ({{requestType}} req contentType res) NH.Method +rMethodL :: Lens_' ({{requestType}} req contentType res accept) NH.Method rMethodL f {{requestType}}{..} = (\rMethod -> {{requestType}} { rMethod, ..} ) <$> f rMethod {-# INLINE rMethodL #-} -- | 'rUrlPath' Lens -rUrlPathL :: Lens_' ({{requestType}} req contentType res) [BCL.ByteString] +rUrlPathL :: Lens_' ({{requestType}} req contentType res accept) [BCL.ByteString] rUrlPathL f {{requestType}}{..} = (\rUrlPath -> {{requestType}} { rUrlPath, ..} ) <$> f rUrlPath {-# INLINE rUrlPathL #-} -- | 'rParams' Lens -rParamsL :: Lens_' ({{requestType}} req contentType res) Params +rParamsL :: Lens_' ({{requestType}} req contentType res accept) Params rParamsL f {{requestType}}{..} = (\rParams -> {{requestType}} { rParams, ..} ) <$> f rParams {-# INLINE rParamsL #-} -- | 'rParams' Lens -rAuthTypesL :: Lens_' ({{requestType}} req contentType res) [P.TypeRep] +rAuthTypesL :: Lens_' ({{requestType}} req contentType res accept) [P.TypeRep] rAuthTypesL f {{requestType}}{..} = (\rAuthTypes -> {{requestType}} { rAuthTypes, ..} ) <$> f rAuthTypes {-# INLINE rAuthTypesL #-} @@ -155,7 +163,7 @@ rAuthTypesL f {{requestType}}{..} = (\rAuthTypes -> {{requestType}} { rAuthTypes -- | Designates the body parameter of a request class HasBodyParam req param where - setBodyParam :: forall contentType res. (Consumes req contentType, MimeRender contentType param) => {{requestType}} req contentType res -> param -> {{requestType}} req contentType res + setBodyParam :: forall contentType res accept. (Consumes req contentType, MimeRender contentType param) => {{requestType}} req contentType res accept -> param -> {{requestType}} req contentType res accept setBodyParam req xs = req `_setBodyLBS` mimeRender (P.Proxy :: P.Proxy contentType) xs & _setContentTypeHeader @@ -166,12 +174,12 @@ class HasOptionalParam req param where {-# MINIMAL applyOptionalParam | (-&-) #-} -- | Apply an optional parameter to a request - applyOptionalParam :: {{requestType}} req contentType res -> param -> {{requestType}} req contentType res + applyOptionalParam :: {{requestType}} req contentType res accept -> param -> {{requestType}} req contentType res accept applyOptionalParam = (-&-) {-# INLINE applyOptionalParam #-} -- | infix operator \/ alias for 'addOptionalParam' - (-&-) :: {{requestType}} req contentType res -> param -> {{requestType}} req contentType res + (-&-) :: {{requestType}} req contentType res accept -> param -> {{requestType}} req contentType res accept (-&-) = applyOptionalParam {-# INLINE (-&-) #-} @@ -213,18 +221,18 @@ data ParamBody _mkRequest :: NH.Method -- ^ Method -> [BCL.ByteString] -- ^ Endpoint - -> {{requestType}} req contentType res -- ^ req: Request Type, res: Response Type + -> {{requestType}} req contentType res accept -- ^ req: Request Type, res: Response Type _mkRequest m u = {{requestType}} m u _mkParams [] _mkParams :: Params _mkParams = Params [] [] ParamBodyNone -setHeader :: {{requestType}} req contentType res -> [NH.Header] -> {{requestType}} req contentType res +setHeader :: {{requestType}} req contentType res accept -> [NH.Header] -> {{requestType}} req contentType res accept setHeader req header = req `removeHeader` P.fmap P.fst header & L.over (rParamsL . paramsHeadersL) (header P.++) -removeHeader :: {{requestType}} req contentType res -> [NH.HeaderName] -> {{requestType}} req contentType res +removeHeader :: {{requestType}} req contentType res accept -> [NH.HeaderName] -> {{requestType}} req contentType res accept removeHeader req header = req & L.over @@ -234,19 +242,19 @@ removeHeader req header = cifst = CI.mk . P.fst -_setContentTypeHeader :: forall req contentType res. MimeType contentType => {{requestType}} req contentType res -> {{requestType}} req contentType res +_setContentTypeHeader :: forall req contentType res accept. MimeType contentType => {{requestType}} req contentType res accept -> {{requestType}} req contentType res accept _setContentTypeHeader req = case mimeType (P.Proxy :: P.Proxy contentType) of Just m -> req `setHeader` [("content-type", BC.pack $ P.show m)] Nothing -> req `removeHeader` ["content-type"] -_setAcceptHeader :: forall req contentType res accept. MimeType accept => {{requestType}} req contentType res -> accept -> {{requestType}} req contentType res -_setAcceptHeader req accept = - case mimeType' accept of +_setAcceptHeader :: forall req contentType res accept. MimeType accept => {{requestType}} req contentType res accept -> {{requestType}} req contentType res accept +_setAcceptHeader req = + case mimeType (P.Proxy :: P.Proxy accept) of Just m -> req `setHeader` [("accept", BC.pack $ P.show m)] Nothing -> req `removeHeader` ["accept"] -setQuery :: {{requestType}} req contentType res -> [NH.QueryItem] -> {{requestType}} req contentType res +setQuery :: {{requestType}} req contentType res accept -> [NH.QueryItem] -> {{requestType}} req contentType res accept setQuery req query = req & L.over @@ -255,29 +263,29 @@ setQuery req query = where cifst = CI.mk . P.fst -addForm :: {{requestType}} req contentType res -> WH.Form -> {{requestType}} req contentType res +addForm :: {{requestType}} req contentType res accept -> WH.Form -> {{requestType}} req contentType res accept addForm req newform = let form = case paramsBody (rParams req) of ParamBodyFormUrlEncoded _form -> _form _ -> mempty in req & L.set (rParamsL . paramsBodyL) (ParamBodyFormUrlEncoded (newform <> form)) -_addMultiFormPart :: {{requestType}} req contentType res -> NH.Part -> {{requestType}} req contentType res +_addMultiFormPart :: {{requestType}} req contentType res accept -> NH.Part -> {{requestType}} req contentType res accept _addMultiFormPart req newpart = let parts = case paramsBody (rParams req) of ParamBodyMultipartFormData _parts -> _parts _ -> [] in req & L.set (rParamsL . paramsBodyL) (ParamBodyMultipartFormData (newpart : parts)) -_setBodyBS :: {{requestType}} req contentType res -> B.ByteString -> {{requestType}} req contentType res +_setBodyBS :: {{requestType}} req contentType res accept -> B.ByteString -> {{requestType}} req contentType res accept _setBodyBS req body = req & L.set (rParamsL . paramsBodyL) (ParamBodyB body) -_setBodyLBS :: {{requestType}} req contentType res -> BL.ByteString -> {{requestType}} req contentType res +_setBodyLBS :: {{requestType}} req contentType res accept -> BL.ByteString -> {{requestType}} req contentType res accept _setBodyLBS req body = req & L.set (rParamsL . paramsBodyL) (ParamBodyBL body) -_hasAuthType :: AuthMethod authMethod => {{requestType}} req contentType res -> P.Proxy authMethod -> {{requestType}} req contentType res +_hasAuthType :: AuthMethod authMethod => {{requestType}} req contentType res accept -> P.Proxy authMethod -> {{requestType}} req contentType res accept _hasAuthType req proxy = req & L.over rAuthTypesL (P.typeRep proxy :) @@ -352,19 +360,24 @@ class P.Typeable a => applyAuthMethod :: {{configType}} -> a - -> {{requestType}} req contentType res - -> IO ({{requestType}} req contentType res) + -> {{requestType}} req contentType res accept + -> IO ({{requestType}} req contentType res accept) -- | An existential wrapper for any AuthMethod data AnyAuthMethod = forall a. AuthMethod a => AnyAuthMethod a deriving (P.Typeable) instance AuthMethod AnyAuthMethod where applyAuthMethod config (AnyAuthMethod a) req = applyAuthMethod config a req +-- | indicates exceptions related to AuthMethods +data AuthMethodException = AuthMethodException String deriving (P.Show, P.Typeable) + +instance E.Exception AuthMethodException + -- | apply all matching AuthMethods in config to request _applyAuthMethods - :: {{requestType}} req contentType res + :: {{requestType}} req contentType res accept -> {{configType}} - -> IO ({{requestType}} req contentType res) + -> IO ({{requestType}} req contentType res accept) _applyAuthMethods req config@({{configType}} {configAuthMethods = as}) = foldlM go req as where diff --git a/modules/swagger-codegen/src/main/resources/haskell-http-client/MimeTypes.mustache b/modules/swagger-codegen/src/main/resources/haskell-http-client/MimeTypes.mustache index 751013b3f50..072a8634c8d 100644 --- a/modules/swagger-codegen/src/main/resources/haskell-http-client/MimeTypes.mustache +++ b/modules/swagger-codegen/src/main/resources/haskell-http-client/MimeTypes.mustache @@ -4,6 +4,7 @@ Module : {{title}}.MimeTypes -} {-# LANGUAGE ConstraintKinds #-} +{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} @@ -32,6 +33,13 @@ import qualified Web.HttpApiData as WH import Prelude (($), (.),(<$>),(<*>),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty) import qualified Prelude as P +-- * ContentType MimeType + +data ContentType a = MimeType a => ContentType { unContentType :: a } + +-- * Accept MimeType + +data Accept a = MimeType a => Accept { unAccept :: a } -- * Consumes Class @@ -181,4 +189,4 @@ instance MimeUnrender MimeOctetStream T.Text where mimeUnrender _ = P.left P.sho instance MimeUnrender MimeOctetStream String where mimeUnrender _ = P.Right . BCL.unpack -- | @P.Right . P.const NoContent@ -instance MimeUnrender MimeNoContent NoContent where mimeUnrender _ = P.Right . P.const NoContent \ No newline at end of file +instance MimeUnrender MimeNoContent NoContent where mimeUnrender _ = P.Right . P.const NoContent diff --git a/modules/swagger-codegen/src/main/resources/haskell-http-client/Model.mustache b/modules/swagger-codegen/src/main/resources/haskell-http-client/Model.mustache index ca63b567309..3613d9588d1 100644 --- a/modules/swagger-codegen/src/main/resources/haskell-http-client/Model.mustache +++ b/modules/swagger-codegen/src/main/resources/haskell-http-client/Model.mustache @@ -8,6 +8,8 @@ Module : {{title}}.Model {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} @@ -18,9 +20,11 @@ Module : {{title}}.Model module {{title}}.Model where import {{title}}.Core +import {{title}}.MimeTypes import Data.Aeson ((.:),(.:!),(.:?),(.=)) +import qualified Control.Arrow as P (left) import qualified Data.Aeson as A import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL @@ -39,7 +43,7 @@ import qualified Web.HttpApiData as WH import Control.Applicative ((<|>)) import Control.Applicative (Alternative) import Data.Text (Text) -import Prelude (($), (.),(<$>),(<*>),(>>=),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty,maybe,pure,Monad,Applicative,Functor) +import Prelude (($), (.),(<$>),(<*>),(>>=),(=<<),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty,maybe,pure,Monad,Applicative,Functor) import qualified Prelude as P @@ -50,18 +54,17 @@ import qualified Prelude as P -- * Models {{#models}} -{{#model}} - +{{#model}}{{^isEnum}} -- ** {{classname}} -- | {{classname}}{{#title}} -- {{{.}}} -- {{/title}}{{#description}} -- {{{.}}}{{/description}}{{#isAlias}} newtype {{classname}} = {{classname}} - { un{{classname}} :: {{{dataType}}} + { un{{classname}} :: {{{vendorExtensions.x-dataType}}} } deriving (P.Eq, P.Show, P.Typeable, A.ToJSON, A.FromJSON, WH.ToHttpApiData, WH.FromHttpApiData{{#modelDeriving}}, {{modelDeriving}}{{/modelDeriving}}){{/isAlias}}{{^isAlias}} data {{classname}} = {{classname}} - { {{#vars}}{{name}} :: {{#x-strictFields}}!({{/x-strictFields}}{{^required}}Maybe {{/required}}{{datatype}}{{#x-strictFields}}){{/x-strictFields}} -- ^ {{#required}}/Required/ {{/required}}{{#readOnly}}/ReadOnly/ {{/readOnly}}"{{baseName}}"{{#description}} - {{description}}{{/description}}{{#hasMore}} + { {{#vars}}{{name}} :: {{#x-strictFields}}!({{/x-strictFields}}{{^required}}Maybe {{/required}}{{{vendorExtensions.x-dataType}}}{{#x-strictFields}}){{/x-strictFields}} -- ^ {{#required}}/Required/ {{/required}}{{#readOnly}}/ReadOnly/ {{/readOnly}}"{{baseName}}"{{#description}} - {{description}}{{/description}}{{#hasMore}} , {{/hasMore}}{{/vars}} } deriving (P.Show, P.Eq, P.Typeable{{#modelDeriving}}, {{modelDeriving}}{{/modelDeriving}}){{/isAlias}} @@ -100,17 +103,40 @@ instance WH.ToForm {{classname}} where {{#generateModelConstructors}} -- | Construct a value of type '{{classname}}' (by applying it's required fields, if any) mk{{classname}} - :: {{#requiredVars}}{{{datatype}}} -- ^ '{{name}}'{{#description}}:{{/description}} {{{description}}} + :: {{#requiredVars}}{{{vendorExtensions.x-dataType}}} -- ^ '{{name}}'{{#description}}:{{/description}} {{{description}}} -> {{/requiredVars}}{{classname}} mk{{classname}} {{#requiredVars}}{{name}} {{/requiredVars}}= {{classname}} { {{#vars}}{{#required}}{{name}}{{/required}}{{^required}}{{name}} = {{#isListContainer}}Nothing{{/isListContainer}}{{#isMapContainer}}Nothing{{/isMapContainer}}{{^isContainer}}Nothing{{/isContainer}}{{/required}}{{#hasMore}} , {{/hasMore}}{{/vars}} } -{{/generateModelConstructors}} -{{/isAlias}} +{{/generateModelConstructors}}{{/isAlias}}{{/isEnum}}{{/model}}{{/models}} -{{/model}} -{{/models}} +{{#x-hasEnumSection}}-- * Enums +{{#x-allUniqueParams}}{{#x-enum}} +-- ** {{{x-paramNameType}}} +-- | Enum of '{{{x-dataType}}}'{{#description}} . +-- {{{.}}}{{/description}} +data {{{x-paramNameType}}} + = {{#allowableValues}}{{#enumVars}}{{{name}}} -- ^ @{{{value}}}@ + {{^-last}}| {{/-last}}{{#-last}}deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum){{/-last}}{{/enumVars}}{{/allowableValues}} + +instance A.ToJSON {{{x-paramNameType}}} where toJSON = A.toJSON . from{{{x-paramNameType}}} +instance A.FromJSON {{{x-paramNameType}}} where parseJSON o = P.either P.fail (pure . P.id) . to{{{x-paramNameType}}} =<< A.parseJSON o +instance WH.ToHttpApiData {{{x-paramNameType}}} where toQueryParam = WH.toQueryParam . from{{{x-paramNameType}}} +instance WH.FromHttpApiData {{{x-paramNameType}}} where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . to{{{x-paramNameType}}} +instance MimeRender MimeMultipartFormData {{{x-paramNameType}}} where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap '{{{x-paramNameType}}}' enum +from{{{x-paramNameType}}} :: {{{x-paramNameType}}} -> {{{x-dataType}}} +from{{{x-paramNameType}}} = \case{{#allowableValues}}{{#enumVars}} + {{{name}}} -> {{{value}}}{{/enumVars}}{{/allowableValues}} + +-- | parse '{{{x-paramNameType}}}' enum +to{{{x-paramNameType}}} :: {{{x-dataType}}} -> P.Either String {{{x-paramNameType}}} +to{{{x-paramNameType}}} = \case{{#allowableValues}}{{#enumVars}} + {{{value}}} -> P.Right {{{name}}}{{/enumVars}}{{/allowableValues}} + s -> P.Left $ "to{{{x-paramNameType}}}: enum parse failure: " P.++ P.show s +{{/x-enum}}{{/x-allUniqueParams}}{{/x-hasEnumSection}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/haskell-http-client/ModelLens.mustache b/modules/swagger-codegen/src/main/resources/haskell-http-client/ModelLens.mustache index 9e509aeebb5..d15a4ba8336 100644 --- a/modules/swagger-codegen/src/main/resources/haskell-http-client/ModelLens.mustache +++ b/modules/swagger-codegen/src/main/resources/haskell-http-client/ModelLens.mustache @@ -33,7 +33,7 @@ import {{title}}.Core {{#vars}} -- | '{{name}}' Lens -{{name}}L :: Lens_' {{classname}} ({{^required}}Maybe {{/required}}{{datatype}}) +{{name}}L :: Lens_' {{classname}} ({{^required}}Maybe {{/required}}{{{vendorExtensions.x-dataType}}}) {{name}}L f {{classname}}{..} = (\{{name}} -> {{classname}} { {{name}}, ..} ) <$> f {{name}} {-# INLINE {{name}}L #-} diff --git a/modules/swagger-codegen/src/main/resources/haskell-http-client/README.mustache b/modules/swagger-codegen/src/main/resources/haskell-http-client/README.mustache index ba1195d798a..747f97d3f42 100644 --- a/modules/swagger-codegen/src/main/resources/haskell-http-client/README.mustache +++ b/modules/swagger-codegen/src/main/resources/haskell-http-client/README.mustache @@ -48,11 +48,6 @@ haskell-http-client * Model Inheritance -* Default Parameter Values - -* Enum Parameters - - This is beta software; other cases may not be supported. ### Codegen "additional properties" parameters @@ -67,10 +62,11 @@ These options allow some customization of the code generation process. | allowToJsonNulls | allow emitting JSON Null during model encoding to JSON | false | {{{allowToJsonNulls}}} | | dateFormat | format string used to parse/render a date | %Y-%m-%d | {{{dateFormat}}} | | dateTimeFormat | format string used to parse/render a datetime. (Defaults to [formatISO8601Millis][1] when not provided) | | {{{dateTimeFormat}}} | +| generateEnums | Generate specific datatypes for swagger enums | true | {{{generateEnums}}} | | generateFormUrlEncodedInstances | Generate FromForm/ToForm instances for models used by x-www-form-urlencoded operations (model fields must be primitive types) | true | {{{generateFormUrlEncodedInstances}}} | | generateLenses | Generate Lens optics for Models | true | {{{generateLenses}}} | | generateModelConstructors | Generate smart constructors (only supply required fields) for models | true | {{{generateModelConstructors}}} | -| inlineConsumesContentTypes | Inline (hardcode) the content-type on operations that do not have multiple content-types (Consumes) | false | {{{inlineConsumesContentTypes}}} | +| inlineMimeTypes | Inline (hardcode) the content-type and accept parameters on operations, when there is only 1 option | false | {{{inlineMimeTypes}}} | | modelDeriving | Additional classes to include in the deriving() clause of Models | | {{{modelDeriving}}} | | strictFields | Add strictness annotations to all model fields | true | {{{x-strictFields}}} | | useMonadLogger | Use the monad-logger package to provide logging (if instead false, use the katip logging package) | false | {{{x-useMonadLogger}}} | @@ -184,11 +180,17 @@ config0 <- withStdoutLogging =<< newConfig let config = config0 `addAuthMethod` AuthOAuthFoo "secret-key" -let addFooRequest = addFoo MimeJSON foomodel requiredparam1 requiredparam2 +let addFooRequest = + addFoo + (ContentType MimeJSON) + (Accept MimeXML) + (ParamBar paramBar) + (ParamQux paramQux) + modelBaz `applyOptionalParam` FooId 1 `applyOptionalParam` FooName "name" `setHeader` [("qux_header","xxyy")] -addFooResult <- dispatchMime mgr config addFooRequest MimeXML +addFooResult <- dispatchMime mgr config addFooRequest ``` -See the example app and the haddocks for details. \ No newline at end of file +See the example app and the haddocks for details. diff --git a/modules/swagger-codegen/src/main/resources/haskell-http-client/_accept.mustache b/modules/swagger-codegen/src/main/resources/haskell-http-client/_accept.mustache new file mode 100644 index 00000000000..bf410b31bdb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/haskell-http-client/_accept.mustache @@ -0,0 +1 @@ +{{^vendorExtensions.x-inlineAccept}}accept{{/vendorExtensions.x-inlineAccept}}{{#vendorExtensions.x-inlineAccept}}{{{x-mediaDataType}}}{{/vendorExtensions.x-inlineAccept}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/haskell-http-client/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/haskell-http-client/git_push.sh.mustache index e153ce23ecf..a2d75234837 100644 --- a/modules/swagger-codegen/src/main/resources/haskell-http-client/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/haskell-http-client/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/haskell-http-client/haskell-http-client.cabal.mustache b/modules/swagger-codegen/src/main/resources/haskell-http-client/haskell-http-client.cabal.mustache index fb8d17763d5..2b0b517b845 100644 --- a/modules/swagger-codegen/src/main/resources/haskell-http-client/haskell-http-client.cabal.mustache +++ b/modules/swagger-codegen/src/main/resources/haskell-http-client/haskell-http-client.cabal.mustache @@ -44,7 +44,7 @@ library , bytestring >=0.10.0 && <0.11 , base64-bytestring >1.0 && <2.0 , containers >=0.5.0.0 && <0.6 - , http-types >=0.8 && <0.10 + , http-types >=0.8 && <0.11 , http-client >=0.5 && <0.6 , http-client-tls , http-api-data >= 0.3.4 && <0.4 diff --git a/modules/swagger-codegen/src/main/resources/haskell-http-client/stack.mustache b/modules/swagger-codegen/src/main/resources/haskell-http-client/stack.mustache index 174a76815bc..aa4a059faa5 100644 --- a/modules/swagger-codegen/src/main/resources/haskell-http-client/stack.mustache +++ b/modules/swagger-codegen/src/main/resources/haskell-http-client/stack.mustache @@ -1,4 +1,4 @@ -resolver: lts-9.0 +resolver: lts-9.10 build: haddock-arguments: haddock-args: diff --git a/modules/swagger-codegen/src/main/resources/haskell-http-client/tests/Instances.mustache b/modules/swagger-codegen/src/main/resources/haskell-http-client/tests/Instances.mustache index f8d6a3c406f..afaaf140c98 100644 --- a/modules/swagger-codegen/src/main/resources/haskell-http-client/tests/Instances.mustache +++ b/modules/swagger-codegen/src/main/resources/haskell-http-client/tests/Instances.mustache @@ -91,13 +91,19 @@ instance ApproxEq TI.Day where {{#models}} {{#model}} +{{^isEnum}} instance Arbitrary {{classname}} where arbitrary = {{#isAlias}}{{classname}} <$> arbitrary{{/isAlias}}{{^isAlias}}{{^hasVars}} pure {{/hasVars}}{{classname}} {{#hasVars}} <$>{{/hasVars}} {{#vars}}arbitrary -- {{name}} :: {{^required}}Maybe {{/required}}{{datatype}} {{#hasMore}} <*> {{/hasMore}}{{/vars}}{{/isAlias}} - +{{/isEnum}} {{/model}} {{/models}} + +{{#x-allUniqueParams}}{{#x-enum}} +instance Arbitrary {{{x-paramNameType}}} where + arbitrary = arbitraryBoundedEnum +{{/x-enum}}{{/x-allUniqueParams}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/kotlin-client/data_class.mustache b/modules/swagger-codegen/src/main/resources/kotlin-client/data_class.mustache index 4e83f8cda65..1237ec1f431 100644 --- a/modules/swagger-codegen/src/main/resources/kotlin-client/data_class.mustache +++ b/modules/swagger-codegen/src/main/resources/kotlin-client/data_class.mustache @@ -12,11 +12,14 @@ data class {{classname}} ( {{/-last}}{{/optionalVars}} ) { {{#hasEnums}}{{#vars}}{{#isEnum}} - enum class {{nameInCamelCase}}(val value: {{datatype}}) { - {{#_enum}} - {{{this}}}({{#isString}}"{{/isString}}{{{this}}}{{#isString}}"{{/isString}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} - {{/_enum}} + /** + * {{{description}}} + * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} + */ + enum class {{nameInCamelCase}}(val value: {{dataType}}){ + {{#allowableValues}}{{#enumVars}} + {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} + {{/enumVars}}{{/allowableValues}} } - {{/isEnum}}{{/vars}}{{/hasEnums}} -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/kotlin-client/enum_class.mustache b/modules/swagger-codegen/src/main/resources/kotlin-client/enum_class.mustache index 845fa192c21..791398b9789 100644 --- a/modules/swagger-codegen/src/main/resources/kotlin-client/enum_class.mustache +++ b/modules/swagger-codegen/src/main/resources/kotlin-client/enum_class.mustache @@ -1,9 +1,9 @@ /** * {{{description}}} -* Values: {{#allowableValues}}{{#enumVars}}{{name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} +* Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} */ enum class {{classname}}(val value: {{dataType}}){ {{#allowableValues}}{{#enumVars}} - {{name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} + {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} {{/enumVars}}{{/allowableValues}} -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/lua/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/lua/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/lua/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/lua/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache index 038977fb6d4..21ee6fd90e8 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache @@ -5,7 +5,8 @@ using System.Collections.Generic; using Sharpility.Base; using {{packageName}}.{{packageContext}}.Models; using {{packageName}}.{{packageContext}}.Utils; -using NodaTime; +using NodaTime;{{#asyncServer}} +using System.Threading.Tasks;{{/asyncServer}} {{#imports}}using {{import}}; {{/imports}} @@ -24,13 +25,13 @@ namespace {{packageName}}.{{packageContext}}.Modules /// Service handling requests public {{classname}}Module({{interfacePrefix}}{{classname}}Service service) : base("{{{baseContext}}}") { {{#operation}} - {{httpMethod}}["{{{path}}}"] = parameters => + {{httpMethod}}["{{{path}}}"{{#asyncServer}}, true{{/asyncServer}}] = {{#asyncServer}}async (parameters, ct){{/asyncServer}}{{^asyncServer}}parameters{{/asyncServer}} => { {{#allParams}}{{#isBodyParam}}var {{paramName}} = this.Bind<{{&dataType}}>();{{/isBodyParam}}{{^isBodyParam}}{{#isEnum}}var {{paramName}} = Parameters.ValueOf<{{>innerApiEnumName}}?>({{>innerParameterValueOfArgs}});{{/isEnum}}{{^isEnum}}var {{paramName}} = Parameters.ValueOf<{{&dataType}}>({{>innerParameterValueOfArgs}});{{/isEnum}}{{#hasMore}} {{/hasMore}}{{/isBodyParam}}{{/allParams}}{{#allParams}}{{#required}} Preconditions.IsNotNull({{paramName}}, "Required parameter: '{{paramName}}' is missing at '{{operationId}}'"); {{/required}}{{/allParams}} - {{#returnType}}return {{/returnType}}service.{{operationId}}(Context{{#allParams.0}}, {{/allParams.0}}{{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}}{{#isListContainer}}.ToArray(){{/isListContainer}}{{/returnType}};{{^returnType}} + {{#returnType}}return {{/returnType}}{{#asyncServer}}await {{/asyncServer}}service.{{operationId}}(Context{{#allParams.0}}, {{/allParams.0}}{{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}}{{#isListContainer}}.ToArray(){{/isListContainer}}{{/returnType}};{{^returnType}} return new Response { ContentType = "{{produces.0.mediaType}}"};{{/returnType}} }; {{/operation}} @@ -48,7 +49,7 @@ namespace {{packageName}}.{{packageContext}}.Modules /// Context of request {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} - {{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}(NancyContext context{{#allParams.0}}, {{/allParams.0}}{{>paramsList}});{{#hasMore}} + {{#asyncServer}}{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}}{{/asyncServer}}{{^asyncServer}}{{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/asyncServer}} {{operationId}}(NancyContext context{{#allParams.0}}, {{/allParams.0}}{{>paramsList}});{{#hasMore}} {{/hasMore}}{{/operation}} } @@ -58,14 +59,14 @@ namespace {{packageName}}.{{packageContext}}.Modules /// public abstract class Abstract{{classname}}Service: {{interfacePrefix}}{{classname}}Service { - {{#operation}}public virtual {{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}(NancyContext context{{#allParams.0}}, {{/allParams.0}}{{>paramsList}}) + {{#operation}}public virtual {{#asyncServer}}{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}}{{/asyncServer}}{{^asyncServer}}{{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/asyncServer}} {{operationId}}(NancyContext context{{#allParams.0}}, {{/allParams.0}}{{>paramsList}}) { - {{#returnType}}return {{/returnType}}{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{^asyncServer}}{{#returnType}}return {{/returnType}}{{/asyncServer}}{{#asyncServer}}return {{/asyncServer}}{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); }{{#hasMore}} {{/hasMore}}{{/operation}} - {{#operation}}protected abstract {{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{>paramsList}});{{#hasMore}} + {{#operation}}protected abstract {{#asyncServer}}{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}}{{/asyncServer}}{{^asyncServer}}{{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/asyncServer}} {{operationId}}({{>paramsList}});{{#hasMore}} {{/hasMore}}{{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/innerApiEnum.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/innerApiEnum.mustache index 0c6a219e7bb..586b0e423c7 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/innerApiEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/innerApiEnum.mustache @@ -4,7 +4,7 @@ public enum {{>innerApiEnumName}} { {{#allowableValues}} -{{#values}} {{&.}}{{^-last}}, {{/-last}} +{{#values}} {{&.}}{{^isInteger}} = {{-index}}{{/isInteger}}{{^-last}}, {{/-last}} {{/values}} {{/allowableValues}} }; diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/modelEnum.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/modelEnum.mustache index 8d29373d205..303e4c71c26 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/modelEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/modelEnum.mustache @@ -10,6 +10,6 @@ /// /// Enum {{name}} /// - {{name}}{{#isInteger}} = {{{value}}}{{/isInteger}}{{^-last}}, + {{name}}{{#isInteger}} = {{{value}}}{{/isInteger}}{{^isInteger}} = {{-index}}{{/isInteger}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}} - } \ No newline at end of file + } 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 index e153ce23ecf..a2d75234837 100644 --- a/modules/swagger-codegen/src/main/resources/objc/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/perl/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/perl/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/perl/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/Controller.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/Controller.mustache index af937c7d99f..dec27347f82 100644 --- a/modules/swagger-codegen/src/main/resources/php-symfony/Controller.mustache +++ b/modules/swagger-codegen/src/main/resources/php-symfony/Controller.mustache @@ -19,9 +19,10 @@ namespace {{controllerPackage}}; -use Symfony\Bundle\FrameworkBundle\Controller\Controller as BaseController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\HttpException; +use {{servicePackage}}\SerializerInterface; +use {{servicePackage}}\ValidatorInterface; /** * Controller Class Doc Comment @@ -31,212 +32,147 @@ use Symfony\Component\HttpKernel\Exception\HttpException; * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ -class Controller extends BaseController +class Controller { + protected $validator; + protected $serializer; + protected $apiServer; - /** - * This will return a response with code 400. Usage example: - * return $this->createBadRequestResponse('Unable to access this page!'); - * - * @param string $message A message - * - * @return Response - */ - public function createBadRequestResponse($message = 'Bad Request.') - { - return new Response($message, 400); - } + public function setValidator(ValidatorInterface $validator) + { + $this->validator = $validator; + } - /** - * This will return an error response. Usage example: - * return $this->createErrorResponse(new UnauthorizedHttpException()); - * - * @param HttpException $exception An HTTP exception - * - * @return Response - */ - public function createErrorResponse(HttpException $exception) - { - $statusCode = $exception->getStatusCode(); - $headers = array_merge($exception->getHeaders(), ['Content-Type' => 'application/json']); + public function setSerializer(SerializerInterface $serializer) + { + $this->serializer = $serializer; + } - $json = $this->exceptionToArray($exception); - $json['statusCode'] = $statusCode; + public function setApiServer($server) + { + $this->apiServer = $server; + } - return new Response(json_encode($json, 15, 512), $statusCode, $headers); - } + /** + * This will return a response with code 400. Usage example: + * return $this->createBadRequestResponse('Unable to access this page!'); + * + * @param string $message A message + * + * @return Response + */ + public function createBadRequestResponse($message = 'Bad Request.') + { + return new Response($message, 400); + } - /** - * Serializes data to a given type format. - * - * @param mixed $data The data to serialize. - * @param string $class The source data class. - * @param string $format The target serialization format. - * - * @return string A serialized data string. - */ - public function serialize($data, $format) - { - return $this->get('{{bundleAlias}}.model.model_serializer')->serialize($data, $format); - } + /** + * This will return an error response. Usage example: + * return $this->createErrorResponse(new UnauthorizedHttpException()); + * + * @param HttpException $exception An HTTP exception + * + * @return Response + */ + public function createErrorResponse(HttpException $exception) + { + $statusCode = $exception->getStatusCode(); + $headers = array_merge($exception->getHeaders(), ['Content-Type' => 'application/json']); - /** - * Deserializes data from a given type format. - * - * @param string $data The data to deserialize. - * @param string $class The target data class. - * @param string $format The source serialization format. - * - * @return mixed A deserialized data. - */ - public function deserialize($data, $class, $format) - { - return $this->get('{{bundleAlias}}.model.model_serializer')->deserialize($data, $class, $format); - } + $json = $this->exceptionToArray($exception); + $json['statusCode'] = $statusCode; - /** - * Decodes a string value. - * - * @param string $string The string value to decode. - * @param string $dataType The data type of the parameter. - * - * @return mixed The decoded value. - */ - public function fromString($string, $dataType) - { - if ($dataType === 'integer' || $dataType === 'number') { - return $this->toNumber($string); - } - if ($dataType === 'bool') { - return $this->toBoolean($string); - } - if ($dataType === '\DateTime') { - return $this->toDateTime($string); - } + return new Response(json_encode($json, 15, 512), $statusCode, $headers); + } - return $string; - } + /** + * Serializes data to a given type format. + * + * @param mixed $data The data to serialize. + * @param string $class The source data class. + * @param string $format The target serialization format. + * + * @return string A serialized data string. + */ + protected function serialize($data, $format) + { + return $this->serializer->serialize($data, $format); + } - /** - * Decodes a header value. - * - * @param string $header The header value to decode. - * @param string $dataType The data type of the parameter. - * - * @return mixed The decoded value. - */ - public function fromHeader($header, $dataType) - { - return $this->fromString($header, $dataType); - } + /** + * Deserializes data from a given type format. + * + * @param string $data The data to deserialize. + * @param string $class The target data class. + * @param string $format The source serialization format. + * + * @return mixed A deserialized data. + */ + protected function deserialize($data, $class, $format) + { + return $this->serializer->deserialize($data, $class, $format); + } - /** - * Decodes a query value. - * - * @param string $query The query value to decode. - * @param string $dataType The data type of the parameter. - * - * @return mixed The decoded value. - */ - public function fromQuery($query, $dataType) - { - return $this->fromString($query, $dataType); - } + protected function validate($data, $asserts = null) + { + $errors = $this->validator->validate($data, $asserts); - /** - * Decodes a path value. - * - * @param string $path The path value to decode. - * @param string $dataType The data type of the parameter. - * - * @return mixed The decoded value. - */ - public function fromPath($path, $dataType) - { - return $this->fromString($path, $dataType); - } + if (count($errors) > 0) { + $errorsString = (string)$errors; + return $this->createBadRequestResponse($errorsString); + } + } - /** - * Decodes a form value. - * - * @param string $form The form value to decode. - * @param string $dataType The data type of the parameter. - * - * @return mixed The decoded value. - */ - public function fromForm($form, $dataType) - { - return $this->fromString($form, $dataType); - } + /** + * Converts an exception to a serializable array. + * + * @param \Exception|null $exception + * + * @return array + */ + private function exceptionToArray(\Exception $exception = null) + { + if (null === $exception) { + return null; + } - /** - * Decoded a string to a number. - * - * @param string $string The string to decode. - * - * @return number|null A decoded number, or null, if not a valid string. - */ - private function toNumber($string) - { - if (is_numeric($string)) { - return $string + 0; - } + if (!$this->container->get('kernel')->isDebug()) { + return [ + 'message' => $exception->getMessage(), + ]; + } - return null; - } + return [ + 'message' => $exception->getMessage(), + 'type' => get_class($exception), + 'previous' => $this->exceptionToArray($exception->getPrevious()), + ]; + } - /** - * Decoded a string to a boolean. - * - * @param string $string The string to decode. - * - * @return boolean|null A decoded boolean, or null, if not a valid string. - */ - private function toBoolean($string) - { - if ($string === 'true') { - return true; - } - if ($string === 'false') { - return false; - } + protected function getOutputFormat($accept, array $produced) + { + // Figure out what the client accepts + $accept = preg_split("/[\s,]+/", $accept); + + if (in_array('*/*', $accept) || in_array('application/*', $accept)) { + // Prefer JSON if the client has no preference + if (in_array('application/json', $produced)) { + return 'application/json'; + } + if (in_array('application/xml', $produced)) { + return 'application/xml'; + } + } - return null; - } + if (in_array('application/json', $accept) && in_array('application/json', $produced)) { + return 'application/json'; + } - /** - * Decoded a string to a date time. - * - * @param string $string The string to decode. - * - * @return \DateTime|null A decoded date time, or null, if not a valid string. - */ - private function toDateTime($string) - { - if ($dateTime = date_create($string)) { - return $dateTime; - } + if (in_array('application/xml', $accept) && in_array('application/xml', $produced)) { + return 'application/xml'; + } - return null; - } - - /** - * Converts an exception to a serializable array. - * - * @param \Exception|null $exception - * - * @return array - */ - private function exceptionToArray(\Exception $exception = null) - { - if (null === $exception) { - return null; - } - - return [ - 'message' => $exception->getMessage(), - 'type' => get_class($exception), - 'previous' => $this->exceptionToArray($exception->getPrevious()), - ]; - } + // If we reach this point, we don't have a common ground between server and client + return null; + } } diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/ModelInterface.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/ModelInterface.mustache deleted file mode 100644 index a568374d6d3..00000000000 --- a/modules/swagger-codegen/src/main/resources/php-symfony/ModelInterface.mustache +++ /dev/null @@ -1,55 +0,0 @@ -partial_header}} -/** - * 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. - */ - -namespace {{modelPackage}}; - -/** - * Interface abstracting model access. - * - * @package {{modelPackage}} - * @author Swagger Codegen team - */ -interface ModelInterface -{ - - /** - * The original name of the model. - * - * @return string - */ - public function modelName(); - - /** - * Array of property to mappings. - * - * @return array[] - */ - public function modelAttributes(); - - /** - * Validate all the properties in the model - * - * Return true if all passed. - * - * @return bool True if all properties are valid - */ - public function isValid(); -} - - diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/ModelSerializer.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/ModelSerializer.mustache deleted file mode 100644 index c2064b60a8d..00000000000 --- a/modules/swagger-codegen/src/main/resources/php-symfony/ModelSerializer.mustache +++ /dev/null @@ -1,174 +0,0 @@ -partial_header}} -/** - * 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. - */ - -namespace {{modelPackage}}; - -/** - * ModelSerializer Class Doc Comment - * - * @category Class - * @package {{modelPackage}} - * @author Swagger Codegen team - * @link https://github.com/swagger-api/swagger-codegen - */ -class ModelSerializer -{ - - /** - * Serializes data to a given type format. - * - * @param mixed $data The data to serialize. - * @param string $format The target serialization format. - * - * @return string A serialized data string. - * @throws \InvalidArgumentException When invalid serialization format was used. - */ - public function serialize($data, $format) - { - $normalized = $this->normalize($data); - if ($format === 'json') { - return json_encode($normalized, 15, 512); - } - - throw new \InvalidArgumentException('Unsupported serialization format: '.$format); - } - - /** - * Deserializes data from a given type format. - * - * @param string $data The data to deserialize. - * @param string $class The target class to deserialize to. - * @param string $format The source serialization format. - * - * @return mixed A deserialized value. - * @throws \InvalidArgumentException When invalid serialization format was used. - */ - public function deserialize($data, $class, $format) - { - switch ($format) { - case 'json': - $normalized = json_decode($data, true, 512, 15); - break; - default: - throw new \InvalidArgumentException('Unsupported serialization format: '.$format); - } - - return $this->denormalize($normalized, $class); - } - - public function normalize($data, $format = null) - { - if (is_scalar($data) || null === $data) { - return $data; - } - - if (is_array($data)) { - return array_map(function ($value) use ($format) { - return $this->normalize($value, $format); - }, $data); - } - - if ($data instanceof \DateTime) { - return ($format === 'date') ? $data->format('Y-m-d') : $data->format(\DateTime::ATOM); - } - - if ($data instanceof ModelInterface) { - $values = []; - foreach ($data->modelAttributes() as $name => $attribute) { - list($baseName, , $format, , $getter) = $attribute; - $value = $this->normalize($data->$getter(), $format); - if ($value !== null && method_exists($data, 'getAllowableEnumValues') - && !in_array($value, $data::getAllowableEnumValues())) { - $imploded = implode("', '", $data::getAllowableEnumValues()); - throw new \InvalidArgumentException("Invalid value for enum '$data', must be one of: '$imploded'"); - } - - if ($value !== null) { - $values[$baseName] = $value; - } - } - - return $values; - } - - return (string) $data; - } - - public function denormalize($data, $class, $format = null) - { - if ($data === null) { - return null; - } - - if (in_array($class, ['DateTime', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { - settype($data, $class); - return $data; - } - - // Denormalize array - if (substr($class, -2) === '[]') { - $innerClass = substr($class, 0, -2); - return array_map(function ($value) use ($format, $innerClass) { - return $this->denormalize($value, $innerClass, $format); - }, $data); - } - - if (!class_exists($class)) { - return $data; - } - - // Denormalize enum - if (method_exists($class, 'getAllowableEnumValues')) { - if (!in_array($data, $class::getAllowableEnumValues())) { - $imploded = implode("', '", $class::getAllowableEnumValues()); - throw new \InvalidArgumentException("Invalid value for enum '$class', must be one of: '$imploded'"); - } - - return $data; - } - - // If a discriminator is defined and points to a valid subclass, use it. - $discriminator = $class::DISCRIMINATOR; - if (!empty($discriminator) && isset($data[$discriminator]) && is_string($data[$discriminator])) { - $subclass = '{{modelPackage}}\\'.$data[$discriminator]; - if (is_subclass_of($subclass, $class)) { - $class = $subclass; - } - } - - // Denormalize another model - $values = new $class(); - if ($values instanceof ModelInterface) { - foreach ($values->modelAttributes() as $name => $attribute) { - list($baseName, $innerClass, $format, $setter) = $attribute; - - if (!isset($data[$baseName])) { - continue; - } - - $value = $this->denormalize($data[$baseName], $innerClass, $format); - $values->$setter($value); - } - - return $values; - } - - return $data; - } -} diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/README.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/README.mustache index d61acfa1c84..0b72cf635fa 100644 --- a/modules/swagger-codegen/src/main/resources/php-symfony/README.mustache +++ b/modules/swagger-codegen/src/main/resources/php-symfony/README.mustache @@ -23,28 +23,28 @@ PHP 5.4.0 and later ## Installation & Usage -To install the bindings via [Composer](http://getcomposer.org/), add the following to `composer.json`: +To install the dependencies via [Composer](http://getcomposer.org/), add the following repository to `composer.json` of your Symfony project: -``` +```json { - "repositories": [ - { - "type": "git", - "url": "https://github.com/{{#composerVendorName}}{{.}}{{/composerVendorName}}{{^composerVendorName}}{{gitUserId}}{{/composerVendorName}}/{{#composerProjectName}}{{.}}{{/composerProjectName}}{{^composerProjectName}}{{gitRepoId}}{{/composerProjectName}}.git" - } - ], - "require": { - "{{#composerVendorName}}{{.}}{{/composerVendorName}}{{^composerVendorName}}{{gitUserId}}{{/composerVendorName}}/{{#composerProjectName}}{{.}}{{/composerProjectName}}{{^composerProjectName}}{{gitRepoId}}{{/composerProjectName}}": "*@dev" - } + "repositories": [{ + "type": "path", + "url": "//Path to your generated swagger bundle" + }], } ``` -Then run `composer install` +Then run: +``` +composer require {{#composerVendorName}}{{.}}{{/composerVendorName}}{{^composerVendorName}}{{gitUserId}}{{/composerVendorName}}/{{#composerProjectName}}{{.}}{{/composerProjectName}}{{^composerProjectName}}{{gitRepoId}}{{/composerProjectName}}:dev-master +``` + +to add the generated swagger bundle as a dependency. ## Tests -To run the unit tests: +To run the unit tests for the generated bundle, first navigate to the directory containing the code, then run the following commands: ``` composer install diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/api.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/api.mustache index b3985a9489a..0e581a1b84d 100644 --- a/modules/swagger-codegen/src/main/resources/php-symfony/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php-symfony/api.mustache @@ -18,6 +18,7 @@ namespace {{apiPackage}}; +use Symfony\Component\HttpFoundation\File\UploadedFile; {{#operations}}{{#imports}}use {{import}}; {{/imports}} @@ -58,18 +59,15 @@ interface {{classname}} {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} + * @param integer $responseCode The HTTP response code to return + * @param array $responseHeaders Additional HTTP headers to return with the response () * - {{#responses}} - {{#vendorExtensions.x-symfonyExceptionSimple}} - * @throws {{vendorExtensions.x-symfonyExceptionSimple}} {{message}} - {{/vendorExtensions.x-symfonyExceptionSimple}} - {{^vendorExtensions.x-symfonyExceptionSimple}} - * @return {{^dataType}}void{{/dataType}}{{#dataType}}{{dataType}}{{/dataType}} {{message}} + {{#returnType}} + * @return {{{returnType}}} * - {{/vendorExtensions.x-symfonyExceptionSimple}} - {{/responses}} + {{/returnType}} */ - public function {{operationId}}({{#allParams}}{{#vendorExtensions.x-parameterType}}{{vendorExtensions.x-parameterType}} {{/vendorExtensions.x-parameterType}}${{paramName}}{{^required}} = {{#defaultValue}}'{{{.}}}'{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + public function {{operationId}}({{#allParams}}{{#vendorExtensions.x-parameterType}}{{vendorExtensions.x-parameterType}} {{/vendorExtensions.x-parameterType}}${{paramName}}{{^required}} = {{#defaultValue}}{{{.}}}{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}{{/required}}, {{/allParams}}&$responseCode, array &$responseHeaders); {{/operation}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/api_controller.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/api_controller.mustache index 8fb9efb5ed7..6f21a082eb5 100644 --- a/modules/swagger-codegen/src/main/resources/php-symfony/api_controller.mustache +++ b/modules/swagger-codegen/src/main/resources/php-symfony/api_controller.mustache @@ -23,6 +23,7 @@ use \Exception; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\HttpException; +use Symfony\Component\Validator\Constraints as Assert; use {{apiPackage}}\{{classname}}; {{#imports}}use {{import}}; {{/imports}} @@ -53,8 +54,28 @@ class {{controllerName}} extends Controller * @param Request $request The Symfony request to handle. * @return Response The Symfony response. */ - public function {{operationId}}Action(Request $request) + public function {{operationId}}Action(Request $request{{#hasPathParams}}{{#pathParams}}, ${{paramName}}{{/pathParams}}{{/hasPathParams}}) { + {{#bodyParams}} + // Make sure that the client is providing something that we can consume + $consumes = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]; + $inputFormat = $request->headers->has('Content-Type')?$request->headers->get('Content-Type'):$consumes[0]; + if (!in_array($inputFormat, $consumes)) { + // We can't consume the content that the client is sending us + return new Response('', 415); + } + + {{/bodyParams}} + // Figure out what data format to return to the client + $produces = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication {{#authMethods}} // Authentication '{{name}}' required {{#isApiKey}} @@ -76,81 +97,58 @@ class {{controllerName}} extends Controller $security{{name}} = $request->headers->get('authorization'); {{/isOAuth}} {{/authMethods}} + + // Read out all input parameter values into variables + {{#allParams}} {{#queryParams}} - // Handle query params - ${{paramName}} = $this->fromQuery($request->query->get('{{paramName}}'), '{{dataType}}'); + ${{paramName}} = $request->query->get('{{paramName}}'); {{/queryParams}} {{#headerParams}} - // Handle header params - ${{paramName}} = $this->fromHeader($request->headers->get('{{paramName}}'), '{{dataType}}'); + ${{paramName}} = $request->headers->get('{{paramName}}'); {{/headerParams}} - {{#pathParams}} - // Handle path params - ${{paramName}} = $this->fromPath($request->attributes->get('{{paramName}}'), '{{dataType}}'); - {{/pathParams}} {{#formParams}} {{#isFile}} - // Handle file params ${{paramName}} = $request->files->get('{{paramName}}'); {{/isFile}} {{^isFile}} - // Handle form params - ${{paramName}} = $this->fromForm($request->request->get('{{paramName}}'), '{{dataType}}'); + ${{paramName}} = $request->request->get('{{paramName}}'); {{/isFile}} {{/formParams}} {{#bodyParams}} - // Handle body params - ${{paramName}} = $this->deserialize($request->getContent(), '{{{dataType}}}', 'json'); + ${{paramName}} = $request->getContent(); {{/bodyParams}} - // Parse incoming parameters - {{#allParams}} - {{#required}} - // Verify the required parameter '{{paramName}}' is set - if (${{paramName}} === null) { - return $this->createBadRequestResponse('Missing the required parameter ${{paramName}} when calling {{operationId}}'); - } + // Use the default value if no value was provided + {{^required}} + {{#isContainer}} + {{#items}} + {{#defaultValue}} + ${{paramName}} = ${{paramName}}?:[{{{defaultValue}}}]; + {{/defaultValue}} + {{/items}} + {{/isContainer}} + {{^isContainer}} + {{#defaultValue}} + ${{paramName}} = ${{paramName}}?:{{{defaultValue}}}; + {{/defaultValue}} + {{/isContainer}} {{/required}} - {{#hasValidation}} - {{#maxLength}} - if ({{^required}}!is_null(${{paramName}}) && {{/required}}(strlen(${{paramName}}) > {{maxLength}})) { - return $this->createBadRequestResponse('Invalid length for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maxLength}}.'); - } - {{/maxLength}} - {{#minLength}} - if ({{^required}}!is_null(${{paramName}}) && {{/required}}(strlen(${{paramName}}) < {{minLength}})) { - return $this->createBadRequestResponse('Invalid length for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minLength}}.'); - } - {{/minLength}} - {{#maximum}} - if ({{^required}}!is_null(${{paramName}}) && {{/required}}(${{paramName}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}})) { - return $this->createBadRequestResponse('Invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.'); - } - {{/maximum}} - {{#minimum}} - if ({{^required}}!is_null(${{paramName}}) && {{/required}}(${{paramName}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}})) { - return $this->createBadRequestResponse('Invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.'); - } - {{/minimum}} - {{#pattern}} - if ({{^required}}!is_null(${{paramName}}) && {{/required}}!preg_match("{{{pattern}}}", ${{paramName}})) { - return $this->createBadRequestResponse("Invalid value for \"{{paramName}}\" when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}."); - } - {{/pattern}} - {{#maxItems}} - if ({{^required}}!is_null(${{paramName}}) && {{/required}}(count(${{paramName}}) > {{maxItems}})) { - return $this->createBadRequestResponse('Invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{maxItems}}.'); - } - {{/maxItems}} - {{#minItems}} - if ({{^required}}!is_null(${{paramName}}) && {{/required}}(count(${{paramName}}) < {{minItems}})) { - return $this->createBadRequestResponse('Invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{minItems}}.'); - } - {{/minItems}} - {{/hasValidation}} + + // Deserialize the input values that needs it + {{^isFile}} + {{#bodyParams}} + + ${{paramName}} = $this->deserialize(${{paramName}}, '{{{dataType}}}', $inputFormat); + {{/bodyParams}} + {{^bodyParams}} + ${{paramName}} = $this->deserialize(${{paramName}}, '{{#isContainer}}array<{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}{{^collectionFormat}}csv{{/collectionFormat}}>{{/isContainer}}{{^isContainer}}{{dataType}}{{/isContainer}}', 'string'); + {{/bodyParams}} + {{/isFile}} {{/allParams}} - // Call the API interface + // Validate the input values +{{>api_input_validation}} + try { $handler = $this->getApiHandler(); @@ -158,31 +156,35 @@ class {{controllerName}} extends Controller // Set authentication method '{{name}}' $handler->set{{name}}($security{{name}}); {{/authMethods}} - {{#returnType}} - // Expecting a return value (exception otherwise) - $result = $handler->{{operationId}}({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + + // Make the call to the business logic + $responseCode = {{#returnType}}200{{/returnType}}{{^returnType}}204{{/returnType}}; + $responseHeaders = []; + $result = $handler->{{operationId}}({{#allParams}}${{paramName}}, {{/allParams}}$responseCode, $responseHeaders); + // Find default response message + $message = '{{#responses}}{{#isDefault}}{{message}}{{/isDefault}}{{/responses}}'; + + // Find a more specific message, if available + switch ($responseCode) { {{#responses}} - {{^vendorExtensions.x-symfonyExceptionSimple}} - // Handle {{code}} response: {{message}} - $content = $this->serialize($result, 'json'); - return new Response($content, {{code}}, [ - 'Content-Type' => 'application/json', - 'X-Swagger-Message' => '{{message}}', - ]); - {{/vendorExtensions.x-symfonyExceptionSimple}} + case {{code}}: + $message = '{{message}}'; + break; {{/responses}} - {{/returnType}} - {{^returnType}} - // No return type expected; return empty response - $handler->{{operationId}}({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - return new Response('', 204); - {{/returnType}} - {{#responses}} - } catch (HttpException $exception) { - // {{message}} - return $this->createErrorResponse($exception); - {{/responses}} + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); } catch (Exception $fallthrough) { return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); } @@ -195,7 +197,7 @@ class {{controllerName}} extends Controller */ public function getApiHandler() { - return $this->get('{{bundleAlias}}.api.api_server')->getApiHandler('{{pathPrefix}}'); + return $this->apiServer->getApiHandler('{{pathPrefix}}'); } } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/api_input_validation.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/api_input_validation.mustache new file mode 100644 index 00000000000..0bcd3053485 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php-symfony/api_input_validation.mustache @@ -0,0 +1,88 @@ +{{#allParams}} + $asserts = []; +{{#required}} + $asserts[] = new Assert\NotNull(); +{{/required}} +{{#isEnum}} + {{#isContainer}} + $asserts[] = new Assert\All([ + {{#items}} + new Assert\Choice([ {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}} ]) + {{/items}} + ]); + {{/isContainer}} + {{^isContainer}} + $asserts[] = new Assert\Choice([ {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}} ]); + {{/isContainer}} +{{/isEnum}} +{{#isContainer}} + $asserts[] = new Assert\All([ + {{#items}} + new Assert\Type("{{datatype}}") + {{/items}} + ]); +{{/isContainer}} +{{^isContainer}} + {{#isDate}} + $asserts[] = new Assert\Date(); + {{/isDate}} + {{#isDateTime}} + $asserts[] = new Assert\DateTime(); + {{/isDateTime}} + {{^isDate}} + {{^isDateTime}} + {{#isFile}} + $asserts[] = new Assert\File(); + {{/isFile}} + {{^isFile}} + $asserts[] = new Assert\Type("{{dataType}}"); + {{/isFile}} + {{/isDateTime}} + {{/isDate}} +{{/isContainer}} +{{#hasValidation}} + {{#maxLength}} + $asserts[] = new Assert\Length([ + 'max' => {{maxLength}} + ]); + {{/maxLength}} + {{#minLength}} + $asserts[] = new Assert\Length([ + 'min' => {{minLength}} + ]); + {{/minLength}} + {{#minimum}} + {{#exclusiveMinimum}} + $asserts[] = new Assert\GreaterThan({{minimum}}); + {{/exclusiveMinimum}} + {{^exclusiveMinimum}} + $asserts[] = new Assert\GreaterThanOrEqual({{minimum}}); + {{/exclusiveMinimum}} + {{/minimum}} + {{#maximum}} + {{#exclusiveMaximum}} + $asserts[] = new Assert\LessThan({{minimum}}); + {{/exclusiveMaximum}} + {{^exclusiveMaximum}} + $asserts[] = new Assert\LessThanOrEqual({{minimum}}); + {{/exclusiveMaximum}} + {{/maximum}} + {{#pattern}} + $asserts[] = new Assert\Regex("/{{pattern}}/"); + {{/pattern}} + {{#maxItems}} + $asserts[] = new Assert\Count([ + 'max' => {{maxItems}} + ]); + {{/maxItems}} + {{#minItems}} + $asserts[] = new Assert\Count([ + 'min' => {{minItems}} + ]); + {{/minItems}} +{{/hasValidation}} + $response = $this->validate(${{paramName}}, $asserts); + if ($response instanceof Response) { + return $response; + } +{{/allParams}} diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/api_test.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/api_test.mustache deleted file mode 100644 index c1f16c70cea..00000000000 --- a/modules/swagger-codegen/src/main/resources/php-symfony/api_test.mustache +++ /dev/null @@ -1,77 +0,0 @@ -partial_header}} -/** - * 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. - */ - -namespace {{apiTestsPackage}}; - -use \{{invokerPackage}}\Configuration; -use \{{invokerPackage}}\ApiClient; -use \{{invokerPackage}}\ApiException; -use \{{invokerPackage}}\ObjectSerializer; - -/** - * {{classname}}Test Class Doc Comment - * - * @category Class - * @package {{apiTestsPackage}} - * @author Swagger Codegen team - * @link https://github.com/swagger-api/swagger-codegen - */ -{{#operations}}class {{classname}}Test extends \PHPUnit_Framework_TestCase -{ - - /** - * Setup before running any test cases - */ - public static function setUpBeforeClass() - { - } - - /** - * Setup before running each test case - */ - public function setUp() - { - } - - /** - * Clean up after running each test case - */ - public function tearDown() - { - } - - /** - * Clean up after running all test cases - */ - public static function tearDownAfterClass() - { - } - {{#operation}} - - /** - * Test case for {{{operationId}}} - * - * {{{summary}}}. - * - */ - public function test{{operationIdCamelCase}}() - { - } - {{/operation}} -} -{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/composer.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/composer.mustache index eda7618bf65..5d6156df550 100644 --- a/modules/swagger-codegen/src/main/resources/php-symfony/composer.mustache +++ b/modules/swagger-codegen/src/main/resources/php-symfony/composer.mustache @@ -23,13 +23,17 @@ "ext-curl": "*", "ext-json": "*", "ext-mbstring": "*", + "symfony/validator": "*", + "jms/serializer-bundle": "*", "symfony/framework-bundle": "^2.3|^3.0" }, "require-dev": { "phpunit/phpunit": "~4.8", "satooshi/php-coveralls": "~1.0", "squizlabs/php_codesniffer": "~2.6", - "friendsofphp/php-cs-fixer": "~1.12" + "friendsofphp/php-cs-fixer": "~1.12", + "symfony/browser-kit": "*", + "hoa/regex": "~1.0" }, "autoload": { "psr-4": { "{{escapedInvokerPackage}}\\" : "{{srcBasePath}}/" } diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/git_push.sh.mustache index a9b0f28edfb..f65b794638f 100755 --- a/modules/swagger-codegen/src/main/resources/php-symfony/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/php-symfony/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/model.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/model.mustache index 6e865578075..02d96acb45f 100644 --- a/modules/swagger-codegen/src/main/resources/php-symfony/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php-symfony/model.mustache @@ -21,10 +21,9 @@ namespace {{modelPackage}}; -{{^isEnum}} -{{#useStatements}}use {{this}}; -{{/useStatements}} -{{/isEnum}} +use Symfony\Component\Validator\Constraints as Assert; +use JMS\Serializer\Annotation\Type; +use JMS\Serializer\Annotation\SerializedName; /** * Class representing the {{classname}} model. @@ -36,5 +35,5 @@ namespace {{modelPackage}}; * @package {{modelPackage}} * @author Swagger Codegen team */ -{{#isEnum}}{{>model_enum}}{{/isEnum}}{{^isEnum}}{{>model_generic}}{{/isEnum}} +{{>model_generic}} {{/model}}{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/model_generic.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/model_generic.mustache index 8e72f968406..8106055c854 100644 --- a/modules/swagger-codegen/src/main/resources/php-symfony/model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/php-symfony/model_generic.mustache @@ -1,49 +1,6 @@ -class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}implements ModelInterface, \ArrayAccess +class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}} { - const DISCRIMINATOR = {{#discriminator}}'{{discriminator}}'{{/discriminator}}{{^discriminator}}null{{/discriminator}}; - - /** - * The original name of the model. - * @var string - */ - protected static $_name = '{{name}}'; - - /** - * Array of property to type mappings. Used for (de)serialization - * @var array[] - */ - protected static $_attributes = [{{#vars}} - '{{name}}' => ['{{baseName}}', '{{{vendorExtensions.x-fullType}}}', {{#dataFormat}}'{{{dataFormat}}}'{{/dataFormat}}{{^dataFormat}}null{{/dataFormat}}, '{{setter}}', '{{getter}}'],{{/vars}} - ]; - {{#vars}}{{#isEnum}} - - /** - * Allowed values of {{name}} - */{{#allowableValues}}{{#enumVars}} - const {{enumName}}_{{{name}}} = {{{value}}};{{/enumVars}}{{/allowableValues}}{{/isEnum}}{{/vars}} - - {{#vars}}{{#isEnum}} - /** - * Gets allowable values of the enum - * @return string[] - */ - public function {{getter}}AllowableValues() - { - return [ - {{#allowableValues}}{{#enumVars}}self::{{enumName}}_{{{name}}},{{^-last}} - {{/-last}}{{/enumVars}}{{/allowableValues}} - ]; - } - {{/isEnum}}{{/vars}} - {{#vars}} - /**{{#description}} - * {{description}} - * - {{/description}} - * @var {{{datatype}}}{{^required}}|null{{/required}} - */ - protected ${{name}}; - + {{#vars}}{{>model_variables}} {{/vars}} /** * Constructor @@ -58,187 +15,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple {{#vars}} $this->{{name}} = isset($data['{{name}}']) ? $data['{{name}}'] : {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}; {{/vars}} - {{#discriminator}} - - // Initialize discriminator property with the model name. - foreach (self::$_attributes as $_name => $attribute) { - list($baseName) = $attribute; - if ('{{discriminator}}' === $baseName) { - $this->$_name = static::$_name; - } - } - {{/discriminator}} } - - /** - * show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - {{#parent}} - $invalid_properties = parent::listInvalidProperties(); - {{/parent}} - {{^parent}} - $invalid_properties = []; - {{/parent}} - - {{#vars}} - {{#required}} - if ($this->{{name}} === null) { - $invalid_properties[] = "'{{name}}' can't be null"; - } - {{/required}} - {{#isEnum}} - {{^isContainer}} - $allowedValues = $this->{{getter}}AllowableValues(); - if (!in_array($this->{{name}}, $allowedValues, true)) { - $invalid_properties[] = sprintf( - "invalid value for '{{name}}', must be one of '%s'", - implode("', '", $allowedValues) - ); - } - - {{/isContainer}} - {{/isEnum}} - {{#hasValidation}} - {{#maxLength}} - if ({{^required}}!is_null($this->{{name}}) && {{/required}}(strlen($this->{{name}}) > {{maxLength}})) { - $invalid_properties[] = "invalid value for '{{name}}', the character length must be smaller than or equal to {{{maxLength}}}."; - } - - {{/maxLength}} - {{#minLength}} - if ({{^required}}!is_null($this->{{name}}) && {{/required}}(strlen($this->{{name}}) < {{minLength}})) { - $invalid_properties[] = "invalid value for '{{name}}', the character length must be bigger than or equal to {{{minLength}}}."; - } - - {{/minLength}} - {{#maximum}} - if ({{^required}}!is_null($this->{{name}}) && {{/required}}($this->{{name}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}})) { - $invalid_properties[] = "invalid value for '{{name}}', must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}."; - } - - {{/maximum}} - {{#minimum}} - if ({{^required}}!is_null($this->{{name}}) && {{/required}}($this->{{name}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}})) { - $invalid_properties[] = "invalid value for '{{name}}', must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}."; - } - - {{/minimum}} - {{#pattern}} - if ({{^required}}!is_null($this->{{name}}) && {{/required}}!preg_match("{{{pattern}}}", $this->{{name}})) { - $invalid_properties[] = "invalid value for '{{name}}', must be conform to the pattern {{{pattern}}}."; - } - - {{/pattern}} - {{#maxItems}} - if ({{^required}}!is_null($this->{{name}}) && {{/required}}(count($this->{{name}}) > {{maxItems}})) { - $invalid_properties[] = "invalid value for '{{name}}', number of items must be less than or equal to {{{maxItems}}}."; - } - - {{/maxItems}} - {{#minItems}} - if ({{^required}}!is_null($this->{{name}}) && {{/required}}(count($this->{{name}}) < {{minItems}})) { - $invalid_properties[] = "invalid value for '{{name}}', number of items must be greater than or equal to {{{minItems}}}."; - } - - {{/minItems}} - {{/hasValidation}} - {{/vars}} - return $invalid_properties; - } - - /** - * The original name of the model. - * - * @return string - */ - public function modelName() { - return self::$_name; - } - - /** - * Array of property to mappings. - * - * @return array[] - */ - public function modelAttributes() { - {{#parentSchema}}return array_merge(parent::$_attributes, self::$_attributes);{{/parentSchema}} - {{^parentSchema}}return self::$_attributes;{{/parentSchema}} - } - - /** - * Validate all the properties in the model - * - * Return true if all passed. - * - * @return bool True if all properties are valid - */ - public function isValid() - { - {{#parent}} - if (!parent::isValid()) { - return false; - } - - {{/parent}} - {{#vars}} - {{#required}} - if ($this->{{name}} === null) { - return false; - } - {{/required}} - {{#isEnum}} - {{^isContainer}} - $allowedValues = $this->{{getter}}AllowableValues(); - if (!in_array($this->{{name}}, $allowedValues)) { - return false; - } - {{/isContainer}} - {{/isEnum}} - {{#hasValidation}} - {{#maxLength}} - if (strlen($this->{{name}}) > {{maxLength}}) { - return false; - } - {{/maxLength}} - {{#minLength}} - if (strlen($this->{{name}}) < {{minLength}}) { - return false; - } - {{/minLength}} - {{#maximum}} - if ($this->{{name}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}) { - return false; - } - {{/maximum}} - {{#minimum}} - if ($this->{{name}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}) { - return false; - } - {{/minimum}} - {{#pattern}} - if (!preg_match("{{{pattern}}}", $this->{{name}})) { - return false; - } - {{/pattern}} - {{#maxItems}} - if (count($this->{{name}}) > {{maxItems}}) { - return false; - } - {{/maxItems}} - {{#minItems}} - if (count($this->{{name}}) < {{minItems}}) { - return false; - } - {{/minItems}} - {{/hasValidation}} - {{/vars}} - return true; - } - {{#vars}} /** @@ -258,109 +35,11 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * * @return $this */ - public function {{setter}}({{#vendorExtensions.x-typeAnnotation}}{{vendorExtensions.x-typeAnnotation}} {{/vendorExtensions.x-typeAnnotation}}${{name}}{{^required}} = null{{/required}}) + public function {{setter}}({{#vendorExtensions.x-parameterType}}{{vendorExtensions.x-parameterType}} {{/vendorExtensions.x-parameterType}}${{name}}{{^required}} = null{{/required}}) { - {{#isEnum}} - $allowedValues = $this->{{getter}}AllowableValues(); - {{^isContainer}} - if ({{^required}}${{name}} !== null && {{/required}}!in_array(${{{name}}}, $allowedValues, true)) { - throw new \InvalidArgumentException( - sprintf( - "Invalid value for '{{name}}', must be one of '%s'", - implode("', '", $allowedValues) - ) - ); - } - {{/isContainer}} - {{#isContainer}} - if ({{^required}}!is_null(${{name}}) && {{/required}}array_diff(${{{name}}}, $allowedValues)) { - throw new \InvalidArgumentException( - sprintf( - "Invalid value for '{{name}}', must be one of '%s'", - implode("', '", $allowedValues) - ) - ); - } - {{/isContainer}} - {{/isEnum}} - {{#hasValidation}} - {{#maxLength}} - if ({{^required}}!is_null(${{name}}) && {{/required}}(strlen(${{name}}) > {{maxLength}})) { - throw new \InvalidArgumentException('invalid length for ${{name}} when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maxLength}}.'); - }{{/maxLength}} - {{#minLength}} - if ({{^required}}!is_null(${{name}}) && {{/required}}(strlen(${{name}}) < {{minLength}})) { - throw new \InvalidArgumentException('invalid length for ${{name}} when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minLength}}.'); - } - {{/minLength}} - {{#maximum}} - if ({{^required}}!is_null(${{name}}) && {{/required}}(${{name}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}})) { - throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.'); - } - {{/maximum}} - {{#minimum}} - if ({{^required}}!is_null(${{name}}) && {{/required}}(${{name}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}})) { - throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.'); - } - {{/minimum}} - {{#pattern}} - if ({{^required}}!is_null(${{name}}) && {{/required}}(!preg_match("{{{pattern}}}", ${{name}}))) { - throw new \InvalidArgumentException("invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}."); - } - {{/pattern}} - {{#maxItems}} - if ({{^required}}!is_null(${{name}}) && {{/required}}(count(${{name}}) > {{maxItems}})) { - throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{maxItems}}.'); - }{{/maxItems}} - {{#minItems}} - if ({{^required}}!is_null(${{name}}) && {{/required}}(count(${{name}}) < {{minItems}})) { - throw new \InvalidArgumentException('invalid length for ${{name}} when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{minItems}}.'); - } - {{/minItems}} - {{/hasValidation}} $this->{{name}} = ${{name}}; return $this; } {{/vars}} - /** - * Returns true if offset exists. False otherwise. - * @param integer $offset Offset - * @return boolean - */ - public function offsetExists($offset) - { - return isset($this->$offset); - } - - /** - * Gets offset. - * @param integer $offset Offset - * @return mixed - */ - public function offsetGet($offset) - { - return isset($this->$offset) ? $this->$offset : null; - } - - /** - * Sets value based on offset. - * @param string $offset Offset - * @param mixed $value Value to be set - * @return void - */ - public function offsetSet($offset, $value) - { - $this->$offset = $value; - } - - /** - * Unsets offset. - * @param integer $offset Offset - * @return void - */ - public function offsetUnset($offset) - { - $this->$offset = null; - } } diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/model_variables.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/model_variables.mustache new file mode 100644 index 00000000000..d0af5b8579e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php-symfony/model_variables.mustache @@ -0,0 +1,91 @@ + /** + {{#description}} + * {{description}} + * + {{/description}} + * @var {{{datatype}}}{{^required}}|null{{/required}} + * @SerializedName("{{baseName}}") +{{#required}} + * @Assert\NotNull() +{{/required}} +{{#isEnum}} + {{#isContainer}} + * @Assert\All({ + {{#items}} + * @Assert\Choice({ {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}} }) + {{/items}} + * }) + {{/isContainer}} + {{^isContainer}} + * @Assert\Choice({ {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}} }) + {{/isContainer}} +{{/isEnum}} +{{#isContainer}} + * @Assert\All({ + {{#items}} + * @Assert\Type("{{datatype}}") + {{/items}} + * }) + {{#items}} + * @Type("array<{{datatype}}>") + {{/items}} +{{/isContainer}} +{{^isContainer}} + {{#isDate}} + * @Assert\Date() + * @Type("DateTime") + {{/isDate}} + {{#isDateTime}} + * @Assert\DateTime() + * @Type("DateTime") + {{/isDateTime}} + {{^isDate}} + {{^isDateTime}} + * @Assert\Type("{{datatype}}") + * @Type("{{datatype}}") + {{/isDateTime}} + {{/isDate}} +{{/isContainer}} +{{#hasValidation}} + {{#maxLength}} + * @Assert\Length( + * max = {{maxLength}} + * ) + {{/maxLength}} + {{#minLength}} + * @Assert\Length( + * min = {{minLength}} + * ) + {{/minLength}} + {{#minimum}} + {{#exclusiveMinimum}} + * @Assert\GreaterThan({{minimum}}) + {{/exclusiveMinimum}} + {{^exclusiveMinimum}} + * @Assert\GreaterThanOrEqual({{minimum}}) + {{/exclusiveMinimum}} + {{/minimum}} + {{#maximum}} + {{#exclusiveMaximum}} + * @Assert\LessThan({{minimum}}) + {{/exclusiveMaximum}} + {{^exclusiveMaximum}} + * @Assert\LessThanOrEqual({{minimum}}) + {{/exclusiveMaximum}} + {{/maximum}} + {{#pattern}} + * @Assert\Regex("/{{pattern}}/") + {{/pattern}} + {{#maxItems}} + * @Assert\Count( + * max = {{maxItems}} + * ) + {{/maxItems}} + {{#minItems}} + * @Assert\Count( + * min = {{minItems}} + * ) + {{/minItems}} +{{/hasValidation}} + */ + protected ${{name}}; diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/routing.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/routing.mustache index e91e9349c06..e0294a956d1 100644 --- a/modules/swagger-codegen/src/main/resources/php-symfony/routing.mustache +++ b/modules/swagger-codegen/src/main/resources/php-symfony/routing.mustache @@ -11,7 +11,29 @@ path: {{path}} methods: [{{httpMethod}}] defaults: - _controller: {{bundleClassName}}:{{baseName}}:{{operationId}} + _controller: {{bundleAlias}}.controller.{{pathPrefix}}:{{operationId}}Action + {{#hasPathParams}} + requirements: + {{/hasPathParams}} + {{#pathParams}} + {{#pattern}} + {{paramName}}: '{{pattern}}' + {{/pattern}} + {{^pattern}} + {{#isLong}} + {{paramName}}: '\d+' + {{/isLong}} + {{#isInteger}} + {{paramName}}: '\d+' + {{/isInteger}} + {{#isString}} + {{paramName}}: '[a-z0-9]+' + {{/isString}} + {{#isBoolean}} + {{paramName}}: 'true|false' + {{/isBoolean}} + {{/pattern}} + {{/pathParams}} {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/serialization/JmsSerializer.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/serialization/JmsSerializer.mustache new file mode 100644 index 00000000000..995e71ba023 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php-symfony/serialization/JmsSerializer.mustache @@ -0,0 +1,91 @@ +serializer = SerializerBuilder::create() + ->setDeserializationVisitor('json', new StrictJsonDeserializationVisitor($naming_strategy)) + ->setDeserializationVisitor('xml', new XmlDeserializationVisitor($naming_strategy)) + ->build(); + } + + public function serialize($data, $format) + { + return SerializerBuilder::create()->build()->serialize($data, $this->convertFormat($format)); + } + + public function deserialize($data, $type, $format) + { + if ($format == 'string') { + return $this->deserializeString($data, $type); + } + + // If we end up here, let JMS serializer handle the deserialization + return $this->serializer->deserialize($data, $type, $this->convertFormat($format)); + } + + private function convertFormat($format) + { + switch ($format) { + case 'application/json': + return 'json'; + case 'application/xml': + return 'xml'; + } + + return null; + } + + private function deserializeString($data, $type) + { + switch ($type) { + case 'int': + case 'integer': + if (is_int($data)) { + return $data; + } + + if (is_numeric($data)) { + return $data + 0; + } + + break; + case 'string': + break; + case 'boolean': + case 'bool': + if (strtolower($data) === 'true') { + return true; + } + + if (strtolower($data) === 'false') { + return false; + } + + break; + case 'array': + return explode(',', $data); + case 'array': + return explode(' ', $data); + case 'array': + return explode("\t", $data); + case 'array': + return explode('|', $data); + } + + // If we end up here, just return data + return $data; + } +} diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/serialization/SerializerInterface.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/serialization/SerializerInterface.mustache new file mode 100644 index 00000000000..60ad8724648 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php-symfony/serialization/SerializerInterface.mustache @@ -0,0 +1,27 @@ +getCurrentPath()) > 0) { + $property = sprintf('property "%s" to be ', implode('.', $context->getCurrentPath())); + } else { + $property = ''; + } + + return new static(sprintf( + 'Expected %s%s, but got %s: %s', + $property, + $expected_type, + gettype($actual_value), + json_encode($actual_value) + )); + } +} diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/services.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/services.mustache index 89e2bb8a96b..f6aec0cc2e0 100644 --- a/modules/swagger-codegen/src/main/resources/php-symfony/services.mustache +++ b/modules/swagger-codegen/src/main/resources/php-symfony/services.mustache @@ -2,9 +2,33 @@ # https://github.com/swagger-api/swagger-codegen # Do not edit the class manually. +parameters: + {{bundleAlias}}.serializer: '{{servicePackage}}\JmsSerializer' + {{bundleAlias}}.validator: '{{servicePackage}}\SymfonyValidator' + services: {{bundleAlias}}.api.api_server: class: {{apiPackage}}\ApiServer {{bundleAlias}}.model.model_serializer: class: {{modelPackage}}\ModelSerializer + + {{bundleAlias}}.service.serializer: + class: %{{bundleAlias}}.serializer% + + {{bundleAlias}}.service.validator: + class: %{{bundleAlias}}.validator% + +{{#apiInfo}} +{{#apis}} +{{#operations}} + {{bundleAlias}}.controller.{{pathPrefix}}: + class: {{controllerPackage}}\{{baseName}}Controller + calls: + - [setSerializer, ['@{{bundleAlias}}.service.serializer']] + - [setValidator, ['@{{bundleAlias}}.service.validator']] + - [setApiServer, ['@{{bundleAlias}}.api.api_server']] + +{{/operations}} +{{/apis}} +{{/apiInfo}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/testing/AppKernel.php b/modules/swagger-codegen/src/main/resources/php-symfony/testing/AppKernel.php new file mode 100644 index 00000000000..631690bc978 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php-symfony/testing/AppKernel.php @@ -0,0 +1,21 @@ +load(__DIR__.'/test_config.yml'); + } +} diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/testing/api_test.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/testing/api_test.mustache new file mode 100644 index 00000000000..d337c1e3df6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php-symfony/testing/api_test.mustache @@ -0,0 +1,116 @@ +partial_header}} +/** + * 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. + */ + +namespace {{apiTestsPackage}}; + +use {{invokerPackage}}\Configuration; +use {{invokerPackage}}\ApiClient; +use {{invokerPackage}}\ApiException; +use {{invokerPackage}}\ObjectSerializer; +use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; + +/** + * {{classname}}Test Class Doc Comment + * + * @category Class + * @package {{apiTestsPackage}} + * @author Swagger Codegen team + * @link https://github.com/swagger-api/swagger-codegen + */ +{{#operations}}class {{classname}}Test extends WebTestCase +{ + + /** + * Setup before running any test cases + */ + public static function setUpBeforeClass() + { + } + + /** + * Setup before running each test case + */ + public function setUp() + { + } + + /** + * Clean up after running each test case + */ + public function tearDown() + { + } + + /** + * Clean up after running all test cases + */ + public static function tearDownAfterClass() + { + } + {{#operation}} + + /** + * Test case for {{{operationId}}} + * + * {{{summary}}}. + * + */ + public function test{{operationIdCamelCase}}() + { + $client = static::createClient(); + + $path = '{{path}}'; + {{#pathParams}} + {{=<% %>=}} + $pattern = '{<%paramName%>}'; + <%={{ }}=%> + {{#pattern}} + $data = $this->genTestData('{{pattern}}'); + {{/pattern}} + {{^pattern}} + {{#isLong}} + $data = $this->genTestData('\d+'); + {{/isLong}} + {{#isInteger}} + $data = $this->genTestData('\d+'); + {{/isInteger}} + {{#isString}} + $data = $this->genTestData('[a-z0-9]+'); + {{/isString}} + {{#isBoolean}} + $data = $this->genTestData('true|false'); + {{/isBoolean}} + {{/pattern}} + $path = str_replace($pattern, $data, $path); + {{/pathParams}} + + $crawler = $client->request('{{httpMethod}}', $path); + } + {{/operation}} + + protected function genTestData($regexp) + { + $grammar = new \Hoa\File\Read('hoa://Library/Regex/Grammar.pp'); + $compiler = \Hoa\Compiler\Llk\Llk::load($grammar); + $ast = $compiler->parse($regexp); + $generator = new \Hoa\Regex\Visitor\Isotropic(new \Hoa\Math\Sampler\Random()); + + return $generator->visit($ast); + } +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/model_test.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/testing/model_test.mustache similarity index 95% rename from modules/swagger-codegen/src/main/resources/php-symfony/model_test.mustache rename to modules/swagger-codegen/src/main/resources/php-symfony/testing/model_test.mustache index 797f9a2af2a..b4b9cf012a3 100644 --- a/modules/swagger-codegen/src/main/resources/php-symfony/model_test.mustache +++ b/modules/swagger-codegen/src/main/resources/php-symfony/testing/model_test.mustache @@ -19,7 +19,7 @@ * Please update the test case below to test the model. */ -namespace {{modelTestsPackage}}; +namespace {{modelPackage}}; /** * {{classname}}Test Class Doc Comment @@ -67,6 +67,7 @@ class {{classname}}Test extends \PHPUnit_Framework_TestCase */ public function test{{classname}}() { + $test{{classname}} = new {{classname}}(); } {{#vars}} diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/phpunit.xml.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/testing/phpunit.xml.mustache similarity index 90% rename from modules/swagger-codegen/src/main/resources/php-symfony/phpunit.xml.mustache rename to modules/swagger-codegen/src/main/resources/php-symfony/testing/phpunit.xml.mustache index 5de6fea575c..bd5b2978ee0 100644 --- a/modules/swagger-codegen/src/main/resources/php-symfony/phpunit.xml.mustache +++ b/modules/swagger-codegen/src/main/resources/php-symfony/testing/phpunit.xml.mustache @@ -12,6 +12,10 @@ + + + + {{apiSrcPath}} diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/testing/pom.xml b/modules/swagger-codegen/src/main/resources/php-symfony/testing/pom.xml new file mode 100644 index 00000000000..614b3d33f98 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php-symfony/testing/pom.xml @@ -0,0 +1,57 @@ + + 4.0.0 + com.penneo + PhpSymfonyPetstoreServerTests + pom + 1.0-SNAPSHOT + PHP Symfony Swagger Petstore Server + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + bundle-install + pre-integration-test + + exec + + + composer + + install + + + + + bundle-test + integration-test + + exec + + + vendor/bin/phpunit + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/testing/test_config.yml b/modules/swagger-codegen/src/main/resources/php-symfony/testing/test_config.yml new file mode 100644 index 00000000000..10c88a274c9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php-symfony/testing/test_config.yml @@ -0,0 +1,8 @@ +imports: + - { resource: "../Resources/config/services.yml" } + +framework: + secret: "testsecret" + test: ~ + router: + resource: "%kernel.root_dir%/../Resources/config/routing.yml" diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/validation/SymfonyValidator.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/validation/SymfonyValidator.mustache new file mode 100644 index 00000000000..3b6c5dd0ef6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php-symfony/validation/SymfonyValidator.mustache @@ -0,0 +1,20 @@ +validator = Validation::createValidator(); + } + + public function validate($value, $constraints = null, $groups = null) + { + return $this->validator->validate($value, $constraints, $groups); + } +} diff --git a/modules/swagger-codegen/src/main/resources/php-symfony/validation/ValidatorInterface.mustache b/modules/swagger-codegen/src/main/resources/php-symfony/validation/ValidatorInterface.mustache new file mode 100644 index 00000000000..e2a0d9badc5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php-symfony/validation/ValidatorInterface.mustache @@ -0,0 +1,25 @@ +setUsername('YOUR_USERNAME'); -{{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD');{{/isBasic}}{{#isApiKey}} + ->setUsername('YOUR_USERNAME') + ->setPassword('YOUR_PASSWORD');{{/isBasic}}{{#isApiKey}} // Configure API key authorization: {{{name}}} -{{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKey('{{{keyParamName}}}', 'YOUR_API_KEY'); +$config = {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKey('{{{keyParamName}}}', 'YOUR_API_KEY'); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -// {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKeyPrefix('{{{keyParamName}}}', 'Bearer');{{/isApiKey}}{{#isOAuth}} +// $config = {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKeyPrefix('{{{keyParamName}}}', 'Bearer');{{/isApiKey}}{{#isOAuth}} // Configure OAuth2 access token for authorization: {{{name}}} -{{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');{{/isOAuth}}{{/authMethods}} +$config = {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} -$api_instance = new {{invokerPackage}}\Api\{{classname}}(); +$apiInstance = new {{invokerPackage}}\Api\{{classname}}( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(){{#hasAuthMethods}}, + $config{{/hasAuthMethods}} +); {{#allParams}}${{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}} {{/allParams}} try { - {{#returnType}}$result = {{/returnType}}$api_instance->{{{operationId}}}({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + {{#returnType}}$result = {{/returnType}}$apiInstance->{{{operationId}}}({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} print_r($result);{{/returnType}} } catch (Exception $e) { echo 'Exception when calling {{classname}}->{{operationId}}: ', $e->getMessage(), PHP_EOL; diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 7ba928ce184..5fffd0de57f 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -23,6 +23,7 @@ use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; +use GuzzleHttp\RequestOptions; use {{invokerPackage}}\ApiException; use {{invokerPackage}}\Configuration; use {{invokerPackage}}\HeaderSelector; @@ -122,14 +123,15 @@ use {{invokerPackage}}\ObjectSerializer; $request = $this->{{operationId}}Request({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -236,7 +238,7 @@ use {{invokerPackage}}\ObjectSerializer; $request = $this->{{operationId}}Request({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { {{#returnType}} @@ -487,5 +489,23 @@ use {{invokerPackage}}\ObjectSerializer; } {{/operation}} + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } } {{/operations}} 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 6d0ad8ebbb4..4118b83c30d 100644 --- a/modules/swagger-codegen/src/main/resources/php/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api_doc.mustache @@ -23,22 +23,29 @@ Method | HTTP request | Description require_once(__DIR__ . '/vendor/autoload.php'); {{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} // Configure HTTP basic authorization: {{{name}}} -{{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setUsername('YOUR_USERNAME'); -{{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD');{{/isBasic}}{{#isApiKey}} +$config = {{{invokerPackage}}}\Configuration::getDefaultConfiguration() + ->setUsername('YOUR_USERNAME') + ->setPassword('YOUR_PASSWORD'); +{{/isBasic}}{{#isApiKey}} // Configure API key authorization: {{{name}}} -{{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKey('{{{keyParamName}}}', 'YOUR_API_KEY'); +$config = {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKey('{{{keyParamName}}}', 'YOUR_API_KEY'); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -// {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKeyPrefix('{{{keyParamName}}}', 'Bearer');{{/isApiKey}}{{#isOAuth}} +// $config = {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKeyPrefix('{{{keyParamName}}}', 'Bearer');{{/isApiKey}}{{#isOAuth}} // Configure OAuth2 access token for authorization: {{{name}}} -{{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');{{/isOAuth}}{{/authMethods}} +$config = {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} -$api_instance = new {{invokerPackage}}\Api\{{classname}}(new \Http\Adapter\Guzzle6\Client()); +$apiInstance = new {{invokerPackage}}\Api\{{classname}}( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(){{#hasAuthMethods}}, + $config{{/hasAuthMethods}} +); {{#allParams}}${{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}} {{/allParams}} try { - {{#returnType}}$result = {{/returnType}}$api_instance->{{{operationId}}}({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + {{#returnType}}$result = {{/returnType}}$apiInstance->{{{operationId}}}({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} print_r($result);{{/returnType}} } catch (Exception $e) { echo 'Exception when calling {{classname}}->{{operationId}}: ', $e->getMessage(), PHP_EOL; 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 a9b0f28edfb..f65b794638f 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 @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/python/__init__api.mustache b/modules/swagger-codegen/src/main/resources/python/__init__api.mustache index 989a5ea8382..db658a10fa8 100644 --- a/modules/swagger-codegen/src/main/resources/python/__init__api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/__init__api.mustache @@ -1,8 +1,7 @@ from __future__ import absolute_import +# flake8: noqa + # import apis into api package -{{#apiInfo}} -{{#apis}} -from .{{classVarName}} import {{classname}} -{{/apis}} -{{/apiInfo}} +{{#apiInfo}}{{#apis}}from {{apiPackage}}.{{classVarName}} import {{classname}} +{{/apis}}{{/apiInfo}} \ 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 1a9eaf62794..2266b3d17f4 100644 --- a/modules/swagger-codegen/src/main/resources/python/__init__model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/__init__model.mustache @@ -1,9 +1,10 @@ # coding: utf-8 +# flake8: noqa {{>partial_header}} from __future__ import absolute_import # import models into model package -{{#models}}{{#model}}from .{{classFilename}} import {{classname}}{{/model}} +{{#models}}{{#model}}from {{modelPackage}}.{{classFilename}} import {{classname}}{{/model}} {{/models}} 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 2289de872ef..cd42506f540 100644 --- a/modules/swagger-codegen/src/main/resources/python/__init__package.mustache +++ b/modules/swagger-codegen/src/main/resources/python/__init__package.mustache @@ -1,16 +1,17 @@ # coding: utf-8 +# flake8: noqa + {{>partial_header}} from __future__ import absolute_import -# import models into sdk package -{{#models}}{{#model}}from .models.{{classFilename}} import {{classname}} -{{/model}}{{/models}} # import apis into sdk package -{{#apiInfo}}{{#apis}}from .apis.{{classVarName}} import {{classname}} +{{#apiInfo}}{{#apis}}from {{apiPackage}}.{{classVarName}} import {{classname}} {{/apis}}{{/apiInfo}} # import ApiClient -from .api_client import ApiClient - -from .configuration import Configuration +from {{packageName}}.api_client import ApiClient +from {{packageName}}.configuration import Configuration +# import models into sdk package +{{#models}}{{#model}}from {{modelPackage}}.{{classFilename}} import {{classname}} +{{/model}}{{/models}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 354bb6fd66b..a65946f578d 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -4,20 +4,18 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from {{packageName}}.api_client import ApiClient {{#operations}} class {{classname}}(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -28,13 +26,11 @@ class {{classname}}(object): self.api_client = api_client {{#operation}} - def {{operationId}}(self, {{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs): - """ -{{#summary}} - {{{summary}}} -{{/summary}} + def {{operationId}}(self, {{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs): # noqa: E501 + """{{#summary}}{{.}}{{/summary}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501 + {{#notes}} - {{{notes}}} + {{{notes}}} # noqa: E501 {{/notes}} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True @@ -56,18 +52,16 @@ class {{classname}}(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.{{operationId}}_with_http_info({{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs) + return self.{{operationId}}_with_http_info({{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs) # noqa: E501 else: - (data) = self.{{operationId}}_with_http_info({{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs) + (data) = self.{{operationId}}_with_http_info({{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs) # noqa: E501 return data - def {{operationId}}_with_http_info(self, {{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs): - """ -{{#summary}} - {{{summary}}} -{{/summary}} + def {{operationId}}_with_http_info(self, {{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs): # noqa: E501 + """{{#summary}}{{.}}{{/summary}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501 + {{#notes}} - {{{notes}}} + {{{notes}}} # noqa: E501 {{/notes}} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True @@ -88,14 +82,14 @@ class {{classname}}(object): returns the request thread. """ - all_params = [{{#allParams}}'{{paramName}}'{{#hasMore}}, {{/hasMore}}{{/allParams}}] + all_params = [{{#allParams}}'{{paramName}}'{{#hasMore}}, {{/hasMore}}{{/allParams}}] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -106,44 +100,48 @@ class {{classname}}(object): {{#allParams}} {{#required}} # verify the required parameter '{{paramName}}' is set - if ('{{paramName}}' not in params) or (params['{{paramName}}'] is None): - raise ValueError("Missing the required parameter `{{paramName}}` when calling `{{operationId}}`") + if ('{{paramName}}' not in params or + params['{{paramName}}'] is None): + raise ValueError("Missing the required parameter `{{paramName}}` when calling `{{operationId}}`") # noqa: E501 {{/required}} {{/allParams}} {{#allParams}} {{#hasValidation}} {{#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}}`") + 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}}`") # noqa: E501 {{/maxLength}} {{#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}}`") + 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}}`") # noqa: E501 {{/minLength}} {{#maximum}} - if '{{paramName}}' in params and params['{{paramName}}'] >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}: - raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value less than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}`{{maximum}}`") + if '{{paramName}}' in params and params['{{paramName}}'] >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}: # noqa: E501 + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value less than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}`{{maximum}}`") # noqa: E501 {{/maximum}} {{#minimum}} - if '{{paramName}}' in params and params['{{paramName}}'] <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}: - raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}`{{minimum}}`") + if '{{paramName}}' in params and params['{{paramName}}'] <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}: # noqa: E501 + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}`{{minimum}}`") # noqa: E501 {{/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}}): - raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must conform to the pattern `{{{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}}): # noqa: E501 + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must conform to the pattern `{{{pattern}}}`") # noqa: E501 {{/pattern}} {{#maxItems}} - if '{{paramName}}' in params and len(params['{{paramName}}']) > {{maxItems}}: - raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, number of items must be less than or equal to `{{maxItems}}`") + if ('{{paramName}}' in params and + len(params['{{paramName}}']) > {{maxItems}}): + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, number of items must be less than or equal to `{{maxItems}}`") # noqa: E501 {{/maxItems}} {{#minItems}} - if '{{paramName}}' in params and len(params['{{paramName}}']) < {{minItems}}: - raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, number of items must be greater than or equal to `{{minItems}}`") + if ('{{paramName}}' in params and + len(params['{{paramName}}']) < {{minItems}}): + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, number of items must be greater than or equal to `{{minItems}}`") # noqa: E501 {{/minItems}} {{/hasValidation}} {{#-last}} - {{/-last}} {{/allParams}} collection_formats = {} @@ -151,30 +149,30 @@ class {{classname}}(object): path_params = {} {{#pathParams}} if '{{paramName}}' in params: - path_params['{{baseName}}'] = params['{{paramName}}']{{#isListContainer}} - collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isListContainer}} + path_params['{{baseName}}'] = params['{{paramName}}']{{#isListContainer}} # noqa: E501 + collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isListContainer}} # noqa: E501 {{/pathParams}} query_params = [] {{#queryParams}} if '{{paramName}}' in params: - query_params.append(('{{baseName}}', params['{{paramName}}'])){{#isListContainer}} - collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isListContainer}} + query_params.append(('{{baseName}}', params['{{paramName}}'])){{#isListContainer}} # noqa: E501 + collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isListContainer}} # noqa: E501 {{/queryParams}} header_params = {} {{#headerParams}} if '{{paramName}}' in params: - header_params['{{baseName}}'] = params['{{paramName}}']{{#isListContainer}} - collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isListContainer}} + header_params['{{baseName}}'] = params['{{paramName}}']{{#isListContainer}} # noqa: E501 + collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isListContainer}} # noqa: E501 {{/headerParams}} form_params = [] local_var_files = {} {{#formParams}} if '{{paramName}}' in params: - {{#notFile}}form_params.append(('{{baseName}}', params['{{paramName}}'])){{/notFile}}{{#isFile}}local_var_files['{{baseName}}'] = params['{{paramName}}']{{/isFile}}{{#isListContainer}} - collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isListContainer}} + {{#notFile}}form_params.append(('{{baseName}}', params['{{paramName}}'])){{/notFile}}{{#isFile}}local_var_files['{{baseName}}'] = params['{{paramName}}']{{/isFile}}{{#isListContainer}} # noqa: E501 + collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isListContainer}} # noqa: E501 {{/formParams}} body_params = None @@ -184,32 +182,33 @@ class {{classname}}(object): {{/bodyParam}} {{#hasProduces}} # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept([{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]) + header_params['Accept'] = self.api_client.select_header_accept( + [{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]) # noqa: E501 {{/hasProduces}} {{#hasConsumes}} # HTTP header `Content-Type` - 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( # noqa: E501 + [{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]) # noqa: E501 {{/hasConsumes}} # Authentication setting - auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] + auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] # noqa: E501 - return self.api_client.call_api('{{{path}}}', '{{httpMethod}}', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '{{{path}}}', '{{httpMethod}}', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) {{/operation}} {{/operations}} 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 5372dea0592..6a9a1c2744c 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -2,30 +2,28 @@ {{>partial_header}} from __future__ import absolute_import -import os -import re +import datetime import json import mimetypes +from multiprocessing.pool import ThreadPool +import os +import re import tempfile + +# python 2 and python 3 compatibility library +import six +from six.moves.urllib.parse import quote {{#tornado}} import tornado.gen {{/tornado}} -from multiprocessing.pool import ThreadPool -from datetime import date, datetime - -# python 2 and python 3 compatibility library -from six import PY3, integer_types, iteritems, text_type -from six.moves.urllib.parse import quote - -from . import models -from .configuration import Configuration -from .rest import ApiException, RESTClientObject +from {{packageName}}.configuration import Configuration +import {{modelPackage}} +from {{packageName}} import rest class ApiClient(object): - """ - Generic API client for Swagger client library builds. + """Generic API client for Swagger client library builds. Swagger generic API client. This client handles the client- server communication, and is invariant across implementations. Specifics of @@ -36,53 +34,52 @@ class ApiClient(object): Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. - :param host: The base path for the server to call. + :param configuration: .Configuration object for this client :param header_name: a header to pass when making calls to the API. - :param header_value: a header value to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API """ - PRIMITIVE_TYPES = (float, bool, bytes, text_type) + integer_types + PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types NATIVE_TYPES_MAPPING = { 'int': int, - 'long': int if PY3 else long, + 'long': int if six.PY3 else long, # noqa: F821 'float': float, 'str': str, 'bool': bool, - 'date': date, - 'datetime': datetime, + 'date': datetime.date, + 'datetime': datetime.datetime, 'object': object, } - def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None): + def __init__(self, configuration=None, header_name=None, header_value=None, + cookie=None): if configuration is None: configuration = Configuration() self.configuration = configuration self.pool = ThreadPool() - self.rest_client = RESTClientObject(configuration) + self.rest_client = rest.RESTClientObject(configuration) self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value self.cookie = cookie # Set default User-Agent. self.user_agent = '{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{packageVersion}}}/python{{/httpUserAgent}}' - + def __del__(self): self.pool.close() self.pool.join() @property def user_agent(self): - """ - Gets user agent. - """ + """User agent for this API client""" return self.default_headers['User-Agent'] @user_agent.setter def user_agent(self, value): - """ - Sets user agent. - """ self.default_headers['User-Agent'] = value def set_default_header(self, header_name, header_value): @@ -91,12 +88,12 @@ class ApiClient(object): {{#tornado}} @tornado.gen.coroutine {{/tornado}} - {{#asyncio}}async {{/asyncio}}def __call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_type=None, auth_settings=None, - _return_http_data_only=None, collection_formats=None, _preload_content=True, - _request_timeout=None): + {{#asyncio}}async {{/asyncio}}def __call_api( + self, resource_path, method, path_params=None, + query_params=None, header_params=None, body=None, post_params=None, + files=None, response_type=None, auth_settings=None, + _return_http_data_only=None, collection_formats=None, + _preload_content=True, _request_timeout=None): config = self.configuration @@ -118,7 +115,9 @@ class ApiClient(object): for k, v in path_params: # specified safe chars, encode everything resource_path = resource_path.replace( - '{%s}' % k, quote(str(v), safe=config.safe_chars_for_path_param)) + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) # query parameters if query_params: @@ -144,12 +143,11 @@ class ApiClient(object): url = self.configuration.host + resource_path # perform request and return response - response_data = {{#asyncio}}await {{/asyncio}}{{#tornado}}yield {{/tornado}}self.request(method, url, - query_params=query_params, - headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) + response_data = {{#asyncio}}await {{/asyncio}}{{#tornado}}yield {{/tornado}}self.request( + method, url, query_params=query_params, headers=header_params, + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout) self.last_response = response_data @@ -161,14 +159,23 @@ class ApiClient(object): else: return_data = None +{{^tornado}} if _return_http_data_only: return (return_data) else: - return (return_data, response_data.status, response_data.getheaders()) + return (return_data, response_data.status, + response_data.getheaders()) +{{/tornado}} +{{#tornado}} + if _return_http_data_only: + raise tornado.gen.Return(return_data) + else: + raise tornado.gen.Return((return_data, response_data.status, + response_data.getheaders())) +{{/tornado}} def sanitize_for_serialization(self, obj): - """ - Builds a JSON POST object. + """Builds a JSON POST object. If obj is None, return None. If obj is str, int, long, float, bool, return directly. @@ -191,7 +198,7 @@ class ApiClient(object): elif isinstance(obj, tuple): return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj) - elif isinstance(obj, (datetime, date)): + elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() if isinstance(obj, dict): @@ -203,15 +210,14 @@ class ApiClient(object): # Convert attribute name to json key in # model definition for request. obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in iteritems(obj.swagger_types) + for attr, _ in six.iteritems(obj.swagger_types) if getattr(obj, attr) is not None} return {key: self.sanitize_for_serialization(val) - for key, val in iteritems(obj_dict)} + for key, val in six.iteritems(obj_dict)} def deserialize(self, response, response_type): - """ - Deserializes response into an object. + """Deserializes response into an object. :param response: RESTResponse object to be deserialized. :param response_type: class literal for @@ -233,8 +239,7 @@ class ApiClient(object): return self.__deserialize(data, response_type) def __deserialize(self, data, klass): - """ - Deserializes dict, list, str into an object. + """Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. @@ -253,21 +258,21 @@ class ApiClient(object): if klass.startswith('dict('): sub_kls = re.match('dict\(([^,]*), (.*)\)', klass).group(2) return {k: self.__deserialize(v, sub_kls) - for k, v in iteritems(data)} + for k, v in six.iteritems(data)} # convert str to class if klass in self.NATIVE_TYPES_MAPPING: klass = self.NATIVE_TYPES_MAPPING[klass] else: - klass = getattr(models, klass) + klass = getattr({{modelPackage}}, klass) if klass in self.PRIMITIVE_TYPES: return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) - elif klass == date: + elif klass == datetime.date: return self.__deserialize_date(data) - elif klass == datetime: + elif klass == datetime.datetime: return self.__deserialize_datatime(data) else: return self.__deserialize_model(data, klass) @@ -276,10 +281,10 @@ class ApiClient(object): path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, async=None, - _return_http_data_only=None, collection_formats=None, _preload_content=True, - _request_timeout=None): - """ - Makes the HTTP request (synchronous) and return the deserialized data. + _return_http_data_only=None, collection_formats=None, + _preload_content=True, _request_timeout=None): + """Makes the HTTP request (synchronous) and returns deserialized data. + To make an async request, set the async parameter. :param resource_path: Path to method endpoint. @@ -296,13 +301,17 @@ class ApiClient(object): :param files dict: key -> filename, value -> filepath, for `multipart/form-data`. :param async bool: execute request asynchronously - :param _return_http_data_only: response data without head status code and headers + :param _return_http_data_only: response data without head status code + and headers :param collection_formats: dict of collection formats for path, query, header, and post parameters. - :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without - reading/decoding response data. Default is True. - :param _request_timeout: timeout setting for this request. If one number provided, it will be total request - timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: If async parameter is True, the request will be called asynchronously. @@ -315,22 +324,23 @@ class ApiClient(object): path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, - _return_http_data_only, collection_formats, _preload_content, _request_timeout) + _return_http_data_only, collection_formats, + _preload_content, _request_timeout) else: - thread = self.pool.apply_async(self.__call_api, (resource_path, method, - path_params, query_params, + thread = self.pool.apply_async(self.__call_api, (resource_path, + method, path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, _return_http_data_only, - collection_formats, _preload_content, _request_timeout)) + collection_formats, + _preload_content, _request_timeout)) return thread def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, _request_timeout=None): - """ - Makes the HTTP request using RESTClient. - """ + post_params=None, body=None, _preload_content=True, + _request_timeout=None): + """Makes the HTTP request using RESTClient.""" if method == "GET": return self.rest_client.GET(url, query_params=query_params, @@ -389,8 +399,7 @@ class ApiClient(object): ) def parameters_to_tuples(self, params, collection_formats): - """ - Get parameters as list of tuples, formatting collections. + """Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or list of two-tuples :param dict collection_formats: Parameter collection formats @@ -399,7 +408,7 @@ class ApiClient(object): new_params = [] if collection_formats is None: collection_formats = {} - for k, v in iteritems(params) if isinstance(params, dict) else params: + for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501 if k in collection_formats: collection_format = collection_formats[k] if collection_format == 'multi': @@ -420,8 +429,7 @@ class ApiClient(object): return new_params def prepare_post_parameters(self, post_params=None, files=None): - """ - Builds form parameters. + """Builds form parameters. :param post_params: Normal form parameters. :param files: File parameters. @@ -433,7 +441,7 @@ class ApiClient(object): params = post_params if files: - for k, v in iteritems(files): + for k, v in six.iteritems(files): if not v: continue file_names = v if type(v) is list else [v] @@ -441,15 +449,15 @@ class ApiClient(object): with open(n, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() - mimetype = mimetypes.\ - guess_type(filename)[0] or 'application/octet-stream' - params.append(tuple([k, tuple([filename, filedata, mimetype])])) + mimetype = (mimetypes.guess_type(filename)[0] or + 'application/octet-stream') + params.append( + tuple([k, tuple([filename, filedata, mimetype])])) return params def select_header_accept(self, accepts): - """ - Returns `Accept` based on an array of accepts provided. + """Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json). @@ -465,8 +473,7 @@ class ApiClient(object): return ', '.join(accepts) def select_header_content_type(self, content_types): - """ - Returns `Content-Type` based on an array of content_types provided. + """Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. :return: Content-Type (e.g. application/json). @@ -482,8 +489,7 @@ class ApiClient(object): return content_types[0] def update_params_for_auth(self, headers, querys, auth_settings): - """ - Updates header and query params based on authentication setting. + """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. :param querys: Query parameters tuple list to be updated. @@ -507,7 +513,8 @@ class ApiClient(object): ) def __deserialize_file(self, response): - """ + """Deserializes body to file + Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. @@ -520,19 +527,17 @@ class ApiClient(object): content_disposition = response.getheader("Content-Disposition") if content_disposition: - filename = re.\ - search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).\ - group(1) + filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition).group(1) path = os.path.join(os.path.dirname(path), filename) - with open(path, "w") as f: + with open(path, "wb") as f: f.write(response.data) return path def __deserialize_primitive(self, data, klass): - """ - Deserializes string to primitive type. + """Deserializes string to primitive type. :param data: str. :param klass: class literal. @@ -542,21 +547,19 @@ class ApiClient(object): try: return klass(data) except UnicodeEncodeError: - return unicode(data) + return six.u(data) except TypeError: return data def __deserialize_object(self, value): - """ - Return a original value. + """Return a original value. :return: object. """ return value def __deserialize_date(self, string): - """ - Deserializes string to date. + """Deserializes string to date. :param string: str. :return: date. @@ -567,14 +570,13 @@ class ApiClient(object): except ImportError: return string except ValueError: - raise ApiException( + raise rest.ApiException( status=0, - reason="Failed to parse `{0}` into a date object".format(string) + reason="Failed to parse `{0}` as date object".format(string) ) def __deserialize_datatime(self, string): - """ - Deserializes string to datetime. + """Deserializes string to datetime. The string should be in iso8601 datetime format. @@ -587,32 +589,32 @@ class ApiClient(object): except ImportError: return string except ValueError: - raise ApiException( + raise rest.ApiException( status=0, reason=( - "Failed to parse `{0}` into a datetime object" + "Failed to parse `{0}` as datetime object" .format(string) ) ) def __deserialize_model(self, data, klass): - """ - Deserializes list or dict to model. + """Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object. """ - if not klass.swagger_types and not hasattr(klass, 'get_real_child_model'): + if not klass.swagger_types and not hasattr(klass, + 'get_real_child_model'): return data kwargs = {} if klass.swagger_types is not None: - for attr, attr_type in iteritems(klass.swagger_types): - if data is not None \ - and klass.attribute_map[attr] in data \ - and isinstance(data, (list, dict)): + for attr, attr_type in six.iteritems(klass.swagger_types): + if (data is not None and + klass.attribute_map[attr] in data and + isinstance(data, (list, dict))): value = data[klass.attribute_map[attr]] kwargs[attr] = self.__deserialize(value, attr_type) 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 a496f63bfd1..32c26d929d1 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_doc.mustache @@ -17,7 +17,7 @@ Method | HTTP request | Description {{{notes}}}{{/notes}} -### Example +### Example ```python from __future__ import print_function import time @@ -51,7 +51,7 @@ api_instance = {{{packageName}}}.{{{classname}}}() {{/allParams}} {{/hasAuthMethods}} -try: +try: {{#summary}} # {{{.}}} {{/summary}} {{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}} pprint(api_response){{/returnType}} 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 f0f07f7189e..90fafc15f33 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_test.mustache @@ -4,30 +4,29 @@ from __future__ import absolute_import -import os -import sys import unittest import {{packageName}} +from {{apiPackage}}.{{classVarName}} import {{classname}} # noqa: E501 from {{packageName}}.rest import ApiException -from {{packageName}}.apis.{{classVarName}} import {{classname}} class {{#operations}}Test{{classname}}(unittest.TestCase): - """ {{classname}} unit test stubs """ + """{{classname}} unit test stubs""" def setUp(self): - self.api = {{packageName}}.apis.{{classVarName}}.{{classname}}() + self.api = {{apiPackage}}.{{classVarName}}.{{classname}}() # noqa: E501 def tearDown(self): pass {{#operation}} def test_{{operationId}}(self): - """ - Test case for {{{operationId}}} + """Test case for {{{operationId}}} - {{{summary}}} +{{#summary}} + {{{summary}}} # noqa: E501 +{{/summary}} """ pass diff --git a/modules/swagger-codegen/src/main/resources/python/asyncio/rest.mustache b/modules/swagger-codegen/src/main/resources/python/asyncio/rest.mustache index e0247056944..986902f56d0 100644 --- a/modules/swagger-codegen/src/main/resources/python/asyncio/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/asyncio/rest.mustache @@ -2,16 +2,15 @@ {{>partial_header}} -import aiohttp import io import json -import ssl -import certifi import logging import re +import ssl +import aiohttp +import certifi # python 2 and python 3 compatibility library -from six import PY3 from six.moves.urllib.parse import urlencode logger = logging.getLogger(__name__) @@ -26,22 +25,18 @@ class RESTResponse(io.IOBase): self.data = data def getheaders(self): - """ - Returns a CIMultiDictProxy of the response headers. - """ + """Returns a CIMultiDictProxy of the response headers.""" return self.aiohttp_response.headers def getheader(self, name, default=None): - """ - Returns a given response header. - """ + """Returns a given response header.""" return self.aiohttp_response.headers.get(name, default) -class RESTClientObject: +class RESTClientObject(object): def __init__(self, configuration, pools_size=4, maxsize=4): - # maxsize is the number of requests to host that are allowed in parallel + # maxsize is number of requests to host that are allowed in parallel # ca_certs vs cert_file vs key_file # http://stackoverflow.com/a/23957365/2985775 @@ -53,6 +48,7 @@ class RESTClientObject: ca_certs = certifi.where() ssl_context = ssl.SSLContext() + ssl_context.load_verify_locations(cafile=ca_certs) if configuration.cert_file: ssl_context.load_cert_chain( configuration.cert_file, keyfile=configuration.key_file @@ -60,6 +56,7 @@ class RESTClientObject: connector = aiohttp.TCPConnector( limit=maxsize, + ssl_context=ssl_context, verify_ssl=configuration.verify_ssl ) @@ -75,8 +72,10 @@ class RESTClientObject: ) async def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, _request_timeout=None): - """ + body=None, post_params=None, _preload_content=True, + _request_timeout=None): + """Execute request + :param method: http request method :param url: http request url :param query_params: query parameters in the url @@ -85,12 +84,16 @@ class RESTClientObject: :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` - :param _preload_content: this is a non-applicable field for the AiohttpClient. - :param _request_timeout: timeout setting for this request. If one number provided, it will be total request - timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :param _preload_content: this is a non-applicable field for + the AiohttpClient. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', + 'PATCH', 'OPTIONS'] if post_params and body: raise ValueError( @@ -118,7 +121,7 @@ class RESTClientObject: if body is not None: body = json.dumps(body) args["data"] = body - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 data = aiohttp.FormData() for k, v in post_params.items(): data.add_field(k, v) @@ -132,8 +135,9 @@ class RESTClientObject: args["data"] = body else: # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided arguments. - Please check that your arguments match declared content type.""" + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" raise ApiException(status=0, reason=msg) else: args["data"] = query_params @@ -150,22 +154,25 @@ class RESTClientObject: return r - async def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): + async def GET(self, url, headers=None, query_params=None, + _preload_content=True, _request_timeout=None): return (await self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params)) + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params)) - async def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): + async def HEAD(self, url, headers=None, query_params=None, + _preload_content=True, _request_timeout=None): return (await self.request("HEAD", url, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout, query_params=query_params)) - async def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + async def OPTIONS(self, url, headers=None, query_params=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): return (await self.request("OPTIONS", url, headers=headers, query_params=query_params, @@ -174,7 +181,8 @@ class RESTClientObject: _request_timeout=_request_timeout, body=body)) - async def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None): + async def DELETE(self, url, headers=None, query_params=None, body=None, + _preload_content=True, _request_timeout=None): return (await self.request("DELETE", url, headers=headers, query_params=query_params, @@ -182,8 +190,9 @@ class RESTClientObject: _request_timeout=_request_timeout, body=body)) - async def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + async def POST(self, url, headers=None, query_params=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): return (await self.request("POST", url, headers=headers, query_params=query_params, @@ -192,8 +201,8 @@ class RESTClientObject: _request_timeout=_request_timeout, body=body)) - async def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + async def PUT(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): return (await self.request("PUT", url, headers=headers, query_params=query_params, @@ -202,8 +211,9 @@ class RESTClientObject: _request_timeout=_request_timeout, body=body)) - async def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + async def PATCH(self, url, headers=None, query_params=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): return (await self.request("PATCH", url, headers=headers, query_params=query_params, @@ -228,13 +238,11 @@ class ApiException(Exception): self.headers = None def __str__(self): - """ - Custom error messages for exception - """ - error_message = "({0})\n"\ - "Reason: {1}\n".format(self.status, self.reason) + """Custom error messages for exception""" + error_message = "({0})\nReason: {1}\n".format(self.status, self.reason) if self.headers: - error_message += "HTTP response headers: {0}\n".format(self.headers) + error_message += "HTTP response headers: {0}\n".format( + self.headers) if self.body: error_message += "HTTP response body: {0}\n".format(self.body) diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index 744b277455a..84e6ad4d208 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -4,24 +4,23 @@ from __future__ import absolute_import -import urllib3 - import copy import logging import multiprocessing import sys +import urllib3 -from six import iteritems -from six import with_metaclass +import six from six.moves import http_client as httplib + class TypeWithDefault(type): def __init__(cls, name, bases, dct): super(TypeWithDefault, cls).__init__(name, bases, dct) cls._default = None def __call__(cls): - if cls._default == None: + if cls._default is None: cls._default = type.__call__(cls) return copy.copy(cls._default) @@ -29,17 +28,15 @@ class TypeWithDefault(type): cls._default = copy.copy(default) -class Configuration(with_metaclass(TypeWithDefault, object)): - """ - NOTE: This class is auto generated by the swagger code generator program. +class Configuration(six.with_metaclass(TypeWithDefault, object)): + """NOTE: This class is auto generated by the swagger code generator program. + Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. """ def __init__(self): - """ - Constructor - """ + """Constructor""" # Default Base url self.host = "{{{basePath}}}" # Temp file folder for downloading files @@ -74,7 +71,8 @@ class Configuration(with_metaclass(TypeWithDefault, object)): self.debug = False # SSL/TLS verification - # Set this to false to skip verifying SSL certificate when calling API from https server. + # Set this to false to skip verifying SSL certificate when calling API + # from https server. self.verify_ssl = True # Set this to customize the certificate file to verify the peer. self.ssl_ca_cert = None @@ -92,7 +90,6 @@ class Configuration(with_metaclass(TypeWithDefault, object)): # cpu_count * 5 is used as default value to increase performance. self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - # Proxy URL self.proxy = None # Safe chars for path_param @@ -100,18 +97,22 @@ class Configuration(with_metaclass(TypeWithDefault, object)): @property def logger_file(self): - """ - Gets the logger_file. + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str """ return self.__logger_file @logger_file.setter def logger_file(self, value): - """ - Sets the logger_file. + """The logger file. - If the logger_file is None, then add stream handler and remove file handler. - Otherwise, add file handler and remove stream handler. + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. :param value: The logger_file path. :type: str @@ -122,7 +123,7 @@ class Configuration(with_metaclass(TypeWithDefault, object)): # then add file handler and remove stream handler. self.logger_file_handler = logging.FileHandler(self.__logger_file) self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.addHandler(self.logger_file_handler) if self.logger_stream_handler: logger.removeHandler(self.logger_stream_handler) @@ -131,22 +132,23 @@ class Configuration(with_metaclass(TypeWithDefault, object)): # then add stream handler and remove file handler. self.logger_stream_handler = logging.StreamHandler() self.logger_stream_handler.setFormatter(self.logger_formatter) - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.addHandler(self.logger_stream_handler) if self.logger_file_handler: logger.removeHandler(self.logger_file_handler) @property def debug(self): - """ - Gets the debug status. + """Debug status + + :param value: The debug status, True or False. + :type: bool """ return self.__debug @debug.setter def debug(self, value): - """ - Sets the debug status. + """Debug status :param value: The debug status, True or False. :type: bool @@ -154,29 +156,32 @@ class Configuration(with_metaclass(TypeWithDefault, object)): self.__debug = value if self.__debug: # if debug status is True, turn on debug logging - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.setLevel(logging.DEBUG) # turn on httplib debug httplib.HTTPConnection.debuglevel = 1 else: # if debug status is False, turn off debug logging, # setting log level to default `logging.WARNING` - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.setLevel(logging.WARNING) # turn off httplib debug httplib.HTTPConnection.debuglevel = 0 @property def logger_format(self): - """ - Gets the logger_format. + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str """ return self.__logger_format @logger_format.setter def logger_format(self, value): - """ - Sets the logger_format. + """The logger format. The logger_formatter will be updated when sets logger_format. @@ -187,29 +192,28 @@ class Configuration(with_metaclass(TypeWithDefault, object)): self.logger_formatter = logging.Formatter(self.__logger_format) def get_api_key_with_prefix(self, identifier): - """ - Gets API key (with prefix if set). + """Gets API key (with prefix if set). :param identifier: The identifier of apiKey. :return: The token for api key authentication. """ - if self.api_key.get(identifier) and self.api_key_prefix.get(identifier): - return self.api_key_prefix[identifier] + ' ' + self.api_key[identifier] + if (self.api_key.get(identifier) and + self.api_key_prefix.get(identifier)): + return self.api_key_prefix[identifier] + ' ' + self.api_key[identifier] # noqa: E501 elif self.api_key.get(identifier): return self.api_key[identifier] def get_basic_auth_token(self): - """ - Gets HTTP basic authentication header (string). + """Gets HTTP basic authentication header (string). :return: The token for basic HTTP authentication. """ - return urllib3.util.make_headers(basic_auth=self.username + ':' + self.password)\ - .get('authorization') + return urllib3.util.make_headers( + basic_auth=self.username + ':' + self.password + ).get('authorization') def auth_settings(self): - """ - Gets Auth Settings dict for api client. + """Gets Auth Settings dict for api client. :return: The Auth Settings information dict. """ @@ -244,8 +248,7 @@ class Configuration(with_metaclass(TypeWithDefault, object)): } def to_debug_report(self): - """ - Gets the essential information for debugging. + """Gets the essential information for debugging. :return: The report for debugging. """ diff --git a/modules/swagger-codegen/src/main/resources/python/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/python/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/python/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/python/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 04b2dde376f..5668793b3f6 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -2,27 +2,31 @@ {{>partial_header}} +import pprint +import re # noqa: F401 + +import six +{{#imports}}{{#-first}} +{{/-first}} +{{import}} # noqa: F401,E501 +{{/imports}} + + {{#models}} {{#model}} -from pprint import pformat -from six import iteritems -import re - - class {{classname}}(object): - """ - 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. + """{{#allowableValues}} -{{#allowableValues}} """ allowed enum values """ {{#enumVars}} - {{name}} = {{{value}}} -{{/enumVars}} -{{/allowableValues}} + {{name}} = {{{value}}}{{^-last}} +{{/-last}} +{{/enumVars}}{{/allowableValues}} """ Attributes: @@ -32,96 +36,96 @@ class {{classname}}(object): and the value is json key in definition. """ swagger_types = { - {{#vars}}'{{name}}': '{{{datatype}}}'{{#hasMore}}, - {{/hasMore}}{{/vars}} +{{#vars}} + '{{name}}': '{{{datatype}}}'{{#hasMore}},{{/hasMore}} +{{/vars}} } attribute_map = { - {{#vars}}'{{name}}': '{{baseName}}'{{#hasMore}}, - {{/hasMore}}{{/vars}} +{{#vars}} + '{{name}}': '{{baseName}}'{{#hasMore}},{{/hasMore}} +{{/vars}} } {{#discriminator}} discriminator_value_class_map = { - {{#children}}'{{vendorExtensions.x-discriminator-value}}': '{{{classname}}}'{{^-last}}, + {{#children}}'{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}': '{{{classname}}}'{{^-last}}, {{/-last}}{{/children}} } {{/discriminator}} - def __init__(self{{#vars}}, {{name}}={{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{/vars}}): - """ - {{classname}} - a model defined in Swagger - """ - -{{#vars}} + def __init__(self{{#vars}}, {{name}}={{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{/vars}}): # noqa: E501 + """{{classname}} - a model defined in Swagger""" # noqa: E501 +{{#vars}}{{#-first}} +{{/-first}} self._{{name}} = None {{/vars}} self.discriminator = {{#discriminator}}'{{discriminator}}'{{/discriminator}}{{^discriminator}}None{{/discriminator}} - -{{#vars}} +{{#vars}}{{#-first}} +{{/-first}} {{#required}} self.{{name}} = {{name}} {{/required}} {{^required}} if {{name}} is not None: - self.{{name}} = {{name}} + self.{{name}} = {{name}} {{/required}} {{/vars}} {{#vars}} @property def {{name}}(self): - """ - Gets the {{name}} of this {{classname}}. + """Gets the {{name}} of this {{classname}}. # noqa: E501 + {{#description}} - {{{description}}} + {{{description}}} # noqa: E501 {{/description}} - :return: The {{name}} of this {{classname}}. + :return: The {{name}} of this {{classname}}. # noqa: E501 :rtype: {{datatype}} """ return self._{{name}} @{{name}}.setter def {{name}}(self, {{name}}): - """ - Sets the {{name}} of this {{classname}}. + """Sets the {{name}} of this {{classname}}. + {{#description}} - {{{description}}} + {{{description}}} # noqa: E501 {{/description}} - :param {{name}}: The {{name}} of this {{classname}}. + :param {{name}}: The {{name}} of this {{classname}}. # noqa: E501 :type: {{datatype}} """ {{#required}} if {{name}} is None: - raise ValueError("Invalid value for `{{name}}`, must not be `None`") + raise ValueError("Invalid value for `{{name}}`, must not be `None`") # noqa: E501 {{/required}} {{#isEnum}} {{#isContainer}} - allowed_values = [{{#allowableValues}}{{#values}}{{#items.isString}}"{{/items.isString}}{{{this}}}{{#items.isString}}"{{/items.isString}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] + allowed_values = [{{#allowableValues}}{{#values}}{{#items.isString}}"{{/items.isString}}{{{this}}}{{#items.isString}}"{{/items.isString}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] # noqa: E501 {{#isListContainer}} if not set({{{name}}}).issubset(set(allowed_values)): raise ValueError( - "Invalid values for `{{{name}}}` [{0}], must be a subset of [{1}]" - .format(", ".join(map(str, set({{{name}}})-set(allowed_values))), + "Invalid values for `{{{name}}}` [{0}], must be a subset of [{1}]" # noqa: E501 + .format(", ".join(map(str, set({{{name}}}) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) {{/isListContainer}} {{#isMapContainer}} if not set({{{name}}}.keys()).issubset(set(allowed_values)): raise ValueError( - "Invalid keys in `{{{name}}}` [{0}], must be a subset of [{1}]" - .format(", ".join(map(str, set({{{name}}}.keys())-set(allowed_values))), + "Invalid keys in `{{{name}}}` [{0}], must be a subset of [{1}]" # noqa: E501 + .format(", ".join(map(str, set({{{name}}}.keys()) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) {{/isMapContainer}} {{/isContainer}} {{^isContainer}} - allowed_values = [{{#allowableValues}}{{#values}}{{#isString}}"{{/isString}}{{{this}}}{{#isString}}"{{/isString}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] + allowed_values = [{{#allowableValues}}{{#values}}{{#isString}}"{{/isString}}{{{this}}}{{#isString}}"{{/isString}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] # noqa: E501 if {{{name}}} not in allowed_values: raise ValueError( - "Invalid value for `{{{name}}}` ({0}), must be one of {1}" + "Invalid value for `{{{name}}}` ({0}), must be one of {1}" # noqa: E501 .format({{{name}}}, allowed_values) ) {{/isContainer}} @@ -130,31 +134,31 @@ class {{classname}}(object): {{#hasValidation}} {{#maxLength}} if {{name}} is not None and len({{name}}) > {{maxLength}}: - raise ValueError("Invalid value for `{{name}}`, length must be less than or equal to `{{maxLength}}`") + raise ValueError("Invalid value for `{{name}}`, length must be less than or equal to `{{maxLength}}`") # noqa: E501 {{/maxLength}} {{#minLength}} if {{name}} is not None and len({{name}}) < {{minLength}}: - raise ValueError("Invalid value for `{{name}}`, length must be greater than or equal to `{{minLength}}`") + raise ValueError("Invalid value for `{{name}}`, length must be greater than or equal to `{{minLength}}`") # noqa: E501 {{/minLength}} {{#maximum}} - if {{name}} is not None and {{name}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}: - raise ValueError("Invalid value for `{{name}}`, must be a value less than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}`{{maximum}}`") + if {{name}} is not None and {{name}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}: # noqa: E501 + raise ValueError("Invalid value for `{{name}}`, must be a value less than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}`{{maximum}}`") # noqa: E501 {{/maximum}} {{#minimum}} - if {{name}} is not None and {{name}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}: - raise ValueError("Invalid value for `{{name}}`, must be a value greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}`{{minimum}}`") + if {{name}} is not None and {{name}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}: # noqa: E501 + raise ValueError("Invalid value for `{{name}}`, must be a value greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}`{{minimum}}`") # noqa: E501 {{/minimum}} {{#pattern}} - if {{name}} is not None and 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}}}`") + if {{name}} is not None and not re.search('{{{vendorExtensions.x-regex}}}', {{name}}{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): # noqa: E501 + raise ValueError("Invalid value for `{{name}}`, must be a follow pattern or equal to `{{{pattern}}}`") # noqa: E501 {{/pattern}} {{#maxItems}} if {{name}} is not None and len({{name}}) > {{maxItems}}: - raise ValueError("Invalid value for `{{name}}`, number of items must be less than or equal to `{{maxItems}}`") + raise ValueError("Invalid value for `{{name}}`, number of items must be less than or equal to `{{maxItems}}`") # noqa: E501 {{/maxItems}} {{#minItems}} if {{name}} is not None and len({{name}}) < {{minItems}}: - raise ValueError("Invalid value for `{{name}}`, number of items must be greater than or equal to `{{minItems}}`") + raise ValueError("Invalid value for `{{name}}`, number of items must be greater than or equal to `{{minItems}}`") # noqa: E501 {{/minItems}} {{/hasValidation}} {{/isEnum}} @@ -164,23 +168,16 @@ class {{classname}}(object): {{/vars}} {{#discriminator}} def get_real_child_model(self, data): - """ - Returns the real base class specified by the discriminator - """ + """Returns the real base class specified by the discriminator""" discriminator_value = data[self.discriminator].lower() - if self.discriminator_value_class_map.has_key(discriminator_value): - return self.discriminator_value_class_map[discriminator_value] - else: - return None + return self.discriminator_value_class_map.get(discriminator_value) {{/discriminator}} def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -201,30 +198,22 @@ class {{classname}}(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, {{classname}}): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other {{/model}} {{/models}} 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 5f1b116b776..765e4f9c2c0 100644 --- a/modules/swagger-codegen/src/main/resources/python/model_test.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model_test.mustache @@ -4,19 +4,17 @@ from __future__ import absolute_import -import os -import sys import unittest {{#models}} {{#model}} import {{packageName}} +from {{modelPackage}}.{{classFilename}} import {{classname}} # noqa: E501 from {{packageName}}.rest import ApiException -from {{packageName}}.models.{{classFilename}} import {{classname}} class Test{{classname}}(unittest.TestCase): - """ {{classname}} unit test stubs """ + """{{classname}} unit test stubs""" def setUp(self): pass @@ -25,11 +23,9 @@ class Test{{classname}}(unittest.TestCase): pass def test{{classname}}(self): - """ - Test {{classname}} - """ + """Test {{classname}}""" # FIXME: construct object with mandatory attributes with example values - #model = {{packageName}}.models.{{classFilename}}.{{classname}}() + # model = {{packageName}}.models.{{classFilename}}.{{classname}}() # noqa: E501 pass {{/model}} diff --git a/modules/swagger-codegen/src/main/resources/python/partial_header.mustache b/modules/swagger-codegen/src/main/resources/python/partial_header.mustache index b0c8ebed3ca..513ad04cdbd 100644 --- a/modules/swagger-codegen/src/main/resources/python/partial_header.mustache +++ b/modules/swagger-codegen/src/main/resources/python/partial_header.mustache @@ -4,7 +4,7 @@ {{/appName}} {{#appDescription}} - {{{appDescription}}} + {{{appDescription}}} # noqa: E501 {{/appDescription}} {{#version}}OpenAPI spec version: {{{version}}}{{/version}} diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index aa92c7eba73..ff9b019dc58 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -6,13 +6,13 @@ from __future__ import absolute_import import io import json -import ssl -import certifi import logging import re +import ssl +import certifi # python 2 and python 3 compatibility library -from six import PY3 +import six from six.moves.urllib.parse import urlencode try: @@ -33,15 +33,11 @@ class RESTResponse(io.IOBase): self.data = resp.data def getheaders(self): - """ - Returns a dictionary of the response headers. - """ + """Returns a dictionary of the response headers.""" return self.urllib3_response.getheaders() def getheader(self, name, default=None): - """ - Returns a given response header. - """ + """Returns a given response header.""" return self.urllib3_response.getheader(name, default) @@ -49,10 +45,10 @@ class RESTClientObject(object): def __init__(self, configuration, pools_size=4, maxsize=None): # urllib3.PoolManager will pass all kw parameters to connectionpool - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 - # maxsize is the number of requests to host that are allowed in parallel - # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 # cert_reqs if configuration.verify_ssl: @@ -69,7 +65,7 @@ class RESTClientObject(object): addition_pool_args = {} if configuration.assert_hostname is not None: - addition_pool_args['assert_hostname'] = configuration.assert_hostname + addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 if maxsize is None: if configuration.connection_pool_maxsize is not None: @@ -101,8 +97,10 @@ class RESTClientObject(object): ) def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, _request_timeout=None): - """ + body=None, post_params=None, _preload_content=True, + _request_timeout=None): + """Perform requests. + :param method: http request method :param url: http request url :param query_params: query parameters in the url @@ -111,13 +109,17 @@ class RESTClientObject(object): :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without - reading/decoding response data. Default is True. - :param _request_timeout: timeout setting for this request. If one number provided, it will be total request - timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', + 'PATCH', 'OPTIONS'] if post_params and body: raise ValueError( @@ -129,10 +131,12 @@ class RESTClientObject(object): timeout = None if _request_timeout: - if isinstance(_request_timeout, (int, ) if PY3 else (int, long)): + if isinstance(_request_timeout, (int, ) if six.PY3 else (int, long)): # noqa: E501,F821 timeout = urllib3.Timeout(total=_request_timeout) - elif isinstance(_request_timeout, tuple) and len(_request_timeout) == 2: - timeout = urllib3.Timeout(connect=_request_timeout[0], read=_request_timeout[1]) + elif (isinstance(_request_timeout, tuple) and + len(_request_timeout) == 2): + timeout = urllib3.Timeout( + connect=_request_timeout[0], read=_request_timeout[1]) if 'Content-Type' not in headers: headers['Content-Type'] = 'application/json' @@ -146,42 +150,48 @@ class RESTClientObject(object): request_body = None if body is not None: request_body = json.dumps(body) - r = self.pool_manager.request(method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': - r = self.pool_manager.request(method, url, - fields=post_params, - encode_multipart=False, - preload_content=_preload_content, - timeout=timeout, - headers=headers) + r = self.pool_manager.request( + method, url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + r = self.pool_manager.request( + method, url, + fields=post_params, + encode_multipart=False, + preload_content=_preload_content, + timeout=timeout, + headers=headers) elif headers['Content-Type'] == 'multipart/form-data': - # must del headers['Content-Type'], or the correct Content-Type - # which generated by urllib3 will be overwritten. + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. del headers['Content-Type'] - r = self.pool_manager.request(method, url, - fields=post_params, - encode_multipart=True, - preload_content=_preload_content, - timeout=timeout, - headers=headers) + r = self.pool_manager.request( + method, url, + fields=post_params, + encode_multipart=True, + preload_content=_preload_content, + timeout=timeout, + headers=headers) # Pass a `string` parameter directly in the body to support - # other content types than Json when `body` argument is provided - # in serialized form + # other content types than Json when `body` argument is + # provided in serialized form elif isinstance(body, str): request_body = body - r = self.pool_manager.request(method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) + r = self.pool_manager.request( + method, url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers) else: # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided arguments. - Please check that your arguments match declared content type.""" + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: @@ -199,7 +209,7 @@ class RESTClientObject(object): # In the python 3, the response.data is bytes. # we need to decode it to string. - if PY3: + if six.PY3: r.data = r.data.decode('utf8') # log response body @@ -210,22 +220,24 @@ class RESTClientObject(object): return r - def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): + def GET(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): return self.request("GET", url, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout, query_params=query_params) - def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): + def HEAD(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): return self.request("HEAD", url, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout, query_params=query_params) - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): return self.request("OPTIONS", url, headers=headers, query_params=query_params, @@ -234,7 +246,8 @@ class RESTClientObject(object): _request_timeout=_request_timeout, body=body) - def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None): + def DELETE(self, url, headers=None, query_params=None, body=None, + _preload_content=True, _request_timeout=None): return self.request("DELETE", url, headers=headers, query_params=query_params, @@ -242,8 +255,8 @@ class RESTClientObject(object): _request_timeout=_request_timeout, body=body) - def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def POST(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): return self.request("POST", url, headers=headers, query_params=query_params, @@ -252,8 +265,8 @@ class RESTClientObject(object): _request_timeout=_request_timeout, body=body) - def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def PUT(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): return self.request("PUT", url, headers=headers, query_params=query_params, @@ -262,8 +275,8 @@ class RESTClientObject(object): _request_timeout=_request_timeout, body=body) - def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def PATCH(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): return self.request("PATCH", url, headers=headers, query_params=query_params, @@ -288,13 +301,12 @@ class ApiException(Exception): self.headers = None def __str__(self): - """ - Custom error messages for exception - """ + """Custom error messages for exception""" error_message = "({0})\n"\ "Reason: {1}\n".format(self.status, self.reason) if self.headers: - error_message += "HTTP response headers: {0}\n".format(self.headers) + error_message += "HTTP response headers: {0}\n".format( + self.headers) if self.body: error_message += "HTTP response body: {0}\n".format(self.body) diff --git a/modules/swagger-codegen/src/main/resources/python/setup.mustache b/modules/swagger-codegen/src/main/resources/python/setup.mustache index 4fe9e64b889..e7107e9be94 100644 --- a/modules/swagger-codegen/src/main/resources/python/setup.mustache +++ b/modules/swagger-codegen/src/main/resources/python/setup.mustache @@ -2,8 +2,7 @@ {{>partial_header}} -import sys -from setuptools import setup, find_packages +from setuptools import setup, find_packages # noqa: H301 NAME = "{{{projectName}}}" VERSION = "{{packageVersion}}" @@ -36,7 +35,7 @@ setup( packages=find_packages(), include_package_data=True, long_description="""\ - {{appDescription}} + {{appDescription}} # noqa: E501 """ ) {{/hasMore}} diff --git a/modules/swagger-codegen/src/main/resources/python/tornado/rest.mustache b/modules/swagger-codegen/src/main/resources/python/tornado/rest.mustache index 709edee07f3..805e9d4badd 100644 --- a/modules/swagger-codegen/src/main/resources/python/tornado/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/tornado/rest.mustache @@ -4,17 +4,17 @@ import io import json -import ssl -import certifi import logging import re +import ssl + +import certifi +# python 2 and python 3 compatibility library +import six +from six.moves.urllib.parse import urlencode import tornado import tornado.gen -from tornado.httpclient import AsyncHTTPClient, HTTPRequest - -# python 2 and python 3 compatibility library -from six import PY3 -from six.moves.urllib.parse import urlencode +from tornado import httpclient from urllib3.filepost import encode_multipart_formdata logger = logging.getLogger(__name__) @@ -29,22 +29,18 @@ class RESTResponse(io.IOBase): self.data = data def getheaders(self): - """ - Returns a CIMultiDictProxy of the response headers. - """ + """Returns a CIMultiDictProxy of the response headers.""" return self.tornado_response.headers def getheader(self, name, default=None): - """ - Returns a given response header. - """ + """Returns a given response header.""" return self.tornado_response.headers.get(name, default) -class RESTClientObject: +class RESTClientObject(object): def __init__(self, configuration, pools_size=4, maxsize=4): - # maxsize is the number of requests to host that are allowed in parallel + # maxsize is number of requests to host that are allowed in parallel # ca_certs vs cert_file vs key_file # http://stackoverflow.com/a/23957365/2985775 @@ -55,9 +51,10 @@ class RESTClientObject: # if not set certificate file, use Mozilla's root certificates. ca_certs = certifi.where() - self.ssl_context = ssl_context = ssl.SSLContext() + self.ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) + self.ssl_context.load_verify_locations(cafile=ca_certs) if configuration.cert_file: - ssl_context.load_cert_chain( + self.ssl_context.load_cert_chain( configuration.cert_file, keyfile=configuration.key_file ) @@ -68,12 +65,14 @@ class RESTClientObject: self.proxy_port = 80 self.proxy_host = configuration.proxy - self.pool_manager = AsyncHTTPClient() + self.pool_manager = httpclient.AsyncHTTPClient() @tornado.gen.coroutine - def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, _request_timeout=None): - """ + def request(self, method, url, query_params=None, headers=None, body=None, + post_params=None, _preload_content=True, + _request_timeout=None): + """Execute Request + :param method: http request method :param url: http request url :param query_params: query parameters in the url @@ -82,19 +81,23 @@ class RESTClientObject: :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` - :param _preload_content: this is a non-applicable field for the AiohttpClient. - :param _request_timeout: timeout setting for this request. If one number provided, it will be total request - timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :param _preload_content: this is a non-applicable field for + the AiohttpClient. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', + 'PATCH', 'OPTIONS'] if post_params and body: raise ValueError( "body parameter cannot be used with post_params parameter." ) - request = HTTPRequest(url) + request = httpclient.HTTPRequest(url) request.ssl_context = self.ssl_context request.proxy_host = self.proxy_host request.proxy_port = self.proxy_port @@ -105,7 +108,6 @@ class RESTClientObject: request.headers['Content-Type'] = 'application/json' request.request_timeout = _request_timeout or 5 * 60 - post_params = post_params or {} if query_params: @@ -117,11 +119,11 @@ class RESTClientObject: if body: body = json.dumps(body) request.body = body - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 request.body = urlencode(post_params) - # TODO: transform to multipart form elif headers['Content-Type'] == 'multipart/form-data': - request.body = encode_multipart_formdata(post_params) + multipart = encode_multipart_formdata(post_params) + request.body, headers['Content-Type'] = multipart # Pass a `bytes` parameter directly in the body to support # other content types than Json when `body` argument is provided # in serialized form @@ -129,53 +131,64 @@ class RESTClientObject: request.body = body else: # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided arguments. - Please check that your arguments match declared content type.""" + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" raise ApiException(status=0, reason=msg) - r = yield self.pool_manager.fetch(request) - r = RESTResponse(r, r.body) + r = yield self.pool_manager.fetch(request, raise_error=False) - # log response body - logger.debug("response body: %s", r.data) + if _preload_content: + + r = RESTResponse(r, r.body) + # In the python 3, the response.data is bytes. + # we need to decode it to string. + if six.PY3: + r.data = r.data.decode('utf8') + + # log response body + logger.debug("response body: %s", r.data) if not 200 <= r.status <= 299: raise ApiException(http_resp=r) - return r + raise tornado.gen.Return(r) @tornado.gen.coroutine - def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): + def GET(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): result = yield self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) raise tornado.gen.Return(result) @tornado.gen.coroutine - def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): + def HEAD(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): result = yield self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) raise tornado.gen.Return(result) @tornado.gen.coroutine - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): result = yield self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) raise tornado.gen.Return(result) @tornado.gen.coroutine - def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None): + def DELETE(self, url, headers=None, query_params=None, body=None, + _preload_content=True, _request_timeout=None): result = yield self.request("DELETE", url, headers=headers, query_params=query_params, @@ -185,39 +198,39 @@ class RESTClientObject: raise tornado.gen.Return(result) @tornado.gen.coroutine - def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def POST(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): result = yield self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) raise tornado.gen.Return(result) @tornado.gen.coroutine - def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def PUT(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): result = yield self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) raise tornado.gen.Return(result) @tornado.gen.coroutine - def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def PATCH(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): result = yield self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) raise tornado.gen.Return(result) @@ -236,13 +249,12 @@ class ApiException(Exception): self.headers = None def __str__(self): - """ - Custom error messages for exception - """ - error_message = "({0})\n"\ - "Reason: {1}\n".format(self.status, self.reason) + """Custom error messages for exception""" + error_message = "({0})\nReason: {1}\n".format( + self.status, self.reason) if self.headers: - error_message += "HTTP response headers: {0}\n".format(self.headers) + error_message += "HTTP response headers: {0}\n".format( + self.headers) if self.body: error_message += "HTTP response body: {0}\n".format(self.body) diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/model-body.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/model-body.mustache index 14c15270042..7fa52b6bde1 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/model-body.mustache @@ -58,11 +58,27 @@ void void {{classname}}::fromJsonObject(QJsonObject &pJson) { {{#vars}} - {{^isContainer}}::{{cppNamespace}}::setValue(&{{name}}, pJson["{{baseName}}"], "{{baseType}}", "{{complexType}}");{{/isContainer}} - {{#isContainer}} + {{^isContainer}}::{{cppNamespace}}::setValue(&{{name}}, pJson["{{baseName}}"], "{{baseType}}", "{{complexType}}");{{/isContainer}} + {{#isListContainer}} {{#complexType}}::{{cppNamespace}}::setValue(&{{name}}, pJson["{{baseName}}"], "{{baseType}}", "{{complexType}}");{{/complexType}} {{^complexType}}::{{cppNamespace}}::setValue(&{{name}}, pJson["{{baseName}}"], "{{baseType}}", "{{items.baseType}}");{{/complexType}} - {{/isContainer}} + {{/isListContainer}} + {{#isMapContainer}} + if( pJson["{{baseName}}"].isObject()){ + auto varmap = pJson["{{baseName}}"].toObject().toVariantMap(); + if(varmap.count() > 0){ + for(auto val : varmap.keys() ){ + { + {{items.baseType}} *{{name}}_item = new {{items.baseType}}(); + auto jsonval = QJsonValue::fromVariant(varmap[val]); + ::{{cppNamespace}}::setValue(&{{name}}_item, jsonval, "{{items.baseType}}", "{{items.baseType}}"); + {{name}}->insert({{name}}->end(), val, {{name}}_item); + } + } + } + } + + {{/isMapContainer}} {{/vars}} } @@ -83,14 +99,28 @@ QJsonObject* toJsonValue(QString("{{baseName}}"), {{name}}, obj, QString("{{complexType}}"));{{/complexType}}{{^complexType}} if({{name}} != nullptr && *{{name}} != nullptr) { obj->insert("{{name}}", QJsonValue(*{{name}})); - }{{/complexType}}{{/isContainer}}{{#isContainer}} + }{{/complexType}}{{/isContainer}}{{#isListContainer}} QJsonArray {{name}}JsonArray; toJsonArray((QList*){{name}}, &{{name}}JsonArray, "{{name}}", "{{complexType}}"); - obj->insert("{{baseName}}", {{name}}JsonArray);{{/isContainer}}{{/complexType}}{{^complexType}}{{^isContainer}} - obj->insert("{{baseName}}", QJsonValue({{name}}));{{/isContainer}}{{#isContainer}} + obj->insert("{{baseName}}", {{name}}JsonArray);{{/isListContainer}}{{#isMapContainer}} + QJsonArray {{name}}JsonArray; + for(auto keyval : {{name}}->keys()){ + QJsonObject {{name}}_jobj; + toJsonValue(keyval, ((*{{name}})[keyval]), &{{name}}_jobj, "{{complexType}}"); + {{name}}JsonArray.append({{name}}_jobj); + } + obj->insert("{{baseName}}", {{name}}JsonArray);{{/isMapContainer}}{{/complexType}}{{^complexType}}{{^isContainer}} + obj->insert("{{baseName}}", QJsonValue({{name}}));{{/isContainer}}{{#isListContainer}} QJsonArray {{name}}JsonArray; toJsonArray((QList*){{name}}, &{{name}}JsonArray, "{{name}}", "{{items.baseType}}"); - obj->insert("{{baseName}}", {{name}}JsonArray);{{/isContainer}}{{/complexType}} + obj->insert("{{baseName}}", {{name}}JsonArray);{{/isListContainer}}{{#isMapContainer}} + QJsonArray {{name}}JsonArray; + for(auto keyval : {{name}}->keys()){ + QJsonObject {{name}}_jobj; + toJsonValue(keyval, ((*{{name}})[keyval]), &{{name}}_jobj, "{{items.baseType}}"); + {{name}}JsonArray.append(portsobj); + } + obj->insert("{{baseName}}", {{name}}JsonArray);{{/isMapContainer}}{{/complexType}} {{/vars}} return obj; diff --git a/modules/swagger-codegen/src/main/resources/r/api.mustache b/modules/swagger-codegen/src/main/resources/r/api.mustache index eb64e29cdb2..c47ef969681 100644 --- a/modules/swagger-codegen/src/main/resources/r/api.mustache +++ b/modules/swagger-codegen/src/main/resources/r/api.mustache @@ -35,14 +35,15 @@ {{#operation}} {{operationId}} = function({{#allParams}}{{paramName}}, {{/allParams}}...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() + {{#hasHeaderParams}} {{#headerParams}} if (!missing(`{{paramName}}`)) { headerParams['{{baseName}}'] <- `{{paramName}}` } + {{/headerParams}} {{/hasHeaderParams}} {{#hasQueryParams}} @@ -50,6 +51,7 @@ if (!missing(`{{paramName}}`)) { queryParams['{{baseName}}'] <- {{paramName}} } + {{/queryParams}} {{/hasQueryParams}} {{#hasFormParams}} @@ -62,25 +64,28 @@ "{{baseName}}" = httr::upload_file({{paramName}}){{#hasMore}},{{/hasMore}} {{/isFile}} {{/formParams}} - ) + ) + {{/hasFormParams}} {{#hasBodyParam}} {{#bodyParams}} if (!missing(`{{paramName}}`)) { - body <- `{{paramName}}`$toJSON() + body <- `{{paramName}}`$toJSONString() + } else { + body <- NULL } + {{/bodyParams}} {{/hasBodyParam}} - urlPath <- "{{path}}" {{#hasPathParams}} {{#pathParams}} if (!missing(`{{paramName}}`)) { urlPath <- gsub(paste0("\\{", "{{baseName}}", "\\}"), `{{paramName}}`, urlPath) } + {{/pathParams}} {{/hasPathParams}} - resp <- self$apiClient$callApi(url = paste0(self$apiClient$basePath, urlPath), method = "{{httpMethod}}", queryParams = queryParams, diff --git a/modules/swagger-codegen/src/main/resources/r/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/r/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/r/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/r/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/r/model.mustache b/modules/swagger-codegen/src/main/resources/r/model.mustache index 9181c8e51e2..94ae74085e2 100644 --- a/modules/swagger-codegen/src/main/resources/r/model.mustache +++ b/modules/swagger-codegen/src/main/resources/r/model.mustache @@ -98,7 +98,7 @@ sprintf( '{ {{#vars}} - "{{baseName}}": {{#isListContainer}}[{{/isListContainer}}{{#isPrimitiveType}}{{#isNumeric}}%d{{/isNumeric}}{{^isNumeric}}"%s"{{/isNumeric}}{{/isPrimitiveType}}{{^isPrimitiveType}}%s{{/isPrimitiveType}}{{#isListContainer}}]{{/isListContainer}}{{#hasMore}},{{/hasMore}} + "{{baseName}}": {{#isListContainer}}[{{/isListContainer}}{{#isPrimitiveType}}{{#isNumeric}}%d{{/isNumeric}}{{^isNumeric}}%s{{/isNumeric}}{{/isPrimitiveType}}{{^isPrimitiveType}}%s{{/isPrimitiveType}}{{#isListContainer}}]{{/isListContainer}}{{#hasMore}},{{/hasMore}} {{/vars}} }', {{#vars}} diff --git a/modules/swagger-codegen/src/main/resources/restbed/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/restbed/git_push.sh.mustache index c7d7c390acf..c7a337655c3 100644 --- a/modules/swagger-codegen/src/main/resources/restbed/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/restbed/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/ruby/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/ruby/git_push.sh.mustache index 052b8991126..62855652e65 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 @@ -39,7 +39,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/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 index 34df546ac86..f2f366900ef 100644 --- 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 @@ -6,8 +6,8 @@ # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) - consantValues = {{classname}}.constants.select{|c| c.to_s == value} - raise "Invalid ENUM value #{value} for class #{{{classname}}}" if consantValues.empty? + constantValues = {{classname}}.constants.select{|c| {{classname}}::const_get(c) == value} + raise "Invalid ENUM value #{value} for class #{{{classname}}}" if constantValues.empty? value end 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 index 00a75b25396..d1882aa2641 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache @@ -56,11 +56,16 @@ {{#vars}} if attributes.has_key?(:'{{{baseName}}}') - {{#isContainer}} + {{#isListContainer}} if (value = attributes[:'{{{baseName}}}']).is_a?(Array) self.{{{name}}} = value end - {{/isContainer}} + {{/isListContainer}} + {{#isMapContainer}} + if (value = attributes[:'{{{baseName}}}']).is_a?(Hash) + self.{{{name}}} = value + end + {{/isMapContainer}} {{^isContainer}} self.{{{name}}} = attributes[:'{{{baseName}}}'] {{/isContainer}} diff --git a/modules/swagger-codegen/src/main/resources/rust-server/Cargo.mustache b/modules/swagger-codegen/src/main/resources/rust-server/Cargo.mustache new file mode 100644 index 00000000000..8cab22ff513 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust-server/Cargo.mustache @@ -0,0 +1,34 @@ +[package] +name = "{{packageName}}" +version = "{{appVersion}}" +authors = [{{#infoEmail}}"{{infoEmail}}"{{/infoEmail}}] + +[features] +default = ["client", "server"] +client = ["serde_json", {{#usesXml}}"serde-xml-rs", {{/usesXml}}"serde_ignored", "hyper", "hyper-openssl", "uuid"{{#apiHasFile}}, "multipart"{{/apiHasFile}}] +server = ["serde_json", {{#usesXml}}"serde-xml-rs", {{/usesXml}}"serde_ignored", "hyper", "iron", "router", "bodyparser", "urlencoded", "uuid"{{#apiHasFile}}, "multipart"{{/apiHasFile}}] + +[dependencies] +bodyparser = {version = "0.7", optional = true} +chrono = { version = "0.4", features = ["serde"] } +futures = "0.1" +hyper = {version = "0.10", optional = true} +hyper-openssl = {version = "0.2", optional = true } +iron = {version = "0.5", optional = true} +lazy_static = "0.2" +log = "0.3.0" +multipart = {version = "0.13", optional = true} +router = {version = "0.5", optional = true} +serde = "1.0" +serde_derive = "1.0" +serde_ignored = {version = "0.0.4", optional = true} +serde_json = {version = "1.0", optional = true} +swagger = "0.7" +urlencoded = {version = "0.5", optional = true} +uuid = {version = "0.5", optional = true, features = ["serde", "v4"]} +# ToDo: this should be updated to point at the official crate once +# https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream +{{#usesXml}}serde-xml-rs = {git = "git://github.com/Metaswitch/serde-xml-rs.git" , branch = "master", optional = true}{{/usesXml}} + +[dev-dependencies] +clap = "2.25" diff --git a/modules/swagger-codegen/src/main/resources/rust-server/README.mustache b/modules/swagger-codegen/src/main/resources/rust-server/README.mustache new file mode 100644 index 00000000000..c790d7d68b0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust-server/README.mustache @@ -0,0 +1,59 @@ +# Rust API for {{packageName}} + +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +## Overview +This client/server was generated by the [swagger-codegen] +(https://github.com/swagger-api/swagger-codegen) project. +By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. +- + +To see how to make this your own, look here: + +[README](https://github.com/swagger-api/swagger-codegen/blob/master/README.md) + +- API version: {{appVersion}} +- Build date: {{generatedDate}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Examples + +Run examples with: + +``` +cargo run --example +``` + +To pass in arguments to the examples, put them after `--`, for example: + +``` +cargo run --example client -- --help +``` + +### Running the server +To run the server, follow these simple steps: + +``` +cargo run --example server +``` + +### Running a client +To run a client, follow one of the following simple steps: + +```{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} +cargo run --example client {{operationId}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +``` + +### HTTPS +The examples can be run in HTTPS mode by passing in the flag `--https`, for example: + +``` +cargo run --example server -- --https +``` + +This will use the keys/certificates from the examples directory. Note that the server chain is signed with +`CN=localhost`. diff --git a/modules/swagger-codegen/src/main/resources/rust-server/cargo-config b/modules/swagger-codegen/src/main/resources/rust-server/cargo-config new file mode 100644 index 00000000000..b8acc9c00c8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust-server/cargo-config @@ -0,0 +1,18 @@ +[build] +rustflags = [ + "-W", "missing_docs", # detects missing documentation for public members + + "-W", "trivial_casts", # detects trivial casts which could be removed + + "-W", "trivial_numeric_casts", # detects trivial casts of numeric types which could be removed + + "-W", "unsafe_code", # usage of `unsafe` code + + "-W", "unused_qualifications", # detects unnecessarily qualified names + + "-W", "unused_extern_crates", # extern crates that are never used + + "-W", "unused_import_braces", # unnecessary braces around an imported item + + "-D", "warnings", # all warnings should be denied +] diff --git a/modules/swagger-codegen/src/main/resources/rust-server/client.mustache b/modules/swagger-codegen/src/main/resources/rust-server/client.mustache new file mode 100644 index 00000000000..c168f502698 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust-server/client.mustache @@ -0,0 +1,336 @@ +#![allow(unused_extern_crates)] +extern crate hyper_openssl; +extern crate chrono; +{{#apiHasFile}}extern crate multipart;{{/apiHasFile}} + +{{#apiHasFile}}use multipart::client::lazy::Multipart;{{/apiHasFile}} +use hyper; +use hyper::client::IntoUrl; +use hyper::mime; +use hyper::header::{Headers, ContentType}; +use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use hyper::Url; +use self::hyper_openssl::openssl; +use futures; +use futures::{Future, Stream}; +use futures::{future, stream}; +use std::borrow::Cow; +use std::io::{Read, Error}; +use std::error; +use std::fmt; +use std::path::Path; +use std::sync::Arc; +use std::str; + +use mimetypes; + +use serde_json; +{{#usesXml}}use serde_xml_rs;{{/usesXml}} + +#[allow(unused_imports)] +use std::collections::{HashMap, BTreeMap}; +#[allow(unused_imports)] +use swagger; + +use swagger::{Context, ApiError, XSpanId}; + +use {Api{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, + {{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + }; +use models; + +/// Convert input into a base path, e.g. "http://example:123". Also checks the scheme as it goes. +fn into_base_path(input: T, correct_scheme: Option<&'static str>) -> Result { + // First convert to Url, since a base path is a subset of Url. + let url = input.into_url()?; + + let scheme = url.scheme(); + + // Check the scheme if necessary + if let Some(correct_scheme) = correct_scheme { + if scheme != correct_scheme { + return Err(ClientInitError::InvalidScheme); + } + } + + let host = url.host().ok_or_else(|| ClientInitError::MissingHost)?; + let port = url.port().map(|x| format!(":{}", x)).unwrap_or_default(); + Ok(format!("{}://{}{}", scheme, host, port)) +} + +/// A client that implements the API by making HTTP calls out to a server. +#[derive(Clone)] +pub struct Client { + base_path: String, + hyper_client: Arc hyper::client::Client + Sync + Send>, +} + +impl fmt::Debug for Client { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Client {{ base_path: {} }}", self.base_path) + } +} + +impl Client { + pub fn try_new_http(base_path: T) -> Result + where T: IntoUrl + { + Ok(Client { + base_path: into_base_path(base_path, Some("http"))?, + hyper_client: Arc::new(hyper::client::Client::new), + }) + } + + pub fn try_new_https(base_path: T, + ca_certificate: CA) + -> Result + where T: IntoUrl, + CA: AsRef + { + let ca_certificate = ca_certificate.as_ref().to_owned(); + + let https_hyper_client = move || { + // SSL implementation + let mut ssl = openssl::ssl::SslConnectorBuilder::new(openssl::ssl::SslMethod::tls()).unwrap(); + + // Server authentication + ssl.builder_mut().set_ca_file(ca_certificate.clone()).unwrap(); + + let ssl = hyper_openssl::OpensslClient::from(ssl.build()); + let connector = hyper::net::HttpsConnector::new(ssl); + hyper::client::Client::with_connector(connector) + }; + + Ok(Client { + base_path: into_base_path(base_path, Some("https"))?, + hyper_client: Arc::new(https_hyper_client), + }) + } + + pub fn try_new_https_mutual(base_path: T, + ca_certificate: CA, + client_key: K, + client_certificate: C) + -> Result + where T: IntoUrl, + CA: AsRef, + K: AsRef, + C: AsRef + { + let ca_certificate = ca_certificate.as_ref().to_owned(); + let client_key = client_key.as_ref().to_owned(); + let client_certificate = client_certificate.as_ref().to_owned(); + + let https_mutual_hyper_client = move || { + // SSL implementation + let mut ssl = openssl::ssl::SslConnectorBuilder::new(openssl::ssl::SslMethod::tls()).unwrap(); + + // Server authentication + ssl.builder_mut().set_ca_file(ca_certificate.clone()).unwrap(); + + // Client authentication + ssl.builder_mut().set_private_key_file(client_key.clone(), openssl::x509::X509_FILETYPE_PEM).unwrap(); + ssl.builder_mut().set_certificate_chain_file(client_certificate.clone()).unwrap(); + ssl.builder_mut().check_private_key().unwrap(); + + let ssl = hyper_openssl::OpensslClient::from(ssl.build()); + let connector = hyper::net::HttpsConnector::new(ssl); + hyper::client::Client::with_connector(connector) + }; + + Ok(Client { + base_path: into_base_path(base_path, Some("https"))?, + hyper_client: Arc::new(https_mutual_hyper_client) + }) + } + + /// Constructor for creating a `Client` by passing in a pre-made `hyper` client. + /// + /// One should avoid relying on this function if possible, since it adds a dependency on the underlying transport + /// implementation, which it would be better to abstract away. Therefore, using this function may lead to a loss of + /// code generality, which may make it harder to move the application to a serverless environment, for example. + /// + /// The reason for this function's existence is to support legacy test code, which did mocking at the hyper layer. + /// This is not a recommended way to write new tests. If other reasons are found for using this function, they + /// should be mentioned here. + pub fn try_new_with_hyper_client(base_path: T, + hyper_client: Arc hyper::client::Client + Sync + Send>) + -> Result + where T: IntoUrl + { + Ok(Client { + base_path: into_base_path(base_path, None)?, + hyper_client: hyper_client + }) + } +} + +impl Api for Client { +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} + fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, param_{{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &Context) -> Box + Send> { +{{#queryParams}}{{#-first}} + // Query parameters +{{/-first}}{{#required}} let query_{{paramName}} = format!("{{baseName}}={{=<% %>=}}{<% paramName %>}<%={{ }}=%>&", {{paramName}}=param_{{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}{{^isListContainer}}.to_string(){{/isListContainer}}); +{{/required}}{{^required}} let query_{{paramName}} = param_{{paramName}}.map_or_else(String::new, |query| format!("{{baseName}}={{=<% %>=}}{<% paramName %>}<%={{ }}=%>&", {{paramName}}=query{{#isListContainer}}.join(","){{/isListContainer}}{{^isListContainer}}.to_string(){{/isListContainer}})); +{{/required}}{{/queryParams}} + + let url = format!("{}{{basePathWithoutHost}}{{path}}?{{#queryParams}}{{=<% %>=}}{<% paramName %>}<%={{ }}=%>{{/queryParams}}", self.base_path{{#pathParams}}, {{baseName}}=param_{{paramName}}.to_string(){{/pathParams}}{{#queryParams}}, {{paramName}}=query_{{paramName}}{{/queryParams}}); + +{{#vendorExtensions}}{{#hasFile}} // Form data body + let mut multipart = Multipart::new();{{/hasFile}}{{/vendorExtensions}}{{#formParams}}{{#isFile}} + +{{^required}} if let Ok(Some(param_{{paramName}})) = param_{{paramName}}.wait() { {{/required}} +{{^required}} {{/required}} match convert_stream_to_string(param_{{paramName}}) { +{{^required}} {{/required}} Ok(param_{{paramName}}) => { + // Add file to multipart form. + multipart.add_text("{{paramName}}", param_{{paramName}}); + }, +{{^required}} {{/required}} Err(err) => return Box::new(futures::done(Err(err))), +{{^required}} {{/required}} } + {{^required}}}{{/required}}{{/isFile}}{{/formParams}}{{#vendorExtensions}}{{#hasFile}} + + let mut fields = match multipart.prepare() { + Ok(fields) => fields, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build request: {}", err))))), + }; + + let mut body_string = String::new(); + let body = fields.to_body().read_to_string(&mut body_string); + let boundary = fields.boundary(); + let multipart_header = Mime(TopLevel::Multipart, SubLevel::FormData, vec![(Attr::Boundary, Value::Ext(boundary.to_string()))]);{{/hasFile}}{{/vendorExtensions}}{{#bodyParam}}{{#-first}} + // Body parameter +{{/-first}}{{#required}}{{#vendorExtensions}}{{#consumesXml}} +{{^has_namespace}} let body = serde_xml_rs::to_string(¶m_{{paramName}}).expect("impossible to fail to serialize");{{/has_namespace}}{{#has_namespace}} + let mut namespaces = BTreeMap::new(); + // An empty string is used to indicate a global namespace in xmltree. + namespaces.insert("".to_string(), models::namespaces::{{uppercase_data_type}}.clone()); + let body = serde_xml_rs::to_string_with_namespaces(¶m_{{paramName}}, namespaces).expect("impossible to fail to serialize");{{/has_namespace}}{{/consumesXml}}{{^consumesXml}} + let body = serde_json::to_string(¶m_{{paramName}}).expect("impossible to fail to serialize");{{/consumesXml}}{{/vendorExtensions}} +{{/required}}{{^required}} let body = param_{{paramName}}.map(|ref body| { +{{#vendorExtensions}}{{#consumesXml}} +{{^has_namespace}} serde_xml_rs::to_string(body).expect("impossible to fail to serialize"){{/has_namespace}}{{#has_namespace}} + let mut namespaces = BTreeMap::new(); + // An empty string is used to indicate a global namespace in xmltree. + namespaces.insert("".to_string(), models::namespaces::{{uppercase_data_type}}.clone()); + serde_xml_rs::to_string_with_namespaces(body, namespaces).expect("impossible to fail to serialize"){{/has_namespace}}{{/consumesXml}}{{^consumesXml}} + serde_json::to_string(body).expect("impossible to fail to serialize"){{/consumesXml}}{{/vendorExtensions}} + });{{/required}}{{/bodyParam}} + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::{{#vendorExtensions}}{{HttpMethod}}{{/vendorExtensions}}, &url); + let mut custom_headers = hyper::header::Headers::new(); + +{{#bodyParam}}{{#required}} let request = request.body(&body); +{{/required}}{{^required}} let request = match body { + Some(ref body) => request.body(body), + None => request, + }; +{{/required}} + + custom_headers.set(ContentType(mimetypes::requests::{{#vendorExtensions}}{{uppercase_operation_id}}{{/vendorExtensions}}.clone())); +{{/bodyParam}} + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); +{{#headerParams}}{{#-first}} + // Header parameters +{{/-first}}{{^isMapContainer}} header! { (Request{{vendorExtensions.typeName}}, "{{baseName}}") => {{#isListContainer}}({{{baseType}}})*{{/isListContainer}}{{^isListContainer}}[{{{dataType}}}]{{/isListContainer}} } +{{#required}} custom_headers.set(Request{{vendorExtensions.typeName}}(param_{{paramName}}{{#isListContainer}}.clone(){{/isListContainer}})); +{{/required}}{{^required}} param_{{paramName}}.map(|header| custom_headers.set(Request{{vendorExtensions.typeName}}(header{{#isListContainer}}.clone(){{/isListContainer}}))); +{{/required}}{{/isMapContainer}}{{#isMapContainer}} let param_{{paramName}}: Option<{{{dataType}}}> = None; +{{/isMapContainer}}{{/headerParams}} + + let request = request.headers(custom_headers);{{#vendorExtensions}}{{#hasFile}} + let request = request.header(ContentType(multipart_header)) + .body(&body_string); +{{/hasFile}}{{/vendorExtensions}} + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result<{{operationId}}Response, ApiError> { + match response.status.to_u16() { +{{#responses}} + {{code}} => { +{{#dataType}}{{^isFile}} let mut buf = String::new(); + response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?;{{#vendorExtensions}}{{#producesXml}} + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + let body = serde_xml_rs::from_str::<{{{dataType}}}>(&buf) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?;{{/producesXml}}{{^producesXml}} + let body = serde_json::from_str::<{{{dataType}}}>(&buf)?; +{{/producesXml}}{{/vendorExtensions}}{{/isFile}}{{#isFile}} let mut buf = Vec::new(); + response.read_to_end(&mut buf).map_err(|e| ApiError(format!("Received error reading response: {}", e)))?; + let body = Box::new(stream::once(Ok(buf)));{{/isFile}} +{{/dataType}} + +{{#headers}} header! { (Response{{nameInCamelCase}}, "{{baseName}}") => [{{{datatype}}}] } + let response_{{name}} = response.headers.get::().ok_or_else(|| "Required response header {{baseName}} for response {{code}} was not found.")?; +{{/headers}} + +{{#dataType}} Ok({{operationId}}Response::{{message}}{{^headers}}(body){{/headers}}{{#headers}}{{#-first}}{ body: body, {{/-first}}{{name}}: response_{{name}}.0.clone(){{^-last}}, {{/-last}}{{#-last}} }{{/-last}}{{/headers}}) +{{/dataType}}{{^dataType}} Ok({{operationId}}Response::{{message}}{{#headers}}{{#-first}}{ {{/-first}}{{^-first}}, {{/-first}}{{name}}: response_{{name}}.0.clone(){{#-last}} }{{/-last}}{{/headers}}) +{{/dataType}} + }, +{{/responses}} + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + }{{#vendorExtensions}}{{#hasFile}} + + // Helper function to convert a Stream into a String. The String can then be used to build the HTTP body. + fn convert_stream_to_string(stream: Box, Error=Error> + Send>) -> Result { + + stream.fold(Vec::new(), |mut body, chunk| { + body.extend(chunk.iter()); + future::ok::,Error>(body) + }).wait() + .map_err(|e| ApiError(format!("Unable to fold stream: {}", e))) + .and_then(|body| String::from_utf8(body) + .map_err(|e| ApiError(format!("Failed to convert utf8 stream to String: {}", e)))) + }{{/hasFile}}{{/vendorExtensions}} + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +} + +#[derive(Debug)] +pub enum ClientInitError { + InvalidScheme, + InvalidUrl(hyper::error::ParseError), + MissingHost, + SslError(openssl::error::ErrorStack) +} + +impl From for ClientInitError { + fn from(err: hyper::error::ParseError) -> ClientInitError { + ClientInitError::InvalidUrl(err) + } +} + +impl From for ClientInitError { + fn from(err: openssl::error::ErrorStack) -> ClientInitError { + ClientInitError::SslError(err) + } +} + +impl fmt::Display for ClientInitError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + (self as &fmt::Debug).fmt(f) + } +} + +impl error::Error for ClientInitError { + fn description(&self) -> &str { + "Failed to produce a hyper client." + } +} diff --git a/modules/swagger-codegen/src/main/resources/rust-server/example-ca.pem b/modules/swagger-codegen/src/main/resources/rust-server/example-ca.pem new file mode 100644 index 00000000000..d2317fb5db7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust-server/example-ca.pem @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE----- +MIICtjCCAZ4CCQDpKecRERZ0xDANBgkqhkiG9w0BAQsFADAdMQswCQYDVQQGEwJV +UzEOMAwGA1UEAxMFTXkgQ0EwHhcNMTcwNTIzMTYwMDIzWhcNMTcwNjIyMTYwMDIz +WjAdMQswCQYDVQQGEwJVUzEOMAwGA1UEAxMFTXkgQ0EwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQCt66py3x7sCSASRF2D05L5wkNDxAUjQKYx23W8Gbwv +GMGykk89BIdU5LX1JB1cKiUOkoIxfwAYuWc2V/wzTvVV7+11besnk3uX1c9KiqUF +LIX7kn/z5hzS4aelhKvH+MJlSZCSlp1ytpZbwo5GB5Pi2SGH56jDBiBoDRNBVdWL +z4wH7TdrQjqWwNxIZumD5OGMtcfJyuX08iPiEOaslOeoMqzObhvjc9aUgjVjhqyA +FkJGTXsi0oaD7oml+NE+mTNfEeZvEJQpLSjBY0OvQHzuHkyGBShBnfu/9x7/NRwd +WaqsLiF7/re9KDGYdJwP7Cu6uxYfKAyWarp6h2mG/GIdAgMBAAEwDQYJKoZIhvcN +AQELBQADggEBAGIl/VVIafeq/AJOQ9r7TzzB2ABJYr7NZa6bTu5O1jSp1Fonac15 +SZ8gvRxODgH22ZYSqghPG4xzq4J3hkytlQqm57ZEt2I2M3OqIp17Ndcc1xDYzpLl +tA0FrVn6crQTM8vQkTDtGesaCWX+7Fir5dK7HnYWzfpSmsOpST07PfbNisEXKOxG +Dj4lBL1OnhTjsJeymVS1pFvkKkrcEJO+IxFiHL3CDsWjcXB0Z+E1zBtPoYyYsNsO +rBrjUxcZewF4xqWZhpW90Mt61fY2nRgU0uUwHcvDQUqvmzKcsqYa4mPKzfBI5mxo +01Ta96cDD6pS5Y1hOflZ0g84f2g/7xBLLDA= +-----END CERTIFICATE----- diff --git a/modules/swagger-codegen/src/main/resources/rust-server/example-client.mustache b/modules/swagger-codegen/src/main/resources/rust-server/example-client.mustache new file mode 100644 index 00000000000..2d76fcb47d4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust-server/example-client.mustache @@ -0,0 +1,59 @@ +#![allow(missing_docs, unused_variables, trivial_casts)] + +extern crate {{externCrateName}}; +#[allow(unused_extern_crates)] +extern crate futures; +#[allow(unused_extern_crates)] +extern crate swagger; +#[allow(unused_extern_crates)] +extern crate uuid; +extern crate clap; + +#[allow(unused_imports)] +use futures::{Future, future, Stream, stream}; +#[allow(unused_imports)] +use {{externCrateName}}::{ApiNoContext, ContextWrapperExt, + ApiError{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, + {{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + }; +use clap::{App, Arg}; + +fn main() { + let matches = App::new("client") + .arg(Arg::with_name("operation") + .help("Sets the operation to run") + .possible_values(&[ +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#vendorExtensions}}{{^noClientExample}} "{{operationId}}", +{{/noClientExample}}{{/vendorExtensions}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}]) + .required(true) + .index(1)) + .arg(Arg::with_name("https") + .long("https") + .help("Whether to use HTTPS or not")) + .get_matches(); + + let client = if matches.is_present("https") { + // Using Simple HTTPS + {{externCrateName}}::Client::try_new_https("https://localhost:{{serverPort}}", "examples/ca.pem").expect("Failed to create HTTPS client") + } else { + // Using HTTP + {{externCrateName}}::Client::try_new_http("http://localhost:{{serverPort}}").expect("Failed to create HTTP client") + }; + + // Using a non-default `Context` is not required; this is just an example! + let client = client.with_context({{externCrateName}}::Context::new_with_span_id(self::uuid::Uuid::new_v4().to_string())); + + match matches.value_of("operation") { +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} + {{#vendorExtensions}}{{#noClientExample}}// Disabled because there's no example. + // {{/noClientExample}}Some("{{operationId}}") => { + {{#noClientExample}}// {{/noClientExample}} let result = client.{{operation_id}}{{/vendorExtensions}}({{#allParams}}{{^-first}}, {{/-first}}{{#vendorExtensions}}{{{example}}}{{/vendorExtensions}}{{/allParams}}).wait(); + {{#vendorExtensions}}{{#noClientExample}}// {{/noClientExample}}{{/vendorExtensions}} println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + {{#vendorExtensions}}{{#noClientExample}}// {{/noClientExample}}{{/vendorExtensions}} }, +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + _ => { + panic!("Invalid operation provided") + } + } +} + diff --git a/modules/swagger-codegen/src/main/resources/rust-server/example-server-chain.pem b/modules/swagger-codegen/src/main/resources/rust-server/example-server-chain.pem new file mode 100644 index 00000000000..47d7e201404 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust-server/example-server-chain.pem @@ -0,0 +1,66 @@ +Certificate: + Data: + Version: 1 (0x0) + Serial Number: 4096 (0x1000) + Signature Algorithm: sha256WithRSAEncryption + Issuer: C=US, CN=My CA + Validity + Not Before: May 23 16:00:23 2017 GMT + Not After : Apr 29 16:00:23 2117 GMT + Subject: CN=localhost, C=US + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:c9:d4:43:60:50:fc:d6:0f:38:4d:5d:5e:aa:7c: + c0:5e:a9:ec:d9:93:78:d3:93:72:28:41:f5:08:a5: + ea:ac:67:07:d7:1f:f7:7d:74:69:7e:46:89:20:4b: + 7a:2d:9b:02:08:e7:6f:0f:1d:0c:0f:c7:60:69:19: + 4b:df:7e:ca:75:94:0b:49:71:e3:6d:f2:e8:79:fd: + ed:0a:94:67:55:f3:ca:6b:61:ba:58:b7:2e:dd:7b: + ca:b9:02:9f:24:36:ac:26:8f:04:8f:81:c8:35:10: + f4:aa:33:b2:24:16:f8:f7:1e:ea:f7:16:fe:fa:34: + c3:dd:bb:2c:ba:7a:df:4d:e2:da:1e:e5:d2:28:44: + 6e:c8:96:e0:fd:09:0c:14:0c:31:dc:e0:ca:c1:a7: + 9b:bf:16:8c:f7:36:3f:1b:2e:dd:90:eb:45:78:51: + bf:59:22:1e:c6:8c:0a:69:88:e5:03:5e:73:b7:fc: + 93:7f:1b:46:1b:97:68:c5:c0:8b:35:1f:bb:1e:67: + 7f:55:b7:3b:55:3f:ea:f2:ca:db:cc:52:cd:16:89: + db:15:47:bd:f2:cd:6c:7a:d7:b4:1a:ac:c8:15:6c: + 6a:fb:77:c4:e9:f2:30:e0:14:24:66:65:6f:2a:e5: + 2d:cc:f6:81:ae:57:c8:d1:9b:38:90:dc:60:93:02: + 5e:cb + Exponent: 65537 (0x10001) + Signature Algorithm: sha256WithRSAEncryption + 1c:7c:39:e8:3d:49:b2:09:1e:68:5a:2f:74:18:f4:63:b5:8c: + f6:e6:a1:e3:4d:95:90:99:ef:32:5c:34:40:e8:55:13:0e:e0: + 1c:be:cd:ab:3f:64:38:99:5e:2b:c1:81:53:a0:18:a8:f6:ee: + 6a:33:73:6c:9a:73:9d:86:08:5d:c7:11:38:46:4c:cd:a0:47: + 37:8f:fe:a6:50:a9:02:21:99:42:86:5e:47:fe:65:56:60:1d: + 16:53:86:bd:e4:63:c5:69:cf:fa:30:51:ab:a1:c3:50:53:cc: + 66:1c:4c:ff:3f:2a:39:4d:a2:8f:9d:d1:a7:8b:22:e4:78:69: + 24:06:83:4d:cc:0a:c0:87:69:9b:bc:80:a9:d2:b7:a5:23:84: + 7e:a2:32:26:7c:78:0e:bd:db:cd:3b:69:18:33:b8:44:ef:96: + b4:99:86:ee:06:bd:51:1c:c7:a1:a4:0c:c4:4c:51:a0:df:ac: + 14:07:88:8e:d7:39:45:fe:52:e0:a3:4c:db:5d:7a:ab:4d:e4: + ca:06:e8:bd:74:6f:46:e7:93:4a:4f:1b:67:e7:a5:9f:ef:9c: + 02:49:d1:f2:d5:e9:53:ee:09:21:ac:08:c8:15:f7:af:35:b9: + 4f:11:0f:43:ae:46:8e:fd:5b:8d:a3:4e:a7:2c:b7:25:ed:e4: + e5:94:1d:e3 +-----BEGIN CERTIFICATE----- +MIICtTCCAZ0CAhAAMA0GCSqGSIb3DQEBCwUAMB0xCzAJBgNVBAYTAlVTMQ4wDAYD +VQQDEwVNeSBDQTAgFw0xNzA1MjMxNjAwMjNaGA8yMTE3MDQyOTE2MDAyM1owITES +MBAGA1UEAxMJbG9jYWxob3N0MQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEB +BQADggEPADCCAQoCggEBAMnUQ2BQ/NYPOE1dXqp8wF6p7NmTeNOTcihB9Qil6qxn +B9cf9310aX5GiSBLei2bAgjnbw8dDA/HYGkZS99+ynWUC0lx423y6Hn97QqUZ1Xz +ymthuli3Lt17yrkCnyQ2rCaPBI+ByDUQ9KozsiQW+Pce6vcW/vo0w927LLp6303i +2h7l0ihEbsiW4P0JDBQMMdzgysGnm78WjPc2Pxsu3ZDrRXhRv1kiHsaMCmmI5QNe +c7f8k38bRhuXaMXAizUfux5nf1W3O1U/6vLK28xSzRaJ2xVHvfLNbHrXtBqsyBVs +avt3xOnyMOAUJGZlbyrlLcz2ga5XyNGbOJDcYJMCXssCAwEAATANBgkqhkiG9w0B +AQsFAAOCAQEAHHw56D1JsgkeaFovdBj0Y7WM9uah402VkJnvMlw0QOhVEw7gHL7N +qz9kOJleK8GBU6AYqPbuajNzbJpznYYIXccROEZMzaBHN4/+plCpAiGZQoZeR/5l +VmAdFlOGveRjxWnP+jBRq6HDUFPMZhxM/z8qOU2ij53Rp4si5HhpJAaDTcwKwIdp +m7yAqdK3pSOEfqIyJnx4Dr3bzTtpGDO4RO+WtJmG7ga9URzHoaQMxExRoN+sFAeI +jtc5Rf5S4KNM2116q03kygbovXRvRueTSk8bZ+eln++cAknR8tXpU+4JIawIyBX3 +rzW5TxEPQ65Gjv1bjaNOpyy3Je3k5ZQd4w== +-----END CERTIFICATE----- diff --git a/modules/swagger-codegen/src/main/resources/rust-server/example-server-key.pem b/modules/swagger-codegen/src/main/resources/rust-server/example-server-key.pem new file mode 100644 index 00000000000..29c00682922 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust-server/example-server-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDJ1ENgUPzWDzhN +XV6qfMBeqezZk3jTk3IoQfUIpeqsZwfXH/d9dGl+RokgS3otmwII528PHQwPx2Bp +GUvffsp1lAtJceNt8uh5/e0KlGdV88prYbpYty7de8q5Ap8kNqwmjwSPgcg1EPSq +M7IkFvj3Hur3Fv76NMPduyy6et9N4toe5dIoRG7IluD9CQwUDDHc4MrBp5u/Foz3 +Nj8bLt2Q60V4Ub9ZIh7GjAppiOUDXnO3/JN/G0Ybl2jFwIs1H7seZ39VtztVP+ry +ytvMUs0WidsVR73yzWx617QarMgVbGr7d8Tp8jDgFCRmZW8q5S3M9oGuV8jRmziQ +3GCTAl7LAgMBAAECggEBAKEd1q9j14KWYc64s6KLthGbutyxsinMMbxbct11fdIk +6YhdF3fJ35ETg9IJDr6rWEN9ZRX+jStncNpVfFEs6ThVd3Eo/nI+EEGaaIkikR93 +X2a7fEPn7/yVHu70XdBN6L1bPDvHUeiy4W2hmRrgT90OjGm1rNRWHOm7yugOwIZu +HclzbR9Ca7EInFnotUiDQm9sw9VKHbJHqWx6OORdZrxR2ytYs0Qkq0XpGMvti2HW +7WAmKTg5QM8myXW7+/4iqb/u68wVBR2BBalShKmIf7lim9O3W2a1RjDdsvm/wNe9 +I+D+Iq825vpqkKXcrxYlpVg7hYiaQaW/MNsEb7lQRjECgYEA/RJYby0POW+/k0Jn +jO8UmJVEMiuGa8WIUu/JJWMOmzRCukjSRNQOkt7niQrZPJYE8W6clM6RJTolWf9L +IL6mIb+mRaoudUk8SHGDq7ho1iMg9GK8lhYxvKh1Q6uv8EyVSkgLknAEY0NANKC1 +zNdU5Dhven9aRX2gq9vP4XwMz2MCgYEAzCogQ7IFk+gkp3k491dOZnrGRoRCfuzo +4CJtyKFgOSd7BjmpcKkj0IPfVBjw6GjMIxfQRMTQmxAjjWevH45vG8l0Iiwz/gSp +81b5nsDEX5uv2Olcmcz5zxRFy36jOZ9ihMWinxcIlT2oDbyCdbruDKZq9ieJ9S8g +4qGx0OkwE3kCgYEA7CmAiU89U9YqqttfEq/RQoqY91CSwmO10d+ej9seuEtOsdRf +FIfnibulycdr7hP5TOxyBpO1802NqayJiWcgVYIpQf2MGTtcnCYCP+95NcvWZvj1 +EAJqK6nwtFO1fcOZ1ZXh5qfOEGujsPkAbsXLnKXlsiTCMvMHSxl3pu5Cbg0CgYBf +JjbZNctRrjv+7Qj2hPLd4dQsIxGWc7ToWENP4J2mpVa5hQAJqFovoHXhjKohtk2F +AWEn243Y5oGbMjo0e74edhmwn2cvuF64MM2vBem/ISCn98IXT6cQskMA3qkVfsl8 +VVs/x41ReGWs2TD3y0GMFbb9t1mdMfSiincDhNnKCQKBgGfeT4jKyYeCoCw4OLI1 +G75Gd0METt/IkppwODPpNwj3Rp9I5jctWZFA/3wCX/zk0HgBeou5AFNS4nQZ/X/L +L9axbSdR7UJTGkT1r4gu3rLkPV4Tk+8XM03/JT2cofMlzQBuhvl1Pn4SgKowz7hl +lS76ECw4Av3T0S34VW9Z5oye +-----END PRIVATE KEY----- diff --git a/modules/swagger-codegen/src/main/resources/rust-server/example-server.mustache b/modules/swagger-codegen/src/main/resources/rust-server/example-server.mustache new file mode 100644 index 00000000000..7da74ee26e7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust-server/example-server.mustache @@ -0,0 +1,58 @@ +#![allow(missing_docs)] + +extern crate {{externCrateName}}; +extern crate iron; +extern crate futures; +extern crate hyper_openssl; +extern crate clap; +extern crate swagger; + +use hyper_openssl::OpensslServer; +use hyper_openssl::openssl::x509::X509_FILETYPE_PEM; +use hyper_openssl::openssl::ssl::{SslAcceptorBuilder, SslMethod}; +use hyper_openssl::openssl::error::ErrorStack; +use clap::{App, Arg}; +use iron::{Iron, Chain}; +use swagger::auth::AllowAllMiddleware; + +// Import the module that defines the Server struct. +mod server_lib; + +/// Builds an SSL implementation for Simple HTTPS from some hard-coded file names +fn ssl() -> Result { + let mut ssl = SslAcceptorBuilder::mozilla_intermediate_raw(SslMethod::tls())?; + + // Server authentication + ssl.builder_mut().set_private_key_file("examples/server-key.pem", X509_FILETYPE_PEM)?; + ssl.builder_mut().set_certificate_chain_file("examples/server-chain.pem")?; + ssl.builder_mut().check_private_key()?; + + Ok(OpensslServer::from(ssl.build())) +} + +/// Create custom server, wire it to the autogenerated router, +/// and pass it to the web server. +fn main() { + let matches = App::new("server") + .arg(Arg::with_name("https") + .long("https") + .help("Whether to use HTTPS or not")) + .get_matches(); + + let server = server_lib::Server{}; + let router = {{externCrateName}}::router(server); + + let mut chain = Chain::new(router); + chain.link_before({{externCrateName}}::server::ExtractAuthData); + // add authentication middlewares into the chain here + // for the purpose of this example, pretend we have authenticated a user + chain.link_before(AllowAllMiddleware::new("cosmo")); + + if matches.is_present("https") { + // Using Simple HTTPS + Iron::new(chain).https("localhost:{{serverPort}}", ssl().expect("Failed to load SSL keys")).expect("Failed to start HTTPS server"); + } else { + // Using HTTP + Iron::new(chain).http("localhost:{{serverPort}}").expect("Failed to start HTTP server"); + } +} diff --git a/modules/swagger-codegen/src/main/resources/rust-server/example-server_lib.mustache b/modules/swagger-codegen/src/main/resources/rust-server/example-server_lib.mustache new file mode 100644 index 00000000000..b9288a38cc8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust-server/example-server_lib.mustache @@ -0,0 +1,31 @@ +#![allow(missing_docs, unused_extern_crates)] +extern crate chrono; +extern crate swagger; + +use futures::{self, Future}; +{{#apiHasFile}}use futures::Stream;{{/apiHasFile}} + +#[allow(unused_imports)] +use std::collections::HashMap; +{{#apiHasFile}}use std::io::Error;{{/apiHasFile}} + +use {{externCrateName}}::{Api, ApiError, Context{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, + {{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +}; +#[allow(unused_imports)] +use {{externCrateName}}::models; + +#[derive(Copy, Clone)] +pub struct Server; + +impl Api for Server { +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} +{{#summary}} /// {{{summary}}}{{/summary}} + fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("{{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}({{#allParams}}{{^isFile}}{{#vendorExtensions}}{{{formatString}}}{{/vendorExtensions}}{{#hasMore}}, {{/hasMore}}{{/isFile}}{{/allParams}}) - X-Span-ID: {:?}"{{#allParams}}{{^isFile}}, {{paramName}}{{/isFile}}{{/allParams}}, context.x_span_id.unwrap_or(String::from("")).clone());{{#allParams}}{{#isFile}} + let _ = {{paramName}}; //Suppresses unused param warning{{/isFile}}{{/allParams}} + Box::new(futures::failed("Generic failure".into())) + } +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +} diff --git a/modules/swagger-codegen/src/main/resources/rust-server/gitignore b/modules/swagger-codegen/src/main/resources/rust-server/gitignore new file mode 100644 index 00000000000..a9d37c560c6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust-server/gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/modules/swagger-codegen/src/main/resources/rust-server/lib.mustache b/modules/swagger-codegen/src/main/resources/rust-server/lib.mustache new file mode 100644 index 00000000000..2c913125401 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust-server/lib.mustache @@ -0,0 +1,96 @@ +#![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +extern crate serde; +#[macro_use] +extern crate serde_derive; +extern crate serde_json; +{{#usesXml}}extern crate serde_xml_rs;{{/usesXml}} +extern crate futures; +extern crate chrono; +{{#apiHasFile}}extern crate multipart;{{/apiHasFile}} +#[macro_use] +extern crate lazy_static; +#[macro_use] +extern crate log; + +// Logically this should be in the client and server modules, but rust doesn't allow `macro_use` from a module. +#[cfg(any(feature = "client", feature = "server"))] +#[macro_use] +extern crate hyper; + +extern crate swagger; + +use futures::Stream; +use std::io::Error; + +#[allow(unused_imports)] +use std::collections::HashMap; + +pub use futures::Future; + +#[cfg(any(feature = "client", feature = "server"))] +mod mimetypes; + +pub use swagger::{ApiError, Context, ContextWrapper}; + +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} +{{^isResponseFile}} +#[derive(Debug, PartialEq)] +{{/isResponseFile}} +pub enum {{operationId}}Response { +{{#responses}} {{message}} {{#dataType}}{{^headers}}( {{{dataType}}} ) {{/headers}}{{#headers}}{{#-first}}{ body: {{{dataType}}}{{/-first}}{{/headers}}{{/dataType}}{{#headers}}{{#-first}}{{^dataType}} { {{/dataType}}{{#dataType}}, {{/dataType}}{{/-first}}{{^-first}}, {{/-first}}{{name}}: {{{datatype}}}{{#-last}} } {{/-last}}{{/headers}}, +{{/responses}} +} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +/// API +pub trait Api { +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} +{{#summary}} /// {{{summary}}}{{/summary}} + fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &Context) -> Box + Send>; +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +} + +/// API without a `Context` +pub trait ApiNoContext { +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} +{{#summary}} /// {{{summary}}}{{/summary}} + fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}) -> Box + Send>; +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +} + +/// Trait to extend an API to make it easy to bind it to a context. +pub trait ContextWrapperExt<'a> where Self: Sized { + /// Binds this API to a context. + fn with_context(self: &'a Self, context: Context) -> ContextWrapper<'a, Self>; +} + +impl<'a, T: Api + Sized> ContextWrapperExt<'a> for T { + fn with_context(self: &'a T, context: Context) -> ContextWrapper<'a, T> { + ContextWrapper::::new(self, context) + } +} + +impl<'a, T: Api> ApiNoContext for ContextWrapper<'a, T> { +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} +{{#summary}} /// {{{summary}}}{{/summary}} + fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}) -> Box + Send> { + self.api().{{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}({{#allParams}}{{paramName}}, {{/allParams}}&self.context()) + } +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +} + +#[cfg(feature = "client")] +pub mod client; + +// Re-export Client as a top-level name +#[cfg(feature = "client")] +pub use self::client::Client; + +#[cfg(feature = "server")] +pub mod server; + +// Re-export router() as a top-level name +#[cfg(feature = "server")] +pub use self::server::router; + +pub mod models; diff --git a/modules/swagger-codegen/src/main/resources/rust-server/mimetypes.mustache b/modules/swagger-codegen/src/main/resources/rust-server/mimetypes.mustache new file mode 100644 index 00000000000..336e12dfe64 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust-server/mimetypes.mustache @@ -0,0 +1,21 @@ +/// mime types for requests and responses + +pub mod responses { + use hyper::mime::*; + + // The macro is called per-operation to beat the recursion limit +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#responses}}{{#produces}}{{#-first}}{{#dataType}} /// Create Mime objects for the response content types for {{operationId}} + lazy_static! { + pub static ref {{#vendorExtensions}}{{uppercase_operation_id}}_{{uppercase_message}}{{/vendorExtensions}}: Mime = mime!({{{mediaType}}}); + } +{{/dataType}}{{/-first}}{{/produces}}{{/responses}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +} + +pub mod requests { + use hyper::mime::*; +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#bodyParam}} /// Create Mime objects for the request content types for {{operationId}} + lazy_static! { + pub static ref {{#vendorExtensions}}{{uppercase_operation_id}}{{/vendorExtensions}}: Mime = mime!({{#consumes}}{{#-first}}{{{mediaType}}}{{/-first}}{{/consumes}}{{^consumes}}Application/Json{{/consumes}}); + } +{{/bodyParam}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +} diff --git a/modules/swagger-codegen/src/main/resources/rust-server/models.mustache b/modules/swagger-codegen/src/main/resources/rust-server/models.mustache new file mode 100755 index 00000000000..4c31931dde0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust-server/models.mustache @@ -0,0 +1,175 @@ +#![allow(unused_imports, unused_qualifications, unused_extern_crates)] +extern crate chrono; +extern crate uuid; + +{{#usesXml}}use serde_xml_rs;{{/usesXml}} +use serde::ser::Serializer; + +use std::collections::HashMap; +use models; +use swagger; + +{{#models}}{{#model}} +{{#description}}/// {{{description}}} +{{/description}}{{#isEnum}}/// Enumeration of values. +/// Since this enum's variants do not hold data, we can easily define them them as `#[repr(C)]` +/// which helps with FFI. +#[allow(non_camel_case_types)] +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize, Deserialize)]{{#xmlName}} +#[serde(rename = "{{xmlName}}")]{{/xmlName}} +pub enum {{classname}} { {{#allowableValues}}{{#enumVars}} + #[serde(rename = {{{value}}})] + {{name}},{{/enumVars}}{{/allowableValues}} +} + +impl ::std::fmt::Display for {{classname}} { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + match *self { {{#allowableValues}}{{#enumVars}} + {{classname}}::{{name}} => write!(f, "{}", {{{value}}}),{{/enumVars}}{{/allowableValues}} + } + } +} + +impl ::std::str::FromStr for {{classname}} { + type Err = (); + fn from_str(s: &str) -> Result { + match s { +{{#allowableValues}}{{#enumVars}} {{{value}}} => Ok({{classname}}::{{name}}), +{{/enumVars}}{{/allowableValues}} _ => Err(()), + } + } +} +{{/isEnum}}{{^isEnum}}{{#dataType}}{{! newtype}}#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] +{{#xmlName}}#[serde(rename = "{{xmlName}}")]{{/xmlName}} +pub struct {{classname}}({{{dataType}}}); + +impl ::std::convert::From<{{dataType}}> for {{classname}} { + fn from(x: {{dataType}}) -> Self { + {{classname}}(x) + } +} + +impl ::std::convert::From<{{classname}}> for {{dataType}} { + fn from(x: {{classname}}) -> Self { + x.0 + } +} + +impl ::std::ops::Deref for {{classname}} { + type Target = {{{dataType}}}; + fn deref(&self) -> &{{{dataType}}} { + &self.0 + } +} + +impl ::std::ops::DerefMut for {{classname}} { + fn deref_mut(&mut self) -> &mut {{{dataType}}} { + &mut self.0 + } +} + +{{/dataType}}{{^dataType}}{{#arrayModelType}}{{#vendorExtensions}}{{#itemXmlName}}// Utility function for wrapping list elements when serializing xml +fn wrap_in_{{itemXmlName}}(item: &Vec<{{arrayModelType}}>, serializer: S) -> Result +where + S: Serializer, +{ + serde_xml_rs::wrap_primitives(item, serializer, "{{itemXmlName}}") +} + +{{/itemXmlName}}{{/vendorExtensions}}{{! vec}}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct {{classname}}(Vec<{{{arrayModelType}}}>); + +impl ::std::convert::From> for {{classname}} { + fn from(x: Vec<{{arrayModelType}}>) -> Self { + {{classname}}(x) + } +} + +impl ::std::convert::From<{{classname}}> for Vec<{{arrayModelType}}> { + fn from(x: {{classname}}) -> Self { + x.0 + } +} + +impl ::std::iter::FromIterator<{{arrayModelType}}> for {{classname}} { + fn from_iter>(u: U) -> Self { + {{classname}}(Vec::<{{arrayModelType}}>::from_iter(u)) + } +} + +impl ::std::iter::IntoIterator for {{classname}} { + type Item = {{arrayModelType}}; + type IntoIter = ::std::vec::IntoIter<{{arrayModelType}}>; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a> ::std::iter::IntoIterator for &'a {{classname}} { + type Item = &'a {{arrayModelType}}; + type IntoIter = ::std::slice::Iter<'a, {{arrayModelType}}>; + + fn into_iter(self) -> Self::IntoIter { + (&self.0).into_iter() + } +} + +impl<'a> ::std::iter::IntoIterator for &'a mut {{classname}} { + type Item = &'a mut {{arrayModelType}}; + type IntoIter = ::std::slice::IterMut<'a, {{arrayModelType}}>; + + fn into_iter(self) -> Self::IntoIter { + (&mut self.0).into_iter() + } +} + +impl ::std::ops::Deref for {{classname}} { + type Target = Vec<{{{arrayModelType}}}>; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl ::std::ops::DerefMut for {{classname}} { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +{{/arrayModelType}}{{^arrayModelType}}{{! general struct}}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]{{#xmlName}} +#[serde(rename = "{{xmlName}}")]{{/xmlName}} +pub struct {{classname}} { +{{#vars}}{{#description}} /// {{{description}}} +{{/description}}{{#isEnum}} // Note: inline enums are not fully supported by swagger-codegen +{{/isEnum}} #[serde(rename = "{{baseName}}")]{{#vendorExtensions}}{{#itemXmlName}} + #[serde(serialize_with = "wrap_in_{{itemXmlName}}")]{{/itemXmlName}}{{/vendorExtensions}}{{#required}} + pub {{name}}: {{#vendorExtensions}}{{#x-nullable}}swagger::Nullable<{{/x-nullable}}{{/vendorExtensions}}{{{datatype}}}{{#vendorExtensions}}{{#x-nullable}}>{{/x-nullable}}{{/vendorExtensions}}, +{{/required}}{{^required}}{{#vendorExtensions}}{{#x-nullable}} #[serde(deserialize_with = "swagger::nullable_format::deserialize_optional_nullable")] + #[serde(default = "swagger::nullable_format::default_optional_nullable")] +{{/x-nullable}}{{/vendorExtensions}} + #[serde(skip_serializing_if="Option::is_none")] + pub {{name}}: Option<{{#vendorExtensions}}{{#x-nullable}}swagger::Nullable<{{/x-nullable}}{{/vendorExtensions}}{{#isListContainer}}Vec<{{#items}}{{{datatype}}}{{/items}}>{{/isListContainer}}{{^isListContainer}}{{{datatype}}}{{/isListContainer}}{{#vendorExtensions}}{{#x-nullable}}>{{/x-nullable}}{{/vendorExtensions}}>, +{{/required}} + +{{/vars}} +} + +impl {{classname}} { + pub fn new({{#vars}}{{^defaultValue}}{{name}}: {{#vendorExtensions}}{{#x-nullable}}swagger::Nullable<{{/x-nullable}}{{/vendorExtensions}}{{{datatype}}}{{#vendorExtensions}}{{#x-nullable}}>{{/x-nullable}}{{/vendorExtensions}}, {{/defaultValue}}{{/vars}}) -> {{classname}} { + {{classname}} { +{{#vars}} {{name}}: {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}{{name}}{{/defaultValue}}, +{{/vars}} + } + } +} +{{/arrayModelType}}{{/dataType}}{{/isEnum}}{{/model}}{{/models}}{{#usesXmlNamespaces}} +//XML namespaces +pub mod namespaces { + lazy_static!{ + {{#models}}{{#model}}{{#xmlNamespace}}pub static ref {{#vendorExtensions}}{{upperCaseName}}{{/vendorExtensions}}: String = "{{xmlNamespace}}".to_string(); + {{/xmlNamespace}}{{/model}}{{/models}} + } +} +{{/usesXmlNamespaces}} diff --git a/modules/swagger-codegen/src/main/resources/rust-server/server.mustache b/modules/swagger-codegen/src/main/resources/rust-server/server.mustache new file mode 100644 index 00000000000..6091527455f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust-server/server.mustache @@ -0,0 +1,338 @@ +#![allow(unused_extern_crates)] +extern crate serde_ignored; +extern crate iron; +extern crate router; +extern crate bodyparser; +extern crate urlencoded; +extern crate uuid; +extern crate chrono; +{{#apiHasFile}}extern crate multipart;{{/apiHasFile}} + +use futures::Future; +use futures::future; +use futures::{stream, Stream}; +use hyper; +use hyper::header::{Headers, ContentType}; +use self::iron::prelude::*; +use self::iron::{status, modifiers, BeforeMiddleware}; +use self::iron::url::percent_encoding::percent_decode; +use self::router::Router; +use self::urlencoded::UrlEncodedQuery; +use mimetypes; +{{#apiHasFile}}use multipart::server::{Multipart, SaveResult};{{/apiHasFile}} + +use serde_json; +{{#usesXml}}use serde_xml_rs;{{/usesXml}} + +#[allow(unused_imports)] +use std::collections::{HashMap, BTreeMap}; +#[allow(unused_imports)] +use swagger; +use std::io::Error; + +#[allow(unused_imports)] +use std::collections::BTreeSet; + +use swagger::auth::{Authorization, AuthData, Scopes}; +use swagger::{ApiError, Context, XSpanId}; + +use {Api{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, + {{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + }; +#[allow(unused_imports)] +use models; + +header! { (Warning, "Warning") => [String] } + +/// Create a new router for `Api` +pub fn router(api: T) -> Router where T: Api + Send + Sync + Clone + 'static { + let mut router = Router::new(); + add_routes(&mut router, api); + router +} + +/// Add routes for `Api` to a provided router. +/// +/// Note that these routes are added straight onto the router. This means that if the router +/// already has a route for an endpoint which clashes with those provided by this API, then the +/// old route will be lost. +/// +/// It is generally a bad idea to add routes in this way to an existing router, which may have +/// routes on it for other APIs. Distinct APIs should be behind distinct paths to encourage +/// separation of interfaces, which this function does not enforce. APIs should not overlap. +/// +/// Alternative approaches include: +/// +/// - generate an `iron::middleware::Handler` (usually a `router::Router` or +/// `iron::middleware::chain`) for each interface, and add those handlers inside an existing +/// router, mounted at different paths - so the interfaces are separated by path +/// - use a different instance of `iron::Iron` for each interface - so the interfaces are +/// separated by the address/port they listen on +/// +/// This function exists to allow legacy code, which doesn't separate its APIs properly, to make +/// use of this crate. +#[deprecated(note="APIs should not overlap - only for use in legacy code.")] +pub fn route(router: &mut Router, api: T) where T: Api + Send + Sync + Clone + 'static { + add_routes(router, api) +} + +/// Add routes for `Api` to a provided router +fn add_routes(router: &mut Router, api: T) where T: Api + Send + Sync + Clone + 'static { +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} + let api_clone = api.clone(); + router.{{#vendorExtensions}}{{httpmethod}}{{/vendorExtensions}}( + "{{#vendorExtensions}}{{basePathWithoutHost}}{{path}}{{/vendorExtensions}}", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + {{#hasAuthMethods}} + let authorization = context.authorization.as_ref().ok_or_else(|| { + Response::with(( + status::Forbidden, + "Unauthenticated".to_string() + )) + })?; + + {{#authMethods}} + {{#isOAuth}} + // Authorization + if let Scopes::Some(ref scopes) = authorization.scopes { + let required_scopes: BTreeSet = vec![ + {{#scopes}} + "{{scope}}".to_string(), // {{description}} + {{/scopes}} + ].into_iter().collect(); + + if !required_scopes.is_subset(scopes) { + let missing_scopes = required_scopes.difference(scopes); + return Err(Response::with(( + status::Forbidden, + missing_scopes.fold( + "Insufficient authorization, missing scopes".to_string(), + |s, scope| format!("{} {}", s, scope) + ) + ))); + } + } + {{/isOAuth}} + {{/authMethods}} + {{/hasAuthMethods}} + +{{#pathParams}}{{#-first}} + // Path parameters +{{/-first}} let param_{{paramName}} = { + let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? + .find("{{baseName}}").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter {{baseName}}".to_string())))?; + percent_decode(param.as_bytes()).decode_utf8() + .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? + .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter {{baseName}}: {}", e))))? + }; +{{/pathParams}} +{{#headerParams}}{{#-first}} + // Header parameters +{{/-first}} header! { (Request{{vendorExtensions.typeName}}, "{{baseName}}") => {{#isListContainer}}({{{baseType}}})*{{/isListContainer}}{{^isListContainer}}[{{{dataType}}}]{{/isListContainer}} } +{{#required}} let param_{{paramName}} = req.headers.get::().ok_or_else(|| Response::with((status::BadRequest, "Missing or invalid required header {{baseName}}".to_string())))?.0.clone(); +{{/required}}{{^required}} let param_{{paramName}} = req.headers.get::().map(|header| header.0.clone()); +{{/required}}{{/headerParams}} +{{#queryParams}}{{#-first}} + // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) + let query_params = req.get::().unwrap_or_default(); +{{/-first}} let param_{{paramName}} = query_params.get("{{baseName}}") +{{#required}} .ok_or_else(|| Response::with((status::BadRequest, "Missing required query parameter {{baseName}}".to_string())))? +{{#isListContainer}} .iter().flat_map(|x| x.parse::<{{{baseType}}}>()).collect::>(); +{{/isListContainer}}{{^isListContainer}} .first().ok_or_else(|| Response::with((status::BadRequest, "Required query parameter {{baseName}} was empty".to_string())))? + .parse::<{{{dataType}}}>().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse query parameter {{baseName}} - doesn't match schema: {}", e))))?; +{{/isListContainer}}{{/required}}{{^required}}{{#isListContainer}} .map(|list| list.iter().flat_map(|x| x.parse::<{{{baseType}}}>()).collect::>()); +{{/isListContainer}}{{^isListContainer}} .and_then(|list| list.first()).and_then(|x| x.parse::<{{{dataType}}}>().ok()); +{{/isListContainer}}{{/required}}{{/queryParams}} +{{#bodyParams}}{{#-first}} // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. +{{/-first}}{{#required}} + let param_{{paramName}}_raw = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter {{baseName}} - not valid UTF-8: {}", e))))?; +{{/required}}{{^required}} + let param_{{paramName}}_raw = req.get::().unwrap_or(None); +{{/required}} + let mut unused_elements = Vec::new(); + + let param_{{paramName}} = if let Some(param_{{paramName}}_raw) = param_{{paramName}}_raw { {{#vendorExtensions}}{{#consumesXml}} + let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(param_{{paramName}}_raw.as_bytes());{{/consumesXml}}{{^consumesXml}} + let deserializer = &mut serde_json::Deserializer::from_str(¶m_{{paramName}}_raw);{{/consumesXml}}{{/vendorExtensions}} + + let param_{{paramName}}: Option<{{{dataType}}}> = serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }){{#required}}.map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter {{baseName}} - doesn't match schema: {}", e))))?{{/required}}{{^required}}.unwrap_or(None){{/required}}; + + param_{{paramName}} + } else { + None + };{{#required}} + let param_{{paramName}} = param_{{paramName}}.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter {{baseName}}".to_string())))?{{/required}}; + +{{/bodyParams}} +{{#formParams}} + {{#-first}} + // Form parameters +{{/-first}}{{/formParams}}{{#vendorExtensions}}{{#hasFile}} + // Expecting a multipart form, extract and parse it now. + let mut entries = match Multipart::from_request(req) { + Ok(mut multipart) => { + + match multipart.save().temp() { + SaveResult::Full(entries) => { + Ok(entries) + }, + _ => { + Err(Response::with((status::InternalServerError, format!("Unable to process all message parts")))) + }, + } + }, + Err(e) => { + // Unable to parse as multipart + Err(Response::with((status::BadRequest, format!("Couldn't parse body as multipart")))) + } + }?; + +{{/hasFile}}{{/vendorExtensions}}{{#allParams}}{{#isFormParam}}{{#isFile}} + + let param_{{paramName}} = entries.fields.remove("{{paramName}}"); + + let param_{{paramName}} = match param_{{paramName}} { + Some(body) => { + Ok({let bytes = body.as_bytes(); + {{^required}}Some({{/required}} + Box::new(stream::once(Ok(bytes.to_vec()))) as Box, Error=Error> + Send> + {{^required}}){{/required}}} + ) + } + None => {Err(Response::with((status::BadRequest, format!("Body part not found!"))))} + }?; +{{/isFile}} + let param_{{paramName}} = {{#isFile}}{{^required}}Box::new(future::ok({{/required}}param_{{paramName}}{{^required}})){{/required}};{{/isFile}}{{^isFile}}{{^isContainer}}{{#vendorExtensions}}{{{example}}};{{/vendorExtensions}}{{/isContainer}}{{#isListContainer}}{{#required}}Vec::new();{{/required}}{{^required}}None;{{/required}}{{/isListContainer}}{{#isMapContainer}}None;{{/isMapContainer}}{{/isFile}} + {{/isFormParam}} +{{/allParams}} + + match api.{{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}({{#allParams}}param_{{paramName}}{{#isListContainer}}.as_ref(){{/isListContainer}}, {{/allParams}}context).wait() { + Ok(rsp) => match rsp { +{{#responses}} + {{operationId}}Response::{{message}}{{#dataType}}{{^headers}}(body){{/headers}}{{#headers}}{{#-first}}{ body{{/-first}}{{/headers}}{{/dataType}}{{#headers}}{{#-first}}{{^dataType}}{ {{/dataType}}{{#dataType}}, {{/dataType}}{{/-first}}{{^-first}}, {{/-first}}{{name}}{{#-last}} }{{/-last}}{{/headers}} => { +{{^isFile}} +{{#dataType}}{{#vendorExtensions}}{{#producesXml}} +{{^has_namespace}} let body_string = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize");{{/has_namespace}}{{#has_namespace}} + let mut namespaces = BTreeMap::new(); + // An empty string is used to indicate a global namespace in xmltree. + namespaces.insert("".to_string(), models::namespaces::{{uppercase_data_type}}.clone()); + let body_string = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize");{{/has_namespace}}{{/producesXml}}{{^producesXml}} + let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize");{{/producesXml}}{{/vendorExtensions}}{{/dataType}} + + let mut response = Response::with((status::Status::from_u16({{code}}){{#dataType}}, body_string{{/dataType}}));{{/isFile}}{{#isFile}} body.fold(Vec::new(), |mut body, chunk| { + body.extend(chunk.iter()); + future::ok::, Error>(body) + }) + + // Block whilst waiting for the stream to complete + .wait() + + // It's possible that errors were received in the stream, if this is the case then we can't return a success response to the client and instead must return an internal error. + .map_err(|_| Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + + // Assuming no errors then create an Iron response. + .map(|rsp| { + let mut response = Response::new(); + response.status = Some(status::Status::from_u16({{code}})); + response.body = Some(Box::new(rsp)); +{{/isFile}} +{{#headers}}{{#isFile}} {{/isFile}} header! { (Response{{nameInCamelCase}}, "{{baseName}}") => [{{{datatype}}}] } +{{#isFile}} {{/isFile}} response.headers.set(Response{{nameInCamelCase}}({{name}})); +{{/headers}} + {{#produces}}{{#-first}} +{{#dataType}}{{#isFile}} {{/isFile}} response.headers.set(ContentType(mimetypes::responses::{{#vendorExtensions}}{{uppercase_operation_id}}_{{uppercase_message}}{{/vendorExtensions}}.clone()));{{/dataType}} +{{/-first}}{{/produces}} +{{#isFile}} {{/isFile}} context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); +{{#bodyParams}} if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + }{{/bodyParams}} + {{^isFile}}Ok(response){{/isFile}}{{#isFile}} response + }){{/isFile}} + }, +{{/responses}} + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "{{operationId}}"); +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +} + +/// Middleware to extract authentication data from request +pub struct ExtractAuthData; + +impl BeforeMiddleware for ExtractAuthData { + fn before(&self, req: &mut Request) -> IronResult<()> { + {{#authMethods}} + {{#isBasic}} + { + use hyper::header::{Authorization, Basic, Bearer}; + use std::ops::Deref; + if let Some(basic) = req.headers.get::>() { + req.extensions.insert::(AuthData::Basic(basic.deref().clone())); + return Ok(()); + } + } + {{/isBasic}} + {{#isOAuth}} + { + use hyper::header::{Authorization, Basic, Bearer}; + use std::ops::Deref; + if let Some(bearer) = req.headers.get::>() { + req.extensions.insert::(AuthData::Bearer(bearer.deref().clone())); + return Ok(()); + } + } + {{/isOAuth}} + {{#isApiKey}} + {{#isKeyInHeader}} + { + header! { (ApiKey{{-index}}, "{{keyParamName}}") => [String] } + if let Some(header) = req.headers.get::() { + req.extensions.insert::(AuthData::ApiKey(header.0.clone())); + return Ok(()); + } + } + {{/isKeyInHeader}} + {{#isKeyInQuery}} + { + let header = match req.get_ref::() { + Ok(query) => query.get("{{keyParamName}}").map(|v| v[0].clone()), + _ => None + }; + if let Some(key) = header { + req.extensions.insert::(AuthData::ApiKey(key)); + return Ok(()); + } + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{/authMethods}} + + Ok(()) + } +} diff --git a/modules/swagger-codegen/src/main/resources/rust-server/swagger.mustache b/modules/swagger-codegen/src/main/resources/rust-server/swagger.mustache new file mode 100644 index 00000000000..51560926bba --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust-server/swagger.mustache @@ -0,0 +1 @@ +{{{swagger-yaml}}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/rust/Cargo.mustache b/modules/swagger-codegen/src/main/resources/rust/Cargo.mustache index 614745d5088..f3b94581c17 100644 --- a/modules/swagger-codegen/src/main/resources/rust/Cargo.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/Cargo.mustache @@ -4,14 +4,14 @@ version = "{{{packageVersion}}}" authors = ["Swagger Codegen team and contributors"] [dependencies] -serde = "*" -serde_derive = "*" -serde_yaml = "*" -serde_json = "*" -base64 = "*" -futures = "*" -hyper = "*" -url = "*" +serde = "1.0" +serde_derive = "1.0" +serde_yaml = "0.7" +serde_json = "1.0" +base64 = "~0.7.0" +futures = "0.1.16" +hyper = "0.11.6" +url = "1.5" [dev-dependencies] tokio-core = "*" diff --git a/modules/swagger-codegen/src/main/resources/rust/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/rust/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/rust/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/rust/model.mustache b/modules/swagger-codegen/src/main/resources/rust/model.mustache index 5774bbaffa6..d49cc8dd4dd 100644 --- a/modules/swagger-codegen/src/main/resources/rust/model.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/model.mustache @@ -5,6 +5,9 @@ /// {{{classname}}} : {{{description}}} {{/description}} +#[allow(unused_imports)] +use serde_json::Value; + #[derive(Debug, Serialize, Deserialize)] pub struct {{classname}} { {{#vars}} diff --git a/modules/swagger-codegen/src/main/resources/scala/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/scala/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/scala/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/scala/model.mustache b/modules/swagger-codegen/src/main/resources/scala/model.mustache index 12b635bfb3e..f44fc1e5a78 100644 --- a/modules/swagger-codegen/src/main/resources/scala/model.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/model.mustache @@ -12,7 +12,7 @@ case class {{classname}} ( {{#description}} /* {{{description}}} */ {{/description}} - {{{name}}}: {{^required}}Option[{{/required}}{{datatype}}{{^required}}]{{/required}}{{#hasMore}},{{/hasMore}} + {{{name}}}: {{^required}}Option[{{/required}}{{datatype}}{{^required}}] = None{{/required}}{{#hasMore}},{{/hasMore}} {{/vars}} ) diff --git a/modules/swagger-codegen/src/main/resources/swift/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/swift/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/swift/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/swift3/APIs.mustache b/modules/swagger-codegen/src/main/resources/swift3/APIs.mustache index 9db9ba6de80..557ba31efb6 100644 --- a/modules/swagger-codegen/src/main/resources/swift3/APIs.mustache +++ b/modules/swagger-codegen/src/main/resources/swift3/APIs.mustache @@ -32,10 +32,10 @@ open class APIBase { open class RequestBuilder { var credential: URLCredential? var headers: [String:String] - let parameters: Any? - let isBody: Bool - let method: String - let URLString: String + public let parameters: Any? + public let isBody: Bool + public let method: String + public let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((Progress) -> ())? diff --git a/modules/swagger-codegen/src/main/resources/swift3/api.mustache b/modules/swagger-codegen/src/main/resources/swift3/api.mustache index d60ef7566c7..f32b668c64f 100644 --- a/modules/swagger-codegen/src/main/resources/swift3/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift3/api.mustache @@ -120,7 +120,9 @@ open class {{classname}}: APIBase { */ open class func {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{^secondaryParam}}var{{/secondaryParam}}{{/pathParams}} path = "{{{path}}}"{{#pathParams}} - path = path.replacingOccurrences(of: "{{=<% %>=}}{<%baseName%>}<%={{ }}=%>", with: "\({{paramName}}{{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}})", options: .literal, range: nil){{/pathParams}} + let {{paramName}}PreEscape = "\({{paramName}}{{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}})" + let {{paramName}}PostEscape = {{paramName}}PreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{{=<% %>=}}{<%baseName%>}<%={{ }}=%>", with: {{paramName}}PostEscape, options: .literal, range: nil){{/pathParams}} let URLString = {{projectName}}API.basePath + path {{#bodyParam}} let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() diff --git a/modules/swagger-codegen/src/main/resources/swift3/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/swift3/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/swift3/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/swift3/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/swift4/CodableHelper.mustache b/modules/swagger-codegen/src/main/resources/swift4/CodableHelper.mustache index d56cb0e7348..befa0594f6a 100644 --- a/modules/swagger-codegen/src/main/resources/swift4/CodableHelper.mustache +++ b/modules/swagger-codegen/src/main/resources/swift4/CodableHelper.mustache @@ -11,14 +11,20 @@ public typealias EncodeResult = (data: Data?, error: Error?) open class CodableHelper { + open static var dateformatter: DateFormatter? + open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T : Decodable { var returnedDecodable: T? = nil var returnedError: Error? = nil let decoder = JSONDecoder() - decoder.dataDecodingStrategy = .base64 - if #available(iOS 10.0, *) { - decoder.dateDecodingStrategy = .iso8601 + if let df = self.dateformatter { + decoder.dateDecodingStrategy = .formatted(df) + } else { + decoder.dataDecodingStrategy = .base64 + if #available(iOS 10.0, *) { + decoder.dateDecodingStrategy = .iso8601 + } } do { diff --git a/modules/swagger-codegen/src/main/resources/swift4/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/swift4/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/swift4/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/swift4/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/README.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/README.mustache index 5c46e73275f..c48b905d4cf 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/README.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/README.mustache @@ -40,36 +40,77 @@ In your project: npm link {{npmName}}@{{npmVersion}} ``` -In your angular2 project: +In your Angular project: + ``` -import { DefaultApi } from '{{npmName}}/api/api'; +// without configuring providers +import { ApiModule } from '{{npmName}}'; + @NgModule({ - imports: [], - declarations: [], - exports: [], - providers: [AppModule] + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] }) -export class CoreModule {} +export class AppModule {} ``` + ``` -import { DefaultApi } from '{{npmName}}/api/api'; +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from '{{npmName}}'; + +export function apiConfigFactory (): Configuration => { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from '{{npmName}}'; export class AppComponent { constructor(private apiGateway: DefaultApi) { } } ``` +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + ### Set service base path If different than the generated base path, during app bootstrap, you can provide the base path to your service. ``` -import { BASE_PATH } from './path-to-swagger-gen-service/index'; +import { BASE_PATH } from '{{npmName}}'; bootstrap(AppComponent, [ { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, ]); ``` +or + +``` +import { BASE_PATH } from '{{npmName}}'; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + #### Using @angular/cli First extend your `src/environments/*.ts` files by adding the corresponding base path: @@ -88,11 +129,11 @@ import { environment } from '../environments/environment'; @NgModule({ declarations: [ - AppComponent, + AppComponent ], imports: [ ], - providers: [{ provide: BASE_PATH, useValue: useValue: environment.API_BASE_PATH }], - bootstrap: [AppComponent] + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] }) export class AppModule { } ``` \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/api.module.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/api.module.mustache index d41c4114222..f4ae7435980 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/api.module.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/api.module.mustache @@ -1,6 +1,11 @@ -import { NgModule, ModuleWithProviders } from '@angular/core'; +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; import { CommonModule } from '@angular/common'; +{{#useHttpClient}} +import { HttpClientModule } from '@angular/common/http'; +{{/useHttpClient}} +{{^useHttpClient}} import { HttpModule } from '@angular/http'; +{{/useHttpClient}} import { Configuration } from './configuration'; {{#apiInfo}} @@ -10,16 +15,24 @@ import { {{classname}} } from './{{importPath}}'; {{/apiInfo}} @NgModule({ - imports: [ CommonModule, HttpModule ], + imports: [ CommonModule, {{#useHttpClient}}HttpClientModule{{/useHttpClient}}{{^useHttpClient}}HttpModule{{/useHttpClient}} ], declarations: [], exports: [], - providers: [ {{#apiInfo}}{{#apis}}{{classname}}{{#hasMore}}, {{/hasMore}}{{/apis}}{{/apiInfo}} ] + providers: [ + {{#apiInfo}}{{#apis}}{{classname}}{{#hasMore}}, + {{/hasMore}}{{/apis}}{{/apiInfo}} ] }) export class ApiModule { - public static forConfig(configurationFactory: () => Configuration): ModuleWithProviders { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { return { ngModule: ApiModule, - providers: [ {provide: Configuration, useFactory: configurationFactory}] + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + } + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import your base AppModule only.'); } } } diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/api.service.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/api.service.mustache index ea2b19b7885..debe4c15a54 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/api.service.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/api.service.mustache @@ -73,7 +73,6 @@ export class {{classname}} { return false; } - {{^useHttpClient}} {{! not sure why we used to generate a second method here rather than inlining those few lines of code, but let's keep it for now for the sake of backwards compatiblity. }} @@ -199,19 +198,41 @@ export class {{classname}} { {{/isOAuth}} {{/authMethods}} -{{#bodyParam}} + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + {{#produces}} + '{{{mediaType}}}'{{#hasMore}},{{/hasMore}} + {{/produces}} + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { {{^useHttpClient}} - headers.set('Content-Type', 'application/json'); - + headers.set("Accept", httpHeaderAcceptSelected); {{/useHttpClient}} -{{/bodyParam}} -{{#hasFormParams}} +{{#useHttpClient}} + headers = headers.set("Accept", httpHeaderAcceptSelected); +{{/useHttpClient}} + } + // to determine the Content-Type header let consumes: string[] = [ {{#consumes}} '{{{mediaType}}}'{{#hasMore}},{{/hasMore}} {{/consumes}} ]; +{{#bodyParam}} + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { +{{^useHttpClient}} + headers.set('Content-Type', httpContentTypeSelected); +{{/useHttpClient}} +{{#useHttpClient}} + headers = headers.set("Content-Type", httpContentTypeSelected); +{{/useHttpClient}} + } +{{/bodyParam}} + +{{#hasFormParams}} const canConsumeForm = this.canConsumeForm(consumes); let formParams: { append(param: string, value: any): void; }; @@ -239,8 +260,6 @@ export class {{classname}} { {{/useHttpClient}} } - - {{#formParams}} {{#isListContainer}} if ({{paramName}}) { @@ -263,17 +282,19 @@ export class {{classname}} { {{/hasFormParams}} {{#useHttpClient}} - return this.httpClient.{{httpMethod}}{{^isResponseFile}}{{/isResponseFile}}(`${this.basePath}{{{path}}}`, {{#bodyParam}}{{paramName}}, {{/bodyParam}} - {{#hasFormParams}}convertFormParamsToString ? formParams.toString() : formParams, {{/hasFormParams}}{ + return this.httpClient.{{httpMethod}}{{^isResponseFile}}{{/isResponseFile}}(`${this.basePath}{{{path}}}`,{{#isBodyAllowed}} + {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}{{#hasFormParams}}convertFormParamsToString ? formParams.toString() : formParams{{/hasFormParams}}{{^hasFormParams}}null{{/hasFormParams}}{{/bodyParam}},{{/isBodyAllowed}} + { {{#hasQueryParams}} - params: queryParameters, + params: queryParameters, {{/hasQueryParams}} - headers: headers, + headers: headers, {{#isResponseFile}} - responseType: "blob", + responseType: "blob", {{/isResponseFile}} - withCredentials: this.configuration.withCredentials, - }); + withCredentials: this.configuration.withCredentials, + } + ); {{/useHttpClient}} {{^useHttpClient}} let requestOptions: RequestOptionsArgs = new RequestOptions({ diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/configuration.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/configuration.mustache index 005c3a26df3..d486fc9f97d 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/configuration.mustache @@ -23,4 +23,57 @@ export class Configuration { this.basePath = configurationParameters.basePath; this.withCredentials = configurationParameters.withCredentials; } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param {string[]} contentTypes - the array of content types that are available for selection + * @returns {string} the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string { + if (contentTypes.length == 0) { + return undefined; + } + + let type = contentTypes.find(x => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param {string[]} accepts - the array of content types that are available for selection. + * @returns {string} the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string { + if (accepts.length == 0) { + return undefined; + } + + let type = accepts.find(x => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param {string} mime - MIME (Multipurpose Internet Mail Extensions) + * @return {boolean} True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime != null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } } diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/licenseInfo.mustache index bbd8742e52a..7d61c4ee055 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/licenseInfo.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/licenseInfo.mustache @@ -8,4 +8,4 @@ * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - */ + */ \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/modelEnum.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/modelEnum.mustache index a32e859196f..932d3c0fb47 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/modelEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/modelEnum.mustache @@ -1,2 +1,9 @@ export type {{classname}} = {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}} | {{/-last}}{{/enumVars}}{{/allowableValues}}; +export const {{classname}} = { +{{#allowableValues}} +{{#enumVars}} + {{name}}: {{{value}}} as {{classname}}{{^-last}},{{/-last}} +{{/enumVars}} +{{/allowableValues}} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/modelGeneric.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/modelGeneric.mustache index a8b3c80e364..34e35255d5a 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/modelGeneric.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/modelGeneric.mustache @@ -10,14 +10,19 @@ export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ */ {{/description}} {{name}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; - {{/vars}} }{{#hasEnums}} export namespace {{classname}} { {{#vars}} {{#isEnum}} export type {{enumName}} = {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}} | {{/-last}}{{/enumVars}}{{/allowableValues}}; + export const {{enumName}} = { + {{#allowableValues}} + {{#enumVars}} + {{name}}: {{{value}}} as {{enumName}}{{^-last}},{{/-last}} + {{/enumVars}} + {{/allowableValues}} + } {{/isEnum}} {{/vars}} -}{{/hasEnums}} - +}{{/hasEnums}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/package.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/package.mustache index 9123cb8eb66..2c9810e8559 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/package.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/package.mustache @@ -36,7 +36,7 @@ }{{#npmRepository}},{{/npmRepository}} {{#npmRepository}} "publishConfig": { - "registry":"{{{npmRepository}}}" + "registry": "{{{npmRepository}}}" } {{/npmRepository}} } diff --git a/modules/swagger-codegen/src/main/resources/typescript-angularjs/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/typescript-angularjs/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/typescript-angularjs/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angularjs/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/typescript-aurelia/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/typescript-aurelia/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/typescript-aurelia/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-aurelia/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/typescript-fetch/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-fetch/api.mustache index 2fe42a8dd16..1745c5dcddf 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-fetch/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-fetch/api.mustache @@ -1,8 +1,9 @@ +/// // tslint:disable {{>licenseInfo}} import * as url from "url"; -import * as isomorphicFetch from "isomorphic-fetch"; +import * as portableFetch from "portable-fetch"; import { Configuration } from "./configuration"; const BASE_PATH = "{{{basePath}}}".replace(/\/+$/, ""); @@ -24,7 +25,7 @@ export const COLLECTION_FORMATS = { * @interface FetchAPI */ export interface FetchAPI { - (url: string, init?: any): Promise; + (url: string, init?: any): Promise; } /** @@ -45,7 +46,7 @@ export interface FetchArgs { export class BaseAPI { protected configuration: Configuration; - constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected fetch: FetchAPI = isomorphicFetch) { + constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected fetch: FetchAPI = portableFetch) { if (configuration) { this.configuration = configuration; this.basePath = configuration.basePath || this.basePath; @@ -253,9 +254,9 @@ export const {{classname}}Fp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}any{{/returnType}}> { + {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Response{{/returnType}}> { const localVarFetchArgs = {{classname}}FetchParamCreator(configuration).{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response{{#returnType}}.json(){{/returnType}}; diff --git a/modules/swagger-codegen/src/main/resources/typescript-fetch/custom.d.mustache b/modules/swagger-codegen/src/main/resources/typescript-fetch/custom.d.mustache new file mode 100644 index 00000000000..02f969575e3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-fetch/custom.d.mustache @@ -0,0 +1 @@ +declare module 'portable-fetch'; \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-fetch/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/typescript-fetch/git_push.sh.mustache index 4d6b6157f71..dd342baf078 100755 --- a/modules/swagger-codegen/src/main/resources/typescript-fetch/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-fetch/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/typescript-fetch/package.mustache b/modules/swagger-codegen/src/main/resources/typescript-fetch/package.mustache index a058ae016dd..13ce0937761 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-fetch/package.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-fetch/package.mustache @@ -17,7 +17,7 @@ "postinstall": "npm run build" }, "dependencies": { - "isomorphic-fetch": "^2.2.1" + "portable-fetch": "^3.0.0" }, "devDependencies": { "@types/isomorphic-fetch": "0.0.34", diff --git a/modules/swagger-codegen/src/main/resources/typescript-jquery/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/typescript-jquery/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/typescript-jquery/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-jquery/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache index bbcc9cce84c..eb68f2a0e01 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache @@ -1,5 +1,5 @@ {{>licenseInfo}} -import request = require('request'); +import localVarRequest = require('request'); import http = require('http'); {{^supportsES6}} import Promise = require('bluebird'); @@ -196,7 +196,7 @@ let enumsMap = { {{#hasEnums}} {{#vars}} {{#isEnum}} - "{{datatypeWithEnum}}": {{datatypeWithEnum}}, + {{#isContainer}}"{{classname}}.{{enumName}}": {{classname}}.{{enumName}}{{/isContainer}}{{#isNotContainer}}"{{datatypeWithEnum}}": {{datatypeWithEnum}}{{/isNotContainer}}, {{/isEnum}} {{/vars}} {{/hasEnums}} @@ -216,13 +216,13 @@ export interface Authentication { /** * Apply authentication settings to header and query params. */ - applyToRequest(requestOptions: request.Options): void; + applyToRequest(requestOptions: localVarRequest.Options): void; } export class HttpBasicAuth implements Authentication { public username: string; public password: string; - applyToRequest(requestOptions: request.Options): void { + applyToRequest(requestOptions: localVarRequest.Options): void { requestOptions.auth = { username: this.username, password: this.password } @@ -235,7 +235,7 @@ export class ApiKeyAuth implements Authentication { constructor(private location: string, private paramName: string) { } - applyToRequest(requestOptions: request.Options): void { + applyToRequest(requestOptions: localVarRequest.Options): void { if (this.location == "query") { (requestOptions.qs)[this.paramName] = this.apiKey; } else if (this.location == "header" && requestOptions && requestOptions.headers) { @@ -247,7 +247,7 @@ export class ApiKeyAuth implements Authentication { export class OAuth implements Authentication { public accessToken: string; - applyToRequest(requestOptions: request.Options): void { + applyToRequest(requestOptions: localVarRequest.Options): void { if (requestOptions && requestOptions.headers) { requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; } @@ -257,7 +257,7 @@ export class OAuth implements Authentication { export class VoidAuth implements Authentication { public username: string; public password: string; - applyToRequest(_: request.Options): void { + applyToRequest(_: localVarRequest.Options): void { // Do nothing } } @@ -371,9 +371,9 @@ export class {{classname}} { public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.{{#supportsES6}}IncomingMessage{{/supportsES6}}{{^supportsES6}}ClientResponse{{/supportsES6}}; {{#returnType}}body: {{{returnType}}}; {{/returnType}}{{^returnType}}body?: any; {{/returnType}} }> { const localVarPath = this.basePath + '{{{path}}}'{{#pathParams}} .replace('{' + '{{baseName}}' + '}', encodeURIComponent(String({{paramName}}))){{/pathParams}}; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; {{#allParams}} {{#required}} @@ -386,34 +386,34 @@ export class {{classname}} { {{/allParams}} {{#queryParams}} if ({{paramName}} !== undefined) { - queryParameters['{{baseName}}'] = ObjectSerializer.serialize({{paramName}}, "{{{dataType}}}"); + localVarQueryParameters['{{baseName}}'] = ObjectSerializer.serialize({{paramName}}, "{{{dataType}}}"); } {{/queryParams}} {{#headerParams}} - headerParams['{{baseName}}'] = ObjectSerializer.serialize({{paramName}}, "{{{dataType}}}"); + localVarHeaderParams['{{baseName}}'] = ObjectSerializer.serialize({{paramName}}, "{{{dataType}}}"); {{/headerParams}} - let useFormData = false; + let localVarUseFormData = false; {{#formParams}} if ({{paramName}} !== undefined) { {{#isFile}} - formParams['{{baseName}}'] = {{paramName}}; + localVarFormParams['{{baseName}}'] = {{paramName}}; {{/isFile}} {{^isFile}} - formParams['{{baseName}}'] = ObjectSerializer.serialize({{paramName}}, "{{{dataType}}}"); + localVarFormParams['{{baseName}}'] = ObjectSerializer.serialize({{paramName}}, "{{{dataType}}}"); {{/isFile}} } {{#isFile}} - useFormData = true; + localVarUseFormData = true; {{/isFile}} {{/formParams}} - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: '{{httpMethod}}', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, {{^isResponseFile}} @@ -428,27 +428,27 @@ export class {{classname}} { }; {{#authMethods}} - this.authentications.{{name}}.applyToRequest(requestOptions); + this.authentications.{{name}}.applyToRequest(localVarRequestOptions); {{/authMethods}} - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } 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) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { {{#returnType}} body = ObjectSerializer.deserialize(body, "{{{returnType}}}"); {{/returnType}} - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); diff --git a/modules/swagger-codegen/src/main/resources/typescript-node/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/typescript-node/git_push.sh.mustache index e153ce23ecf..a2d75234837 100755 --- a/modules/swagger-codegen/src/main/resources/typescript-node/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-node/git_push.sh.mustache @@ -36,7 +36,7 @@ git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git else git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java index ff69e4b36bf..a37c72a3efc 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 @@ -328,6 +328,48 @@ public class InlineModelResolverTest { ModelImpl impl = (ModelImpl) body; assertNotNull(impl.getProperties().get("address")); } + + @Test + public void resolveInlineBodyParameterWithRequired() throws Exception { + Swagger swagger = new Swagger(); + + swagger.path("/hello", new Path() + .get(new Operation() + .parameter(new BodyParameter() + .name("body") + .schema(new ModelImpl() + .property("address", new ObjectProperty() + .property("street", new StringProperty() + .required(true)) + .required(true)) + .property("name", new StringProperty()))))); + + new InlineModelResolver().flatten(swagger); + + Operation operation = swagger.getPaths().get("/hello").getGet(); + BodyParameter bp = (BodyParameter)operation.getParameters().get(0); + assertTrue(bp.getSchema() instanceof RefModel); + + Model body = swagger.getDefinitions().get("body"); + assertTrue(body instanceof ModelImpl); + + ModelImpl impl = (ModelImpl) body; + assertNotNull(impl.getProperties().get("address")); + + Property addressProperty = impl.getProperties().get("address"); + assertTrue(addressProperty instanceof RefProperty); + assertTrue(addressProperty.getRequired()); + + Model helloAddress = swagger.getDefinitions().get("hello_address"); + assertTrue(helloAddress instanceof ModelImpl); + + ModelImpl addressImpl = (ModelImpl) helloAddress; + assertNotNull(addressImpl); + + Property streetProperty = addressImpl.getProperties().get("street"); + assertTrue(streetProperty instanceof StringProperty); + assertTrue(streetProperty.getRequired()); + } @Test public void resolveInlineBodyParameterWithTitle() throws Exception { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/haskellhttpclient/HaskellHttpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/haskellhttpclient/HaskellHttpClientOptionsTest.java index b79dbe398e0..050d522229e 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/haskellhttpclient/HaskellHttpClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/haskellhttpclient/HaskellHttpClientOptionsTest.java @@ -36,11 +36,13 @@ public class HaskellHttpClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setGenerateModelConstructors(Boolean.valueOf(HaskellHttpClientOptionsProvider.GENERATE_MODEL_CONSTRUCTORS)); times = 1; + clientCodegen.setGenerateEnums(Boolean.valueOf(HaskellHttpClientOptionsProvider.GENERATE_ENUMS)); + times = 1; clientCodegen.setGenerateFormUrlEncodedInstances(Boolean.valueOf(HaskellHttpClientOptionsProvider.GENERATE_FORM_URLENCODED_INSTANCES)); times = 1; clientCodegen.setGenerateLenses(Boolean.valueOf(HaskellHttpClientOptionsProvider.GENERATE_LENSES)); times = 1; - clientCodegen.setInlineConsumesContentTypes(Boolean.valueOf(HaskellHttpClientOptionsProvider.INLINE_CONSUMES_CONTENT_TYPES)); + clientCodegen.setInlineMimeTypes(Boolean.valueOf(HaskellHttpClientOptionsProvider.INLINE_MIME_TYPES)); times = 1; clientCodegen.setModelDeriving(HaskellHttpClientOptionsProvider.MODEL_DERIVING); times = 1; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/kotlin/KotlinClientCodegenModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/kotlin/KotlinClientCodegenModelTest.java index 23bf434bf3f..83ae1904540 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/kotlin/KotlinClientCodegenModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/kotlin/KotlinClientCodegenModelTest.java @@ -6,6 +6,7 @@ import io.swagger.models.*; import io.swagger.models.properties.*; import org.testng.Assert; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @SuppressWarnings("static-method") @@ -153,5 +154,41 @@ public class KotlinClientCodegenModelTest { Assert.assertFalse(property1.required); Assert.assertTrue(property1.isNotContainer); } + + @DataProvider(name = "modelNames") + public static Object[][] modelNames(){ + return new Object[][] { + { "TestNs.TestClass" , new ModelNameTest("TestNs.TestClass", "TestNsTestClass") }, + { "$", new ModelNameTest("$", "Dollar") }, + { "for", new ModelNameTest("`for`","`for`")}, + { "One operations = ImmutableMap.of("operation", Arrays.asList(codegenOperation)); + + Map objs = ImmutableMap.of("operations", operations, "imports", new ArrayList>()); + + javaClientCodegen.postProcessOperations(objs); + + Assert.assertEquals(Arrays.asList(pathParam1, pathParam2, queryParamRequired, queryParamOptional), codegenOperation.allParams); + Assert.assertTrue(pathParam1.hasMore); + Assert.assertTrue(pathParam2.hasMore); + Assert.assertTrue(queryParamRequired.hasMore); + Assert.assertFalse(queryParamOptional.hasMore); + + } + + private CodegenParameter createPathParam(String name) { + CodegenParameter codegenParameter = createStringParam(name); + codegenParameter.isPathParam = true; + return codegenParameter; + } + + private CodegenParameter createQueryParam(String name, boolean required) { + CodegenParameter codegenParameter = createStringParam(name); + codegenParameter.isQueryParam = true; + codegenParameter.required = required; + return codegenParameter; + } + + private CodegenParameter createStringParam(String name){ + CodegenParameter codegenParameter = new CodegenParameter(); + codegenParameter.paramName = name; + codegenParameter.baseName = name; + codegenParameter.dataType = "String"; + return codegenParameter; + } + + } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/HaskellHttpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/HaskellHttpClientOptionsProvider.java index 1b776f43e13..6a6af94a9ea 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/HaskellHttpClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/HaskellHttpClientOptionsProvider.java @@ -20,10 +20,11 @@ public class HaskellHttpClientOptionsProvider implements OptionsProvider { public static final String DATE_FORMAT = "%Y-%m-%d"; public static final String MODEL_DERIVING = ""; public static final String STRICT_FIELDS = "false"; + public static final String GENERATE_ENUMS = "true"; public static final String GENERATE_FORM_URLENCODED_INSTANCES = "true"; public static final String GENERATE_LENSES = "true"; public static final String GENERATE_MODEL_CONSTRUCTORS = "true"; - public static final String INLINE_CONSUMES_CONTENT_TYPES = "false"; + public static final String INLINE_MIME_TYPES = "false"; public static final String USE_MONAD_LOGGER = "false"; @Override @@ -46,10 +47,11 @@ public class HaskellHttpClientOptionsProvider implements OptionsProvider { .put(HaskellHttpClientCodegen.PROP_DATETIME_FORMAT, DATETIME_FORMAT) .put(HaskellHttpClientCodegen.PROP_DATE_FORMAT, DATE_FORMAT) .put(HaskellHttpClientCodegen.PROP_MODEL_DERIVING, MODEL_DERIVING) + .put(HaskellHttpClientCodegen.PROP_GENERATE_ENUMS, GENERATE_ENUMS) .put(HaskellHttpClientCodegen.PROP_GENERATE_FORM_URLENCODED_INSTANCES, GENERATE_FORM_URLENCODED_INSTANCES) .put(HaskellHttpClientCodegen.PROP_GENERATE_LENSES, GENERATE_LENSES) .put(HaskellHttpClientCodegen.PROP_GENERATE_MODEL_CONSTRUCTORS, GENERATE_MODEL_CONSTRUCTORS) - .put(HaskellHttpClientCodegen.PROP_INLINE_CONSUMES_CONTENT_TYPES, INLINE_CONSUMES_CONTENT_TYPES) + .put(HaskellHttpClientCodegen.PROP_INLINE_MIME_TYPES, INLINE_MIME_TYPES) .put(HaskellHttpClientCodegen.PROP_STRICT_FIELDS, STRICT_FIELDS) .put(HaskellHttpClientCodegen.PROP_USE_MONAD_LOGGER, USE_MONAD_LOGGER) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/KotlinClientCodegenOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/KotlinClientCodegenOptionsProvider.java index e27ab8a68c0..aeca5274aea 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/KotlinClientCodegenOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/KotlinClientCodegenOptionsProvider.java @@ -12,6 +12,7 @@ public class KotlinClientCodegenOptionsProvider implements OptionsProvider { public static final String ARTIFACT_ID = "swagger-kotlin-test"; public static final String GROUP_ID = "io.swagger.tests"; public static final String SOURCE_FOLDER = "./generated/kotlin"; + public static final String ENUM_PROPERTY_NAMING = "camelCase"; @Override public String getLanguage() { @@ -27,6 +28,7 @@ public class KotlinClientCodegenOptionsProvider implements OptionsProvider { .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID) .put(CodegenConstants.GROUP_ID, GROUP_ID) .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER) + .put(CodegenConstants.ENUM_PROPERTY_NAMING, ENUM_PROPERTY_NAMING) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Rust2OptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Rust2OptionsProvider.java new file mode 100644 index 00000000000..68c0d94088d --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Rust2OptionsProvider.java @@ -0,0 +1,22 @@ +package io.swagger.codegen.options; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class Rust2OptionsProvider implements OptionsProvider { + @Override + public String getLanguage() { + return "rust2"; + } + + @Override + public Map createOptions() { + return ImmutableMap.of(); + } + + @Override + public boolean isServer() { + return true; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java index afbb88a02ee..a7f38c02043 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java @@ -44,7 +44,7 @@ public class TypeScriptFetchModelTest { Assert.assertEquals(property1.baseName, "id"); Assert.assertEquals(property1.datatype, "number"); Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.defaultValue, "undefined"); Assert.assertEquals(property1.baseType, "number"); Assert.assertTrue(property1.hasMore); Assert.assertTrue(property1.required); @@ -54,7 +54,7 @@ public class TypeScriptFetchModelTest { Assert.assertEquals(property2.baseName, "name"); Assert.assertEquals(property2.datatype, "string"); Assert.assertEquals(property2.name, "name"); - Assert.assertEquals(property2.defaultValue, "null"); + Assert.assertEquals(property2.defaultValue, "undefined"); Assert.assertEquals(property2.baseType, "string"); Assert.assertTrue(property2.hasMore); Assert.assertTrue(property2.required); @@ -65,7 +65,7 @@ public class TypeScriptFetchModelTest { Assert.assertEquals(property3.complexType, null); Assert.assertEquals(property3.datatype, "Date"); Assert.assertEquals(property3.name, "createdAt"); - Assert.assertEquals(property3.defaultValue, "null"); + Assert.assertEquals(property3.defaultValue, "undefined"); Assert.assertTrue(property3.hasMore); Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); @@ -75,7 +75,7 @@ public class TypeScriptFetchModelTest { Assert.assertEquals(property4.complexType, null); Assert.assertEquals(property4.datatype, "string"); Assert.assertEquals(property4.name, "birthDate"); - Assert.assertEquals(property4.defaultValue, "null"); + Assert.assertEquals(property4.defaultValue, "undefined"); Assert.assertFalse(property4.hasMore); Assert.assertFalse(property4.required); Assert.assertTrue(property4.isNotContainer); @@ -100,7 +100,7 @@ public class TypeScriptFetchModelTest { Assert.assertEquals(property1.baseName, "id"); Assert.assertEquals(property1.datatype, "number"); Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.defaultValue, "undefined"); Assert.assertEquals(property1.baseType, "number"); Assert.assertTrue(property1.hasMore); Assert.assertTrue(property1.required); @@ -133,7 +133,7 @@ public class TypeScriptFetchModelTest { Assert.assertEquals(property1.baseName, "children"); Assert.assertEquals(property1.datatype, "Children"); Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.defaultValue, "undefined"); Assert.assertEquals(property1.baseType, "Children"); Assert.assertFalse(property1.required); Assert.assertTrue(property1.isNotContainer); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java index 310fe4ff90a..de2b7ca1538 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java @@ -44,7 +44,7 @@ public class TypeScriptAngularModelTest { Assert.assertEquals(property1.baseName, "id"); Assert.assertEquals(property1.datatype, "number"); Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.defaultValue, "undefined"); Assert.assertEquals(property1.baseType, "number"); Assert.assertTrue(property1.hasMore); Assert.assertTrue(property1.required); @@ -54,7 +54,7 @@ public class TypeScriptAngularModelTest { Assert.assertEquals(property2.baseName, "name"); Assert.assertEquals(property2.datatype, "string"); Assert.assertEquals(property2.name, "name"); - Assert.assertEquals(property2.defaultValue, "null"); + Assert.assertEquals(property2.defaultValue, "undefined"); Assert.assertEquals(property2.baseType, "string"); Assert.assertTrue(property2.hasMore); Assert.assertTrue(property2.required); @@ -66,7 +66,7 @@ public class TypeScriptAngularModelTest { Assert.assertEquals(property3.datatype, "Date"); Assert.assertEquals(property3.name, "createdAt"); Assert.assertEquals(property3.baseType, "Date"); - Assert.assertEquals(property3.defaultValue, "null"); + Assert.assertEquals(property3.defaultValue, "undefined"); Assert.assertTrue(property3.hasMore); Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); @@ -77,7 +77,7 @@ public class TypeScriptAngularModelTest { Assert.assertEquals(property4.datatype, "string"); Assert.assertEquals(property4.name, "birthDate"); Assert.assertEquals(property4.baseType, "string"); - Assert.assertEquals(property4.defaultValue, "null"); + Assert.assertEquals(property4.defaultValue, "undefined"); Assert.assertFalse(property4.hasMore); Assert.assertFalse(property4.required); Assert.assertTrue(property4.isNotContainer); @@ -102,7 +102,7 @@ public class TypeScriptAngularModelTest { Assert.assertEquals(property1.baseName, "id"); Assert.assertEquals(property1.datatype, "number"); Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.defaultValue, "undefined"); Assert.assertEquals(property1.baseType, "number"); Assert.assertTrue(property1.hasMore); Assert.assertTrue(property1.required); @@ -135,7 +135,7 @@ public class TypeScriptAngularModelTest { Assert.assertEquals(property1.baseName, "children"); Assert.assertEquals(property1.datatype, "Children"); Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.defaultValue, "undefined"); Assert.assertEquals(property1.baseType, "Children"); Assert.assertFalse(property1.required); Assert.assertTrue(property1.isNotContainer); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangularjs/TypeScriptAngularJsModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangularjs/TypeScriptAngularJsModelTest.java index cb0e7bec7f3..ca5b22f5ed3 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangularjs/TypeScriptAngularJsModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangularjs/TypeScriptAngularJsModelTest.java @@ -38,7 +38,7 @@ public class TypeScriptAngularJsModelTest { Assert.assertEquals(property1.baseName, "id"); Assert.assertEquals(property1.datatype, "number"); Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.defaultValue, "undefined"); Assert.assertEquals(property1.baseType, "number"); Assert.assertTrue(property1.hasMore); Assert.assertTrue(property1.required); @@ -48,7 +48,7 @@ public class TypeScriptAngularJsModelTest { Assert.assertEquals(property2.baseName, "name"); Assert.assertEquals(property2.datatype, "string"); Assert.assertEquals(property2.name, "name"); - Assert.assertEquals(property2.defaultValue, "null"); + Assert.assertEquals(property2.defaultValue, "undefined"); Assert.assertEquals(property2.baseType, "string"); Assert.assertTrue(property2.hasMore); Assert.assertTrue(property2.required); @@ -59,7 +59,7 @@ public class TypeScriptAngularJsModelTest { Assert.assertEquals(property3.complexType, null); Assert.assertEquals(property3.datatype, "Date"); Assert.assertEquals(property3.name, "createdAt"); - Assert.assertEquals(property3.defaultValue, "null"); + Assert.assertEquals(property3.defaultValue, "undefined"); Assert.assertTrue(property3.hasMore); Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); @@ -69,7 +69,7 @@ public class TypeScriptAngularJsModelTest { Assert.assertEquals(property4.complexType, null); Assert.assertEquals(property4.datatype, "string"); Assert.assertEquals(property4.name, "birthDate"); - Assert.assertEquals(property4.defaultValue, "null"); + Assert.assertEquals(property4.defaultValue, "undefined"); Assert.assertFalse(property4.hasMore); Assert.assertFalse(property4.required); Assert.assertTrue(property4.isNotContainer); @@ -94,7 +94,7 @@ public class TypeScriptAngularJsModelTest { Assert.assertEquals(property1.baseName, "id"); Assert.assertEquals(property1.datatype, "number"); Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.defaultValue, "undefined"); Assert.assertEquals(property1.baseType, "number"); Assert.assertTrue(property1.hasMore); Assert.assertTrue(property1.required); @@ -127,7 +127,7 @@ public class TypeScriptAngularJsModelTest { Assert.assertEquals(property1.baseName, "children"); Assert.assertEquals(property1.datatype, "models.Children"); Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.defaultValue, "undefined"); Assert.assertEquals(property1.baseType, "models.Children"); Assert.assertFalse(property1.required); Assert.assertTrue(property1.isNotContainer); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java index cc8329b8f7f..bc81d9d590a 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java @@ -38,7 +38,7 @@ public class TypeScriptNodeModelTest { Assert.assertEquals(property1.baseName, "id"); Assert.assertEquals(property1.datatype, "number"); Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.defaultValue, "undefined"); Assert.assertEquals(property1.baseType, "number"); Assert.assertTrue(property1.hasMore); Assert.assertTrue(property1.required); @@ -48,7 +48,7 @@ public class TypeScriptNodeModelTest { Assert.assertEquals(property2.baseName, "name"); Assert.assertEquals(property2.datatype, "string"); Assert.assertEquals(property2.name, "name"); - Assert.assertEquals(property2.defaultValue, "null"); + Assert.assertEquals(property2.defaultValue, "undefined"); Assert.assertEquals(property2.baseType, "string"); Assert.assertTrue(property2.hasMore); Assert.assertTrue(property2.required); @@ -59,7 +59,7 @@ public class TypeScriptNodeModelTest { Assert.assertEquals(property3.complexType, null); Assert.assertEquals(property3.datatype, "Date"); Assert.assertEquals(property3.name, "createdAt"); - Assert.assertEquals(property3.defaultValue, "null"); + Assert.assertEquals(property3.defaultValue, "undefined"); Assert.assertTrue(property3.hasMore); Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); @@ -69,7 +69,7 @@ public class TypeScriptNodeModelTest { Assert.assertEquals(property4.complexType, null); Assert.assertEquals(property4.datatype, "string"); Assert.assertEquals(property4.name, "birthDate"); - Assert.assertEquals(property4.defaultValue, "null"); + Assert.assertEquals(property4.defaultValue, "undefined"); Assert.assertFalse(property4.hasMore); Assert.assertFalse(property4.required); Assert.assertTrue(property4.isNotContainer); @@ -94,7 +94,7 @@ public class TypeScriptNodeModelTest { Assert.assertEquals(property1.baseName, "id"); Assert.assertEquals(property1.datatype, "number"); Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.defaultValue, "undefined"); Assert.assertEquals(property1.baseType, "number"); Assert.assertTrue(property1.hasMore); Assert.assertTrue(property1.required); diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithOptionalInlineEnum.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithOptionalInlineEnum.cs index 6ab512ac960..1acd88ef379 100644 --- a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithOptionalInlineEnum.cs +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithOptionalInlineEnum.cs @@ -41,43 +41,43 @@ namespace IO.Swagger.Model /// Enum Sun for value: sun /// [EnumMember(Value = "sun")] - Sun, + Sun = 1, /// /// Enum Mon for value: mon /// [EnumMember(Value = "mon")] - Mon, + Mon = 2, /// /// Enum Tue for value: tue /// [EnumMember(Value = "tue")] - Tue, + Tue = 3, /// /// Enum Wed for value: wed /// [EnumMember(Value = "wed")] - Wed, + Wed = 4, /// /// Enum Thu for value: thu /// [EnumMember(Value = "thu")] - Thu, + Thu = 5, /// /// Enum Fri for value: fri /// [EnumMember(Value = "fri")] - Fri, + Fri = 6, /// /// Enum Sat for value: sat /// [EnumMember(Value = "sat")] - Sat + Sat = 7 } /// diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithRequiredInlineEnum.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithRequiredInlineEnum.cs index a131c7e774a..ac6c2009b41 100644 --- a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithRequiredInlineEnum.cs +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithRequiredInlineEnum.cs @@ -41,43 +41,43 @@ namespace IO.Swagger.Model /// Enum Sun for value: sun /// [EnumMember(Value = "sun")] - Sun, + Sun = 1, /// /// Enum Mon for value: mon /// [EnumMember(Value = "mon")] - Mon, + Mon = 2, /// /// Enum Tue for value: tue /// [EnumMember(Value = "tue")] - Tue, + Tue = 3, /// /// Enum Wed for value: wed /// [EnumMember(Value = "wed")] - Wed, + Wed = 4, /// /// Enum Thu for value: thu /// [EnumMember(Value = "thu")] - Thu, + Thu = 5, /// /// Enum Fri for value: fri /// [EnumMember(Value = "fri")] - Fri, + Fri = 6, /// /// Enum Sat for value: sat /// [EnumMember(Value = "sat")] - Sat + Sat = 7 } /// diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/WeekDays.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/WeekDays.cs index 92d45a5c028..5c449b6cc0e 100644 --- a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/WeekDays.cs +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/WeekDays.cs @@ -37,43 +37,43 @@ namespace IO.Swagger.Model /// Enum Sun for value: sun /// [EnumMember(Value = "sun")] - Sun, + Sun = 1, /// /// Enum Mon for value: mon /// [EnumMember(Value = "mon")] - Mon, + Mon = 2, /// /// Enum Tue for value: tue /// [EnumMember(Value = "tue")] - Tue, + Tue = 3, /// /// Enum Wed for value: wed /// [EnumMember(Value = "wed")] - Wed, + Wed = 4, /// /// Enum Thu for value: thu /// [EnumMember(Value = "thu")] - Thu, + Thu = 5, /// /// Enum Fri for value: fri /// [EnumMember(Value = "fri")] - Fri, + Fri = 6, /// /// Enum Sat for value: sat /// [EnumMember(Value = "sat")] - Sat + Sat = 7 } } diff --git a/pom.xml b/pom.xml index d063b8780d4..06e025965be 100644 --- a/pom.xml +++ b/pom.xml @@ -685,7 +685,7 @@ - typescript-angular-client + typescript-angularjs-client env @@ -837,18 +837,15 @@ - - samples/server/petstore/scalatra - + samples/client/petstore/php/SwaggerClient-php samples/client/petstore/ruby samples/client/petstore/scala samples/client/petstore/akka-scala samples/client/petstore/javascript samples/client/petstore/python - - + samples/client/petstore/python-tornado samples/client/petstore/typescript-fetch/builds/default samples/client/petstore/typescript-fetch/builds/es6-target samples/client/petstore/typescript-fetch/builds/with-npm-version @@ -858,19 +855,10 @@ samples/client/petstore/typescript-angularjs--> - samples/client/petstore/typescript-angular-v2/npm + samples/client/petstore/typescript-angular-v4/npm - - + samples/client/petstore/typescript-angular-v4.3/npm + diff --git a/pom.xml.bash b/pom.xml.bash index 6d43fe6829d..02cd49a802a 100644 --- a/pom.xml.bash +++ b/pom.xml.bash @@ -685,7 +685,7 @@ - typescript-angular-client + typescript-angularjs-client env diff --git a/pom.xml.circleci b/pom.xml.circleci index d1b7b94572c..9de37dea1a7 100644 --- a/pom.xml.circleci +++ b/pom.xml.circleci @@ -656,7 +656,7 @@ - typescript-angular-client + typescript-angularjs-client env @@ -837,6 +837,7 @@ samples/client/petstore/java/resttemplate-withXml samples/client/petstore/java/vertx samples/client/petstore/java/resteasy + samples/client/petstore/java/google-api-client samples/client/petstore/kotlin/ samples/client/petstore/go diff --git a/pom.xml.shippable b/pom.xml.shippable index a73d38ae9aa..3b033834d4f 100644 --- a/pom.xml.shippable +++ b/pom.xml.shippable @@ -685,7 +685,7 @@ - typescript-angular-client + typescript-angularjs-client env diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index 861d7a3f01a..7e15b474c44 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -406,7 +406,7 @@ public class ApiClient { } /** - * Set the tempoaray folder path (for downloading files) + * Set the temporary folder path (for downloading files) * * @param tempFolderPath Temporary folder path * @return ApiClient @@ -428,6 +428,7 @@ public class ApiClient { /** * Sets the connect timeout (in milliseconds). * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. * * @param connectionTimeout connection timeout in milliseconds * @return Api client @@ -437,6 +438,50 @@ public class ApiClient { return this; } + /** + * Get read timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getReadTimeout() { + return httpClient.getReadTimeout(); + } + + /** + * Sets the read timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + * + * @param readTimeout read timeout in milliseconds + * @return Api client + */ + public ApiClient setReadTimeout(int readTimeout) { + httpClient.setReadTimeout(readTimeout, TimeUnit.MILLISECONDS); + return this; + } + + /** + * Get write timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getWriteTimeout() { + return httpClient.getWriteTimeout(); + } + + /** + * Sets the write timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + * + * @param writeTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setWriteTimeout(int writeTimeout) { + httpClient.setWriteTimeout(writeTimeout, TimeUnit.MILLISECONDS); + return this; + } + /** * Format the given parameter object into string. * diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java index d822adb8689..99f88febbd4 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java @@ -63,7 +63,7 @@ public class FakeApi { */ public com.squareup.okhttp.Call testCodeInjectEndRnNRCall(String testCodeInjectEndRnNR, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/fake"; @@ -103,18 +103,14 @@ public class FakeApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call testCodeInjectEndRnNRValidateBeforeCall(String testCodeInjectEndRnNR, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - + com.squareup.okhttp.Call call = testCodeInjectEndRnNRCall(testCodeInjectEndRnNR, progressListener, progressRequestListener); return call; - - - - } /** diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/README.md b/samples/client/petstore-security-test/php/SwaggerClient-php/README.md index 3c73985e40c..1f5c98d4da7 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/README.md +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/README.md @@ -56,11 +56,15 @@ Please follow the [installation procedure](#installation--usage) and then run th testCodeInjectEndRnNR($test_code_inject____end____rn_n_r); + $apiInstance->testCodeInjectEndRnNR($test_code_inject____end____rn_n_r); } catch (Exception $e) { echo 'Exception when calling FakeApi->testCodeInjectEndRnNR: ', $e->getMessage(), PHP_EOL; } diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/docs/Api/FakeApi.md b/samples/client/petstore-security-test/php/SwaggerClient-php/docs/Api/FakeApi.md index 445abaf0855..6b76f9e222c 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/docs/Api/FakeApi.md +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/docs/Api/FakeApi.md @@ -17,11 +17,15 @@ To test code injection *_/ ' \" =end -- \\r\\n \\n \\r testCodeInjectEndRnNR($test_code_inject____end____rn_n_r); + $apiInstance->testCodeInjectEndRnNR($test_code_inject____end____rn_n_r); } catch (Exception $e) { echo 'Exception when calling FakeApi->testCodeInjectEndRnNR: ', $e->getMessage(), PHP_EOL; } diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php index 16ad474af26..bf65cbac5d0 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -32,6 +32,7 @@ use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; +use GuzzleHttp\RequestOptions; use Swagger\Client\ApiException; use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; @@ -113,9 +114,9 @@ class FakeApi $request = $this->testCodeInjectEndRnNRRequest($test_code_inject____end____rn_n_r); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", @@ -184,7 +185,7 @@ class FakeApi $request = $this->testCodeInjectEndRnNRRequest($test_code_inject____end____rn_n_r); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; @@ -294,4 +295,22 @@ class FakeApi ); } + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } } diff --git a/samples/client/petstore-security-test/python/docs/FakeApi.md b/samples/client/petstore-security-test/python/docs/FakeApi.md index e35d744ef36..ba03f0fad17 100644 --- a/samples/client/petstore-security-test/python/docs/FakeApi.md +++ b/samples/client/petstore-security-test/python/docs/FakeApi.md @@ -12,7 +12,7 @@ Method | HTTP request | Description To test code injection */ ' \" =end -- \\r\\n \\n \\r -### Example +### Example ```python from __future__ import print_function import time @@ -24,7 +24,7 @@ from pprint import pprint api_instance = petstore_api.FakeApi() test_code_inject____end____rn_n_r = 'test_code_inject____end____rn_n_r_example' # str | To test code injection */ ' \" =end -- \\r\\n \\n \\r (optional) -try: +try: # To test code injection */ ' \" =end -- \\r\\n \\n \\r api_instance.test_code_inject____end__rn_n_r(test_code_inject____end____rn_n_r=test_code_inject____end____rn_n_r) except ApiException as e: diff --git a/samples/client/petstore-security-test/python/petstore_api/__init__.py b/samples/client/petstore-security-test/python/petstore_api/__init__.py index 0573fa17d0d..af5957b1a04 100644 --- a/samples/client/petstore-security-test/python/petstore_api/__init__.py +++ b/samples/client/petstore-security-test/python/petstore_api/__init__.py @@ -1,9 +1,11 @@ # coding: utf-8 +# flake8: noqa + """ Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- # noqa: E501 OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r @@ -13,13 +15,11 @@ from __future__ import absolute_import -# import models into sdk package -from .models.model_return import ModelReturn - # import apis into sdk package -from .apis.fake_api import FakeApi +from petstore_api.api.fake_api import FakeApi # import ApiClient -from .api_client import ApiClient - -from .configuration import Configuration +from petstore_api.api_client import ApiClient +from petstore_api.configuration import Configuration +# import models into sdk package +from petstore_api.models.model_return import ModelReturn diff --git a/samples/client/petstore-security-test/python/petstore_api/api/__init__.py b/samples/client/petstore-security-test/python/petstore_api/api/__init__.py new file mode 100644 index 00000000000..a2a6f73f45c --- /dev/null +++ b/samples/client/petstore-security-test/python/petstore_api/api/__init__.py @@ -0,0 +1,6 @@ +from __future__ import absolute_import + +# flake8: noqa + +# import apis into api package +from petstore_api.api.fake_api import FakeApi diff --git a/samples/client/petstore-security-test/python/petstore_api/api/fake_api.py b/samples/client/petstore-security-test/python/petstore_api/api/fake_api.py new file mode 100644 index 00000000000..0972042d7be --- /dev/null +++ b/samples/client/petstore-security-test/python/petstore_api/api/fake_api.py @@ -0,0 +1,127 @@ +# coding: utf-8 + +""" + Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- # noqa: E501 + + OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r + Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r + Generated by: https://github.com/swagger-api/swagger-codegen.git +""" + + +from __future__ import absolute_import + +import re # noqa: F401 + +# python 2 and python 3 compatibility library +import six + +from petstore_api.api_client import ApiClient + + +class FakeApi(object): + """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 + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def test_code_inject____end__rn_n_r(self, **kwargs): # noqa: E501 + """To test code injection */ ' \" =end -- \\r\\n \\n \\r # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async=True + >>> thread = api.test_code_inject____end__rn_n_r(async=True) + >>> result = thread.get() + + :param async bool + :param str test_code_inject____end____rn_n_r: To test code injection */ ' \" =end -- \\r\\n \\n \\r + :return: None + If the method is called asynchronously, + returns the request thread. + """ + kwargs['_return_http_data_only'] = True + if kwargs.get('async'): + return self.test_code_inject____end__rn_n_r_with_http_info(**kwargs) # noqa: E501 + else: + (data) = self.test_code_inject____end__rn_n_r_with_http_info(**kwargs) # noqa: E501 + return data + + def test_code_inject____end__rn_n_r_with_http_info(self, **kwargs): # noqa: E501 + """To test code injection */ ' \" =end -- \\r\\n \\n \\r # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async=True + >>> thread = api.test_code_inject____end__rn_n_r_with_http_info(async=True) + >>> result = thread.get() + + :param async bool + :param str test_code_inject____end____rn_n_r: To test code injection */ ' \" =end -- \\r\\n \\n \\r + :return: None + If the method is called asynchronously, + returns the request thread. + """ + + all_params = ['test_code_inject____end____rn_n_r'] # noqa: E501 + all_params.append('async') + all_params.append('_return_http_data_only') + all_params.append('_preload_content') + all_params.append('_request_timeout') + + params = locals() + for key, val in six.iteritems(params['kwargs']): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method test_code_inject____end__rn_n_r" % key + ) + params[key] = val + del params['kwargs'] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + if 'test_code_inject____end____rn_n_r' in params: + form_params.append(('test code inject */ ' " =end -- \r\n \n \r', params['test_code_inject____end____rn_n_r'])) # noqa: E501 + + body_params = None + # HTTP header `Accept` + header_params['Accept'] = self.api_client.select_header_accept( + ['application/json', '*/ \" =end -- ']) # noqa: E501 + + # HTTP header `Content-Type` + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json', '*/ \" =end -- ']) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + '/fake', 'PUT', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore-security-test/python/petstore_api/api_client.py b/samples/client/petstore-security-test/python/petstore_api/api_client.py index ea9f0084ba5..360016c2565 100644 --- a/samples/client/petstore-security-test/python/petstore_api/api_client.py +++ b/samples/client/petstore-security-test/python/petstore_api/api_client.py @@ -2,7 +2,7 @@ """ Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- # noqa: E501 OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r @@ -11,27 +11,25 @@ from __future__ import absolute_import -import os -import re +import datetime import json import mimetypes -import tempfile from multiprocessing.pool import ThreadPool - -from datetime import date, datetime +import os +import re +import tempfile # python 2 and python 3 compatibility library -from six import PY3, integer_types, iteritems, text_type +import six from six.moves.urllib.parse import quote -from . import models -from .configuration import Configuration -from .rest import ApiException, RESTClientObject +from petstore_api.configuration import Configuration +import petstore_api.models +from petstore_api import rest class ApiClient(object): - """ - Generic API client for Swagger client library builds. + """Generic API client for Swagger client library builds. Swagger generic API client. This client handles the client- server communication, and is invariant across implementations. Specifics of @@ -42,64 +40,63 @@ class ApiClient(object): Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. - :param host: The base path for the server to call. + :param configuration: .Configuration object for this client :param header_name: a header to pass when making calls to the API. - :param header_value: a header value to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API """ - PRIMITIVE_TYPES = (float, bool, bytes, text_type) + integer_types + PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types NATIVE_TYPES_MAPPING = { 'int': int, - 'long': int if PY3 else long, + 'long': int if six.PY3 else long, # noqa: F821 'float': float, 'str': str, 'bool': bool, - 'date': date, - 'datetime': datetime, + 'date': datetime.date, + 'datetime': datetime.datetime, 'object': object, } - def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None): + def __init__(self, configuration=None, header_name=None, header_value=None, + cookie=None): if configuration is None: configuration = Configuration() self.configuration = configuration self.pool = ThreadPool() - self.rest_client = RESTClientObject(configuration) + self.rest_client = rest.RESTClientObject(configuration) self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value self.cookie = cookie # Set default User-Agent. self.user_agent = 'Swagger-Codegen/1.0.0/python' - + def __del__(self): self.pool.close() self.pool.join() @property def user_agent(self): - """ - Gets user agent. - """ + """User agent for this API client""" return self.default_headers['User-Agent'] @user_agent.setter def user_agent(self, value): - """ - Sets user agent. - """ self.default_headers['User-Agent'] = value def set_default_header(self, header_name, header_value): self.default_headers[header_name] = header_value - def __call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_type=None, auth_settings=None, - _return_http_data_only=None, collection_formats=None, _preload_content=True, - _request_timeout=None): + def __call_api( + self, resource_path, method, path_params=None, + query_params=None, header_params=None, body=None, post_params=None, + files=None, response_type=None, auth_settings=None, + _return_http_data_only=None, collection_formats=None, + _preload_content=True, _request_timeout=None): config = self.configuration @@ -121,7 +118,9 @@ class ApiClient(object): for k, v in path_params: # specified safe chars, encode everything resource_path = resource_path.replace( - '{%s}' % k, quote(str(v), safe=config.safe_chars_for_path_param)) + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) # query parameters if query_params: @@ -147,12 +146,11 @@ class ApiClient(object): url = self.configuration.host + resource_path # perform request and return response - response_data = self.request(method, url, - query_params=query_params, - headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) + response_data = self.request( + method, url, query_params=query_params, headers=header_params, + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout) self.last_response = response_data @@ -167,11 +165,11 @@ class ApiClient(object): if _return_http_data_only: return (return_data) else: - return (return_data, response_data.status, response_data.getheaders()) + return (return_data, response_data.status, + response_data.getheaders()) def sanitize_for_serialization(self, obj): - """ - Builds a JSON POST object. + """Builds a JSON POST object. If obj is None, return None. If obj is str, int, long, float, bool, return directly. @@ -194,7 +192,7 @@ class ApiClient(object): elif isinstance(obj, tuple): return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj) - elif isinstance(obj, (datetime, date)): + elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() if isinstance(obj, dict): @@ -206,15 +204,14 @@ class ApiClient(object): # Convert attribute name to json key in # model definition for request. obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in iteritems(obj.swagger_types) + for attr, _ in six.iteritems(obj.swagger_types) if getattr(obj, attr) is not None} return {key: self.sanitize_for_serialization(val) - for key, val in iteritems(obj_dict)} + for key, val in six.iteritems(obj_dict)} def deserialize(self, response, response_type): - """ - Deserializes response into an object. + """Deserializes response into an object. :param response: RESTResponse object to be deserialized. :param response_type: class literal for @@ -236,8 +233,7 @@ class ApiClient(object): return self.__deserialize(data, response_type) def __deserialize(self, data, klass): - """ - Deserializes dict, list, str into an object. + """Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. @@ -256,21 +252,21 @@ class ApiClient(object): if klass.startswith('dict('): sub_kls = re.match('dict\(([^,]*), (.*)\)', klass).group(2) return {k: self.__deserialize(v, sub_kls) - for k, v in iteritems(data)} + for k, v in six.iteritems(data)} # convert str to class if klass in self.NATIVE_TYPES_MAPPING: klass = self.NATIVE_TYPES_MAPPING[klass] else: - klass = getattr(models, klass) + klass = getattr(petstore_api.models, klass) if klass in self.PRIMITIVE_TYPES: return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) - elif klass == date: + elif klass == datetime.date: return self.__deserialize_date(data) - elif klass == datetime: + elif klass == datetime.datetime: return self.__deserialize_datatime(data) else: return self.__deserialize_model(data, klass) @@ -279,10 +275,10 @@ class ApiClient(object): path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, async=None, - _return_http_data_only=None, collection_formats=None, _preload_content=True, - _request_timeout=None): - """ - Makes the HTTP request (synchronous) and return the deserialized data. + _return_http_data_only=None, collection_formats=None, + _preload_content=True, _request_timeout=None): + """Makes the HTTP request (synchronous) and returns deserialized data. + To make an async request, set the async parameter. :param resource_path: Path to method endpoint. @@ -299,13 +295,17 @@ class ApiClient(object): :param files dict: key -> filename, value -> filepath, for `multipart/form-data`. :param async bool: execute request asynchronously - :param _return_http_data_only: response data without head status code and headers + :param _return_http_data_only: response data without head status code + and headers :param collection_formats: dict of collection formats for path, query, header, and post parameters. - :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without - reading/decoding response data. Default is True. - :param _request_timeout: timeout setting for this request. If one number provided, it will be total request - timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: If async parameter is True, the request will be called asynchronously. @@ -318,22 +318,23 @@ class ApiClient(object): path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, - _return_http_data_only, collection_formats, _preload_content, _request_timeout) + _return_http_data_only, collection_formats, + _preload_content, _request_timeout) else: - thread = self.pool.apply_async(self.__call_api, (resource_path, method, - path_params, query_params, + thread = self.pool.apply_async(self.__call_api, (resource_path, + method, path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, _return_http_data_only, - collection_formats, _preload_content, _request_timeout)) + collection_formats, + _preload_content, _request_timeout)) return thread def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, _request_timeout=None): - """ - Makes the HTTP request using RESTClient. - """ + post_params=None, body=None, _preload_content=True, + _request_timeout=None): + """Makes the HTTP request using RESTClient.""" if method == "GET": return self.rest_client.GET(url, query_params=query_params, @@ -392,8 +393,7 @@ class ApiClient(object): ) def parameters_to_tuples(self, params, collection_formats): - """ - Get parameters as list of tuples, formatting collections. + """Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or list of two-tuples :param dict collection_formats: Parameter collection formats @@ -402,7 +402,7 @@ class ApiClient(object): new_params = [] if collection_formats is None: collection_formats = {} - for k, v in iteritems(params) if isinstance(params, dict) else params: + for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501 if k in collection_formats: collection_format = collection_formats[k] if collection_format == 'multi': @@ -423,8 +423,7 @@ class ApiClient(object): return new_params def prepare_post_parameters(self, post_params=None, files=None): - """ - Builds form parameters. + """Builds form parameters. :param post_params: Normal form parameters. :param files: File parameters. @@ -436,7 +435,7 @@ class ApiClient(object): params = post_params if files: - for k, v in iteritems(files): + for k, v in six.iteritems(files): if not v: continue file_names = v if type(v) is list else [v] @@ -444,15 +443,15 @@ class ApiClient(object): with open(n, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() - mimetype = mimetypes.\ - guess_type(filename)[0] or 'application/octet-stream' - params.append(tuple([k, tuple([filename, filedata, mimetype])])) + mimetype = (mimetypes.guess_type(filename)[0] or + 'application/octet-stream') + params.append( + tuple([k, tuple([filename, filedata, mimetype])])) return params def select_header_accept(self, accepts): - """ - Returns `Accept` based on an array of accepts provided. + """Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json). @@ -468,8 +467,7 @@ class ApiClient(object): return ', '.join(accepts) def select_header_content_type(self, content_types): - """ - Returns `Content-Type` based on an array of content_types provided. + """Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. :return: Content-Type (e.g. application/json). @@ -485,8 +483,7 @@ class ApiClient(object): return content_types[0] def update_params_for_auth(self, headers, querys, auth_settings): - """ - Updates header and query params based on authentication setting. + """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. :param querys: Query parameters tuple list to be updated. @@ -510,7 +507,8 @@ class ApiClient(object): ) def __deserialize_file(self, response): - """ + """Deserializes body to file + Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. @@ -523,19 +521,17 @@ class ApiClient(object): content_disposition = response.getheader("Content-Disposition") if content_disposition: - filename = re.\ - search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).\ - group(1) + filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition).group(1) path = os.path.join(os.path.dirname(path), filename) - with open(path, "w") as f: + with open(path, "wb") as f: f.write(response.data) return path def __deserialize_primitive(self, data, klass): - """ - Deserializes string to primitive type. + """Deserializes string to primitive type. :param data: str. :param klass: class literal. @@ -545,21 +541,19 @@ class ApiClient(object): try: return klass(data) except UnicodeEncodeError: - return unicode(data) + return six.u(data) except TypeError: return data def __deserialize_object(self, value): - """ - Return a original value. + """Return a original value. :return: object. """ return value def __deserialize_date(self, string): - """ - Deserializes string to date. + """Deserializes string to date. :param string: str. :return: date. @@ -570,14 +564,13 @@ class ApiClient(object): except ImportError: return string except ValueError: - raise ApiException( + raise rest.ApiException( status=0, - reason="Failed to parse `{0}` into a date object".format(string) + reason="Failed to parse `{0}` as date object".format(string) ) def __deserialize_datatime(self, string): - """ - Deserializes string to datetime. + """Deserializes string to datetime. The string should be in iso8601 datetime format. @@ -590,32 +583,32 @@ class ApiClient(object): except ImportError: return string except ValueError: - raise ApiException( + raise rest.ApiException( status=0, reason=( - "Failed to parse `{0}` into a datetime object" + "Failed to parse `{0}` as datetime object" .format(string) ) ) def __deserialize_model(self, data, klass): - """ - Deserializes list or dict to model. + """Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object. """ - if not klass.swagger_types and not hasattr(klass, 'get_real_child_model'): + if not klass.swagger_types and not hasattr(klass, + 'get_real_child_model'): return data kwargs = {} if klass.swagger_types is not None: - for attr, attr_type in iteritems(klass.swagger_types): - if data is not None \ - and klass.attribute_map[attr] in data \ - and isinstance(data, (list, dict)): + for attr, attr_type in six.iteritems(klass.swagger_types): + if (data is not None and + klass.attribute_map[attr] in data and + isinstance(data, (list, dict))): value = data[klass.attribute_map[attr]] kwargs[attr] = self.__deserialize(value, attr_type) diff --git a/samples/client/petstore-security-test/python/petstore_api/configuration.py b/samples/client/petstore-security-test/python/petstore_api/configuration.py index da9d119a09e..c5a442ee576 100644 --- a/samples/client/petstore-security-test/python/petstore_api/configuration.py +++ b/samples/client/petstore-security-test/python/petstore_api/configuration.py @@ -3,7 +3,7 @@ """ Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- # noqa: E501 OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r @@ -13,24 +13,23 @@ from __future__ import absolute_import -import urllib3 - import copy import logging import multiprocessing import sys +import urllib3 -from six import iteritems -from six import with_metaclass +import six from six.moves import http_client as httplib + class TypeWithDefault(type): def __init__(cls, name, bases, dct): super(TypeWithDefault, cls).__init__(name, bases, dct) cls._default = None def __call__(cls): - if cls._default == None: + if cls._default is None: cls._default = type.__call__(cls) return copy.copy(cls._default) @@ -38,17 +37,15 @@ class TypeWithDefault(type): cls._default = copy.copy(default) -class Configuration(with_metaclass(TypeWithDefault, object)): - """ - NOTE: This class is auto generated by the swagger code generator program. +class Configuration(six.with_metaclass(TypeWithDefault, object)): + """NOTE: This class is auto generated by the swagger code generator program. + Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. """ def __init__(self): - """ - Constructor - """ + """Constructor""" # Default Base url self.host = "https://petstore.swagger.io */ ' \" =end -- \\r\\n \\n \\r/v2 */ ' \" =end -- \\r\\n \\n \\r" # Temp file folder for downloading files @@ -83,7 +80,8 @@ class Configuration(with_metaclass(TypeWithDefault, object)): self.debug = False # SSL/TLS verification - # Set this to false to skip verifying SSL certificate when calling API from https server. + # Set this to false to skip verifying SSL certificate when calling API + # from https server. self.verify_ssl = True # Set this to customize the certificate file to verify the peer. self.ssl_ca_cert = None @@ -101,7 +99,6 @@ class Configuration(with_metaclass(TypeWithDefault, object)): # cpu_count * 5 is used as default value to increase performance. self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - # Proxy URL self.proxy = None # Safe chars for path_param @@ -109,18 +106,22 @@ class Configuration(with_metaclass(TypeWithDefault, object)): @property def logger_file(self): - """ - Gets the logger_file. + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str """ return self.__logger_file @logger_file.setter def logger_file(self, value): - """ - Sets the logger_file. + """The logger file. - If the logger_file is None, then add stream handler and remove file handler. - Otherwise, add file handler and remove stream handler. + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. :param value: The logger_file path. :type: str @@ -131,7 +132,7 @@ class Configuration(with_metaclass(TypeWithDefault, object)): # then add file handler and remove stream handler. self.logger_file_handler = logging.FileHandler(self.__logger_file) self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.addHandler(self.logger_file_handler) if self.logger_stream_handler: logger.removeHandler(self.logger_stream_handler) @@ -140,22 +141,23 @@ class Configuration(with_metaclass(TypeWithDefault, object)): # then add stream handler and remove file handler. self.logger_stream_handler = logging.StreamHandler() self.logger_stream_handler.setFormatter(self.logger_formatter) - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.addHandler(self.logger_stream_handler) if self.logger_file_handler: logger.removeHandler(self.logger_file_handler) @property def debug(self): - """ - Gets the debug status. + """Debug status + + :param value: The debug status, True or False. + :type: bool """ return self.__debug @debug.setter def debug(self, value): - """ - Sets the debug status. + """Debug status :param value: The debug status, True or False. :type: bool @@ -163,29 +165,32 @@ class Configuration(with_metaclass(TypeWithDefault, object)): self.__debug = value if self.__debug: # if debug status is True, turn on debug logging - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.setLevel(logging.DEBUG) # turn on httplib debug httplib.HTTPConnection.debuglevel = 1 else: # if debug status is False, turn off debug logging, # setting log level to default `logging.WARNING` - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.setLevel(logging.WARNING) # turn off httplib debug httplib.HTTPConnection.debuglevel = 0 @property def logger_format(self): - """ - Gets the logger_format. + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str """ return self.__logger_format @logger_format.setter def logger_format(self, value): - """ - Sets the logger_format. + """The logger format. The logger_formatter will be updated when sets logger_format. @@ -196,29 +201,28 @@ class Configuration(with_metaclass(TypeWithDefault, object)): self.logger_formatter = logging.Formatter(self.__logger_format) def get_api_key_with_prefix(self, identifier): - """ - Gets API key (with prefix if set). + """Gets API key (with prefix if set). :param identifier: The identifier of apiKey. :return: The token for api key authentication. """ - if self.api_key.get(identifier) and self.api_key_prefix.get(identifier): - return self.api_key_prefix[identifier] + ' ' + self.api_key[identifier] + if (self.api_key.get(identifier) and + self.api_key_prefix.get(identifier)): + return self.api_key_prefix[identifier] + ' ' + self.api_key[identifier] # noqa: E501 elif self.api_key.get(identifier): return self.api_key[identifier] def get_basic_auth_token(self): - """ - Gets HTTP basic authentication header (string). + """Gets HTTP basic authentication header (string). :return: The token for basic HTTP authentication. """ - return urllib3.util.make_headers(basic_auth=self.username + ':' + self.password)\ - .get('authorization') + return urllib3.util.make_headers( + basic_auth=self.username + ':' + self.password + ).get('authorization') def auth_settings(self): - """ - Gets Auth Settings dict for api client. + """Gets Auth Settings dict for api client. :return: The Auth Settings information dict. """ @@ -242,8 +246,7 @@ class Configuration(with_metaclass(TypeWithDefault, object)): } def to_debug_report(self): - """ - Gets the essential information for debugging. + """Gets the essential information for debugging. :return: The report for debugging. """ diff --git a/samples/client/petstore-security-test/python/petstore_api/models/__init__.py b/samples/client/petstore-security-test/python/petstore_api/models/__init__.py index a75a00eb198..ff65654b12c 100644 --- a/samples/client/petstore-security-test/python/petstore_api/models/__init__.py +++ b/samples/client/petstore-security-test/python/petstore_api/models/__init__.py @@ -1,9 +1,10 @@ # coding: utf-8 +# flake8: noqa """ Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- # noqa: E501 OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r @@ -14,4 +15,4 @@ from __future__ import absolute_import # import models into model package -from .model_return import ModelReturn +from petstore_api.models.model_return import ModelReturn diff --git a/samples/client/petstore-security-test/python/petstore_api/models/model_return.py b/samples/client/petstore-security-test/python/petstore_api/models/model_return.py index bb6813619ad..a4edf0658fd 100644 --- a/samples/client/petstore-security-test/python/petstore_api/models/model_return.py +++ b/samples/client/petstore-security-test/python/petstore_api/models/model_return.py @@ -3,7 +3,7 @@ """ Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- # noqa: E501 OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ModelReturn(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,47 +38,43 @@ class ModelReturn(object): '_return': 'return' } - def __init__(self, _return=None): - """ - ModelReturn - a model defined in Swagger - """ + def __init__(self, _return=None): # noqa: E501 + """ModelReturn - a model defined in Swagger""" # noqa: E501 self.__return = None self.discriminator = None if _return is not None: - self._return = _return + self._return = _return @property def _return(self): - """ - Gets the _return of this ModelReturn. - property description */ ' \" =end -- \\r\\n \\n \\r + """Gets the _return of this ModelReturn. # noqa: E501 - :return: The _return of this ModelReturn. + property description */ ' \" =end -- \\r\\n \\n \\r # noqa: E501 + + :return: The _return of this ModelReturn. # noqa: E501 :rtype: int """ return self.__return @_return.setter def _return(self, _return): - """ - Sets the _return of this ModelReturn. - property description */ ' \" =end -- \\r\\n \\n \\r + """Sets the _return of this ModelReturn. - :param _return: The _return of this ModelReturn. + property description */ ' \" =end -- \\r\\n \\n \\r # noqa: E501 + + :param _return: The _return of this ModelReturn. # noqa: E501 :type: int """ self.__return = _return def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -99,28 +95,20 @@ class ModelReturn(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ModelReturn): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore-security-test/python/petstore_api/rest.py b/samples/client/petstore-security-test/python/petstore_api/rest.py index 8ccd6a6f5e5..1f21e828708 100644 --- a/samples/client/petstore-security-test/python/petstore_api/rest.py +++ b/samples/client/petstore-security-test/python/petstore_api/rest.py @@ -3,7 +3,7 @@ """ Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- # noqa: E501 OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r @@ -15,13 +15,13 @@ from __future__ import absolute_import import io import json -import ssl -import certifi import logging import re +import ssl +import certifi # python 2 and python 3 compatibility library -from six import PY3 +import six from six.moves.urllib.parse import urlencode try: @@ -42,15 +42,11 @@ class RESTResponse(io.IOBase): self.data = resp.data def getheaders(self): - """ - Returns a dictionary of the response headers. - """ + """Returns a dictionary of the response headers.""" return self.urllib3_response.getheaders() def getheader(self, name, default=None): - """ - Returns a given response header. - """ + """Returns a given response header.""" return self.urllib3_response.getheader(name, default) @@ -58,10 +54,10 @@ class RESTClientObject(object): def __init__(self, configuration, pools_size=4, maxsize=None): # urllib3.PoolManager will pass all kw parameters to connectionpool - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 - # maxsize is the number of requests to host that are allowed in parallel - # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 # cert_reqs if configuration.verify_ssl: @@ -78,7 +74,7 @@ class RESTClientObject(object): addition_pool_args = {} if configuration.assert_hostname is not None: - addition_pool_args['assert_hostname'] = configuration.assert_hostname + addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 if maxsize is None: if configuration.connection_pool_maxsize is not None: @@ -110,8 +106,10 @@ class RESTClientObject(object): ) def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, _request_timeout=None): - """ + body=None, post_params=None, _preload_content=True, + _request_timeout=None): + """Perform requests. + :param method: http request method :param url: http request url :param query_params: query parameters in the url @@ -120,13 +118,17 @@ class RESTClientObject(object): :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without - reading/decoding response data. Default is True. - :param _request_timeout: timeout setting for this request. If one number provided, it will be total request - timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', + 'PATCH', 'OPTIONS'] if post_params and body: raise ValueError( @@ -138,10 +140,12 @@ class RESTClientObject(object): timeout = None if _request_timeout: - if isinstance(_request_timeout, (int, ) if PY3 else (int, long)): + if isinstance(_request_timeout, (int, ) if six.PY3 else (int, long)): # noqa: E501,F821 timeout = urllib3.Timeout(total=_request_timeout) - elif isinstance(_request_timeout, tuple) and len(_request_timeout) == 2: - timeout = urllib3.Timeout(connect=_request_timeout[0], read=_request_timeout[1]) + elif (isinstance(_request_timeout, tuple) and + len(_request_timeout) == 2): + timeout = urllib3.Timeout( + connect=_request_timeout[0], read=_request_timeout[1]) if 'Content-Type' not in headers: headers['Content-Type'] = 'application/json' @@ -155,42 +159,48 @@ class RESTClientObject(object): request_body = None if body is not None: request_body = json.dumps(body) - r = self.pool_manager.request(method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': - r = self.pool_manager.request(method, url, - fields=post_params, - encode_multipart=False, - preload_content=_preload_content, - timeout=timeout, - headers=headers) + r = self.pool_manager.request( + method, url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + r = self.pool_manager.request( + method, url, + fields=post_params, + encode_multipart=False, + preload_content=_preload_content, + timeout=timeout, + headers=headers) elif headers['Content-Type'] == 'multipart/form-data': - # must del headers['Content-Type'], or the correct Content-Type - # which generated by urllib3 will be overwritten. + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. del headers['Content-Type'] - r = self.pool_manager.request(method, url, - fields=post_params, - encode_multipart=True, - preload_content=_preload_content, - timeout=timeout, - headers=headers) + r = self.pool_manager.request( + method, url, + fields=post_params, + encode_multipart=True, + preload_content=_preload_content, + timeout=timeout, + headers=headers) # Pass a `string` parameter directly in the body to support - # other content types than Json when `body` argument is provided - # in serialized form + # other content types than Json when `body` argument is + # provided in serialized form elif isinstance(body, str): request_body = body - r = self.pool_manager.request(method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) + r = self.pool_manager.request( + method, url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers) else: # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided arguments. - Please check that your arguments match declared content type.""" + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: @@ -208,7 +218,7 @@ class RESTClientObject(object): # In the python 3, the response.data is bytes. # we need to decode it to string. - if PY3: + if six.PY3: r.data = r.data.decode('utf8') # log response body @@ -219,22 +229,24 @@ class RESTClientObject(object): return r - def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): + def GET(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): return self.request("GET", url, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout, query_params=query_params) - def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): + def HEAD(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): return self.request("HEAD", url, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout, query_params=query_params) - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): return self.request("OPTIONS", url, headers=headers, query_params=query_params, @@ -243,7 +255,8 @@ class RESTClientObject(object): _request_timeout=_request_timeout, body=body) - def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None): + def DELETE(self, url, headers=None, query_params=None, body=None, + _preload_content=True, _request_timeout=None): return self.request("DELETE", url, headers=headers, query_params=query_params, @@ -251,8 +264,8 @@ class RESTClientObject(object): _request_timeout=_request_timeout, body=body) - def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def POST(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): return self.request("POST", url, headers=headers, query_params=query_params, @@ -261,8 +274,8 @@ class RESTClientObject(object): _request_timeout=_request_timeout, body=body) - def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def PUT(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): return self.request("PUT", url, headers=headers, query_params=query_params, @@ -271,8 +284,8 @@ class RESTClientObject(object): _request_timeout=_request_timeout, body=body) - def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def PATCH(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): return self.request("PATCH", url, headers=headers, query_params=query_params, @@ -297,13 +310,12 @@ class ApiException(Exception): self.headers = None def __str__(self): - """ - Custom error messages for exception - """ + """Custom error messages for exception""" error_message = "({0})\n"\ "Reason: {1}\n".format(self.status, self.reason) if self.headers: - error_message += "HTTP response headers: {0}\n".format(self.headers) + error_message += "HTTP response headers: {0}\n".format( + self.headers) if self.body: error_message += "HTTP response body: {0}\n".format(self.body) diff --git a/samples/client/petstore-security-test/python/setup.py b/samples/client/petstore-security-test/python/setup.py index d752ddcc05a..50ee7728519 100644 --- a/samples/client/petstore-security-test/python/setup.py +++ b/samples/client/petstore-security-test/python/setup.py @@ -3,7 +3,7 @@ """ Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- # noqa: E501 OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r @@ -11,8 +11,7 @@ """ -import sys -from setuptools import setup, find_packages +from setuptools import setup, find_packages # noqa: H301 NAME = "petstore-api" VERSION = "1.0.0" @@ -36,6 +35,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. Special characters: \" \\ */ ' \" =end -- + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- # noqa: E501 """ ) diff --git a/samples/client/petstore-security-test/scala/pom.xml b/samples/client/petstore-security-test/scala/pom.xml index eceb1e6fdc4..b23683abc17 100644 --- a/samples/client/petstore-security-test/scala/pom.xml +++ b/samples/client/petstore-security-test/scala/pom.xml @@ -211,7 +211,7 @@ com.wordnik.swagger - swagger-async-httpclient_2.11 + swagger-async-httpclient_2.10 ${swagger-async-httpclient-version} diff --git a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala index 05a73b29609..fc6d1d282b6 100644 --- a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala @@ -40,10 +40,8 @@ import scala.concurrent._ import scala.concurrent.duration._ import scala.util.{Failure, Success, Try} -class FakeApi( - val defBasePath: String = "https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r", - defApiInvoker: ApiInvoker = ApiInvoker -) { +class FakeApi(val defBasePath: String = "https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r", + defApiInvoker: ApiInvoker = ApiInvoker) { implicit val formats = new org.json4s.DefaultFormats { override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+0000") @@ -55,13 +53,10 @@ class FakeApi( implicit val stringWriter = RequestWriters.StringWriter implicit val jsonWriter = JsonFormatsWriter - var basePath: String = defBasePath - var apiInvoker: ApiInvoker = defApiInvoker - - def addHeader(key: String, value: String): mutable.HashMap[String, String] = { - apiInvoker.defaultHeaders += key -> value - } + var basePath = defBasePath + var apiInvoker = defApiInvoker + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value val config = SwaggerConfig.forUrl(new URI(defBasePath)) val client = new RestClient(config) val helper = new FakeApiAsyncHelper(client, config) @@ -90,6 +85,7 @@ class FakeApi( helper.testCodeInject * ' " =end rn n r(testCodeInjectEndRnNR) } + } class FakeApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { diff --git a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala index 8f297a86b7a..b2ce925e121 100644 --- a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala @@ -15,6 +15,6 @@ package io.swagger.client.model case class ModelReturn ( /* property description *_/ ' \" =end -- \\r\\n \\n \\r */ - _return: Option[Integer] + _return: Option[Integer] = None ) diff --git a/samples/client/petstore-security-test/typescript-fetch/LICENSE b/samples/client/petstore-security-test/typescript-fetch/LICENSE deleted file mode 100644 index 8dada3edaf5..00000000000 --- a/samples/client/petstore-security-test/typescript-fetch/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - 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-security-test/typescript-fetch/README.md b/samples/client/petstore-security-test/typescript-fetch/README.md deleted file mode 100644 index 664e1755933..00000000000 --- a/samples/client/petstore-security-test/typescript-fetch/README.md +++ /dev/null @@ -1,54 +0,0 @@ -# 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 every time 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-security-test/typescript-fetch/api.ts b/samples/client/petstore-security-test/typescript-fetch/api.ts index 5146ea641b6..866ba88d58f 100644 --- a/samples/client/petstore-security-test/typescript-fetch/api.ts +++ b/samples/client/petstore-security-test/typescript-fetch/api.ts @@ -1,3 +1,4 @@ +/// // tslint:disable /** * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r @@ -13,7 +14,7 @@ import * as url from "url"; -import * as isomorphicFetch from "isomorphic-fetch"; +import * as portableFetch from "portable-fetch"; import { Configuration } from "./configuration"; const BASE_PATH = "https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r".replace(/\/+$/, ""); @@ -35,7 +36,7 @@ export const COLLECTION_FORMATS = { * @interface FetchAPI */ export interface FetchAPI { - (url: string, init?: any): Promise; + (url: string, init?: any): Promise; } /** @@ -56,7 +57,7 @@ export interface FetchArgs { export class BaseAPI { protected configuration: Configuration; - constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected fetch: FetchAPI = isomorphicFetch) { + constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected fetch: FetchAPI = portableFetch) { if (configuration) { this.configuration = configuration; this.basePath = configuration.basePath || this.basePath; @@ -146,9 +147,9 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testCodeInjectEndRnNR(test code inject * ' " =end rn n r?: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + testCodeInjectEndRnNR(test code inject * ' " =end rn n r?: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = FakeApiFetchParamCreator(configuration).testCodeInjectEndRnNR(test code inject * ' " =end rn n r, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; diff --git a/samples/client/petstore-security-test/typescript-fetch/custom.d.ts b/samples/client/petstore-security-test/typescript-fetch/custom.d.ts new file mode 100644 index 00000000000..02f969575e3 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/custom.d.ts @@ -0,0 +1 @@ +declare module 'portable-fetch'; \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-fetch/package.json b/samples/client/petstore-security-test/typescript-fetch/package.json deleted file mode 100644 index 0204e3c39c9..00000000000 --- a/samples/client/petstore-security-test/typescript-fetch/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "typescript-fetch-api", - "version": "0.0.0", - "license": "Unlicense", - "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" : { - "prepublish" : "typings install && tsc", - "test": "tslint api.ts" - }, - "devDependencies": { - "tslint": "^3.15.1", - "typescript": "^1.8.10", - "typings": "^1.0.4" - } -} diff --git a/samples/client/petstore-security-test/typescript-fetch/tsconfig.json b/samples/client/petstore-security-test/typescript-fetch/tsconfig.json deleted file mode 100644 index 72ff2567206..00000000000 --- a/samples/client/petstore-security-test/typescript-fetch/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "compilerOptions": { - "declaration": true, - "target": "es5", - "module": "commonjs", - "noImplicitAny": true, - "outDir": "dist", - "rootDir": "." - }, - "exclude": [ - "dist", - "node_modules", - "typings/browser", - "typings/main", - "typings/main.d.ts" - ] -} diff --git a/samples/client/petstore-security-test/typescript-fetch/tslint.json b/samples/client/petstore-security-test/typescript-fetch/tslint.json deleted file mode 100644 index 6eb02acec8c..00000000000 --- a/samples/client/petstore-security-test/typescript-fetch/tslint.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "jsRules": { - "class-name": true, - "comment-format": [ - true, - "check-space" - ], - "indent": [ - true, - "spaces" - ], - "no-duplicate-variable": true, - "no-eval": true, - "no-trailing-whitespace": true, - "no-unsafe-finally": true, - "one-line": [ - true, - "check-open-brace", - "check-whitespace" - ], - "quotemark": [ - true, - "double" - ], - "semicolon": [ - true, - "always" - ], - "triple-equals": [ - true, - "allow-null-check" - ], - "variable-name": [ - true, - "ban-keywords" - ], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ] - }, - "rules": { - "class-name": true, - "comment-format": [ - true, - "check-space" - ], - "indent": [ - true, - "spaces" - ], - "no-eval": true, - "no-internal-module": true, - "no-trailing-whitespace": true, - "no-unsafe-finally": true, - "no-var-keyword": true, - "one-line": [ - true, - "check-open-brace", - "check-whitespace" - ], - "quotemark": [ - true, - "double" - ], - "semicolon": [ - true, - "always" - ], - "triple-equals": [ - true, - "allow-null-check" - ], - "typedef-whitespace": [ - true, - { - "call-signature": "nospace", - "index-signature": "nospace", - "parameter": "nospace", - "property-declaration": "nospace", - "variable-declaration": "nospace" - } - ], - "variable-name": [ - true, - "ban-keywords" - ], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ] - } -} diff --git a/samples/client/petstore-security-test/typescript-fetch/typings.json b/samples/client/petstore-security-test/typescript-fetch/typings.json deleted file mode 100644 index a82ea152b4a..00000000000 --- a/samples/client/petstore-security-test/typescript-fetch/typings.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "version": false, - "dependencies": {}, - "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-security-test/typescript-node/api.ts b/samples/client/petstore-security-test/typescript-node/api.ts index dbc8f6e5c4b..71c599e01c7 100644 --- a/samples/client/petstore-security-test/typescript-node/api.ts +++ b/samples/client/petstore-security-test/typescript-node/api.ts @@ -10,7 +10,7 @@ * Do not edit the class manually. */ -import request = require('request'); +import localVarRequest = require('request'); import http = require('http'); import Promise = require('bluebird'); @@ -171,13 +171,13 @@ export interface Authentication { /** * Apply authentication settings to header and query params. */ - applyToRequest(requestOptions: request.Options): void; + applyToRequest(requestOptions: localVarRequest.Options): void; } export class HttpBasicAuth implements Authentication { public username: string; public password: string; - applyToRequest(requestOptions: request.Options): void { + applyToRequest(requestOptions: localVarRequest.Options): void { requestOptions.auth = { username: this.username, password: this.password } @@ -190,7 +190,7 @@ export class ApiKeyAuth implements Authentication { constructor(private location: string, private paramName: string) { } - applyToRequest(requestOptions: request.Options): void { + applyToRequest(requestOptions: localVarRequest.Options): void { if (this.location == "query") { (requestOptions.qs)[this.paramName] = this.apiKey; } else if (this.location == "header" && requestOptions && requestOptions.headers) { @@ -202,7 +202,7 @@ export class ApiKeyAuth implements Authentication { export class OAuth implements Authentication { public accessToken: string; - applyToRequest(requestOptions: request.Options): void { + applyToRequest(requestOptions: localVarRequest.Options): void { if (requestOptions && requestOptions.headers) { requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; } @@ -212,7 +212,7 @@ export class OAuth implements Authentication { export class VoidAuth implements Authentication { public username: string; public password: string; - applyToRequest(_: request.Options): void { + applyToRequest(_: localVarRequest.Options): void { // Do nothing } } @@ -275,41 +275,41 @@ export class FakeApi { */ public testCodeInjectEndRnNR (test code inject * ' " =end rn n r?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/fake'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; - let useFormData = false; + let localVarUseFormData = false; if (test code inject * ' " =end rn n r !== undefined) { - formParams['test code inject */ ' " =end -- \r\n \n \r'] = ObjectSerializer.serialize(test code inject * ' " =end rn n r, "string"); + localVarFormParams['test code inject */ ' " =end -- \r\n \n \r'] = ObjectSerializer.serialize(test code inject * ' " =end rn n r, "string"); } - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'PUT', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); diff --git a/samples/client/petstore/cpprest/ApiClient.cpp b/samples/client/petstore/cpprest/ApiClient.cpp index 92a09ed7fa5..868b78c8521 100644 --- a/samples/client/petstore/cpprest/ApiClient.cpp +++ b/samples/client/petstore/cpprest/ApiClient.cpp @@ -79,17 +79,17 @@ pplx::task ApiClient::callApi( { if (postBody != nullptr && formParams.size() != 0) { - throw ApiException(400, U("Cannot have body and form params")); + throw ApiException(400, utility::conversions::to_string_t("Cannot have body and form params")); } if (postBody != nullptr && fileParams.size() != 0) { - throw ApiException(400, U("Cannot have body and file params")); + throw ApiException(400, utility::conversions::to_string_t("Cannot have body and file params")); } - if (fileParams.size() > 0 && contentType != U("multipart/form-data")) + if (fileParams.size() > 0 && contentType != utility::conversions::to_string_t("multipart/form-data")) { - throw ApiException(400, U("Operations with file parameters must be called with multipart/form-data")); + throw ApiException(400, utility::conversions::to_string_t("Operations with file parameters must be called with multipart/form-data")); } web::http::client::http_client client(m_Configuration->getBaseUrl(), m_Configuration->getHttpConfig()); @@ -115,7 +115,7 @@ pplx::task ApiClient::callApi( uploadData.writeTo(data); auto bodyString = data.str(); auto length = bodyString.size(); - request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, U("multipart/form-data; boundary=") + uploadData.getBoundary()); + request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, utility::conversions::to_string_t("multipart/form-data; boundary=") + uploadData.getBoundary()); } else { @@ -129,7 +129,7 @@ pplx::task ApiClient::callApi( } else { - if (contentType == U("application/json")) + if (contentType == utility::conversions::to_string_t("application/json")) { web::json::value body_data = web::json::value::object(); for (auto& kvp : formParams) @@ -150,7 +150,7 @@ pplx::task ApiClient::callApi( } if (!formParams.empty()) { - request.set_body(formData.query(), U("application/x-www-form-urlencoded")); + request.set_body(formData.query(), utility::conversions::to_string_t("application/x-www-form-urlencoded")); } } } diff --git a/samples/client/petstore/cpprest/ApiClient.h b/samples/client/petstore/cpprest/ApiClient.h index 8adde7a78c6..4b6877e04b3 100644 --- a/samples/client/petstore/cpprest/ApiClient.h +++ b/samples/client/petstore/cpprest/ApiClient.h @@ -16,8 +16,8 @@ * This is an API client responsible for stating the HTTP calls */ -#ifndef ApiClient_H_ -#define ApiClient_H_ +#ifndef IO_SWAGGER_CLIENT_API_ApiClient_H_ +#define IO_SWAGGER_CLIENT_API_ApiClient_H_ #include "ApiConfiguration.h" @@ -60,7 +60,7 @@ public: for( size_t i = 0; i < value.size(); i++) { - if( i > 0) ss << U(", "); + if( i > 0) ss << utility::conversions::to_string_t(", "); ss << ApiClient::parameterToString(value[i]); } @@ -88,4 +88,4 @@ protected: } } -#endif /* ApiClient_H_ */ +#endif /* IO_SWAGGER_CLIENT_API_ApiClient_H_ */ diff --git a/samples/client/petstore/cpprest/ApiConfiguration.cpp b/samples/client/petstore/cpprest/ApiConfiguration.cpp index 68338c95f3f..5baa1e79483 100644 --- a/samples/client/petstore/cpprest/ApiConfiguration.cpp +++ b/samples/client/petstore/cpprest/ApiConfiguration.cpp @@ -67,7 +67,7 @@ utility::string_t ApiConfiguration::getApiKey( const utility::string_t& prefix) { return result->second; } - return U(""); + return utility::conversions::to_string_t(""); } void ApiConfiguration::setApiKey( const utility::string_t& prefix, const utility::string_t& apiKey ) diff --git a/samples/client/petstore/cpprest/ApiConfiguration.h b/samples/client/petstore/cpprest/ApiConfiguration.h index f7834f841c9..d5d22d8fb66 100644 --- a/samples/client/petstore/cpprest/ApiConfiguration.h +++ b/samples/client/petstore/cpprest/ApiConfiguration.h @@ -16,8 +16,8 @@ * This class represents a single item of a multipart-formdata request. */ -#ifndef ApiConfiguration_H_ -#define ApiConfiguration_H_ +#ifndef IO_SWAGGER_CLIENT_API_ApiConfiguration_H_ +#define IO_SWAGGER_CLIENT_API_ApiConfiguration_H_ @@ -62,4 +62,4 @@ protected: } } } -#endif /* ApiConfiguration_H_ */ +#endif /* IO_SWAGGER_CLIENT_API_ApiConfiguration_H_ */ diff --git a/samples/client/petstore/cpprest/ApiException.h b/samples/client/petstore/cpprest/ApiException.h index fe16971e5d5..b5dcdadb87c 100644 --- a/samples/client/petstore/cpprest/ApiException.h +++ b/samples/client/petstore/cpprest/ApiException.h @@ -16,8 +16,8 @@ * This is the exception being thrown in case the api call was not successful */ -#ifndef ApiException_H_ -#define ApiException_H_ +#ifndef IO_SWAGGER_CLIENT_API_ApiException_H_ +#define IO_SWAGGER_CLIENT_API_ApiException_H_ @@ -59,4 +59,4 @@ protected: } } -#endif /* ApiBase_H_ */ +#endif /* IO_SWAGGER_CLIENT_API_ApiBase_H_ */ diff --git a/samples/client/petstore/cpprest/HttpContent.h b/samples/client/petstore/cpprest/HttpContent.h index 908f83bedce..dcbd4868e84 100644 --- a/samples/client/petstore/cpprest/HttpContent.h +++ b/samples/client/petstore/cpprest/HttpContent.h @@ -16,8 +16,8 @@ * This class represents a single item of a multipart-formdata request. */ -#ifndef HttpContent_H_ -#define HttpContent_H_ +#ifndef IO_SWAGGER_CLIENT_MODEL_HttpContent_H_ +#define IO_SWAGGER_CLIENT_MODEL_HttpContent_H_ @@ -67,4 +67,4 @@ protected: } } -#endif /* HttpContent_H_ */ +#endif /* IO_SWAGGER_CLIENT_MODEL_HttpContent_H_ */ diff --git a/samples/client/petstore/cpprest/IHttpBody.h b/samples/client/petstore/cpprest/IHttpBody.h index 1f3ba2ae430..6d2a61bae3a 100644 --- a/samples/client/petstore/cpprest/IHttpBody.h +++ b/samples/client/petstore/cpprest/IHttpBody.h @@ -16,8 +16,8 @@ * This is the interface for contents that can be sent to a remote HTTP server. */ -#ifndef IHttpBody_H_ -#define IHttpBody_H_ +#ifndef IO_SWAGGER_CLIENT_MODEL_IHttpBody_H_ +#define IO_SWAGGER_CLIENT_MODEL_IHttpBody_H_ #include @@ -40,4 +40,4 @@ public: } } -#endif /* IHttpBody_H_ */ +#endif /* IO_SWAGGER_CLIENT_MODEL_IHttpBody_H_ */ diff --git a/samples/client/petstore/cpprest/JsonBody.h b/samples/client/petstore/cpprest/JsonBody.h index 07e356c2174..a8960d94ad8 100644 --- a/samples/client/petstore/cpprest/JsonBody.h +++ b/samples/client/petstore/cpprest/JsonBody.h @@ -16,8 +16,8 @@ * This is a JSON http body which can be submitted via http */ -#ifndef JsonBody_H_ -#define JsonBody_H_ +#ifndef IO_SWAGGER_CLIENT_MODEL_JsonBody_H_ +#define IO_SWAGGER_CLIENT_MODEL_JsonBody_H_ #include "IHttpBody.h" @@ -47,4 +47,4 @@ protected: } } -#endif /* JsonBody_H_ */ +#endif /* IO_SWAGGER_CLIENT_MODEL_JsonBody_H_ */ diff --git a/samples/client/petstore/cpprest/ModelBase.cpp b/samples/client/petstore/cpprest/ModelBase.cpp index 351a2727b64..133b82fec74 100644 --- a/samples/client/petstore/cpprest/ModelBase.cpp +++ b/samples/client/petstore/cpprest/ModelBase.cpp @@ -51,10 +51,10 @@ web::json::value ModelBase::toJson(bool value) { web::json::value ModelBase::toJson( std::shared_ptr content ) { web::json::value value; - value[U("ContentDisposition")] = ModelBase::toJson(content->getContentDisposition()); - value[U("ContentType")] = ModelBase::toJson(content->getContentType()); - value[U("FileName")] = ModelBase::toJson(content->getFileName()); - value[U("InputStream")] = web::json::value::string( ModelBase::toBase64(content->getData()) ); + value[utility::conversions::to_string_t("ContentDisposition")] = ModelBase::toJson(content->getContentDisposition()); + value[utility::conversions::to_string_t("ContentType")] = ModelBase::toJson(content->getContentType()); + value[utility::conversions::to_string_t("FileName")] = ModelBase::toJson(content->getFileName()); + value[utility::conversions::to_string_t("InputStream")] = web::json::value::string( ModelBase::toBase64(content->getData()) ); return value; } @@ -62,21 +62,21 @@ std::shared_ptr ModelBase::fileFromJson(web::json::value& val) { std::shared_ptr content(new HttpContent); - if(val.has_field(U("ContentDisposition"))) + if(val.has_field(utility::conversions::to_string_t("ContentDisposition"))) { - content->setContentDisposition( ModelBase::stringFromJson(val[U("ContentDisposition")]) ); + content->setContentDisposition( ModelBase::stringFromJson(val[utility::conversions::to_string_t("ContentDisposition")]) ); } - if(val.has_field(U("ContentType"))) + if(val.has_field(utility::conversions::to_string_t("ContentType"))) { - content->setContentType( ModelBase::stringFromJson(val[U("ContentType")]) ); + content->setContentType( ModelBase::stringFromJson(val[utility::conversions::to_string_t("ContentType")]) ); } - if(val.has_field(U("FileName"))) + if(val.has_field(utility::conversions::to_string_t("FileName"))) { - content->setFileName( ModelBase::stringFromJson(val[U("FileName")]) ); + content->setFileName( ModelBase::stringFromJson(val[utility::conversions::to_string_t("FileName")]) ); } - if(val.has_field(U("InputStream"))) + if(val.has_field(utility::conversions::to_string_t("InputStream"))) { - content->setData( ModelBase::fromBase64( ModelBase::stringFromJson(val[U("InputStream")]) ) ); + content->setData( ModelBase::fromBase64( ModelBase::stringFromJson(val[utility::conversions::to_string_t("InputStream")]) ) ); } return content; @@ -91,7 +91,7 @@ std::shared_ptr ModelBase::toHttpContent( const utility::string_t& { std::shared_ptr content(new HttpContent); content->setName( name ); - content->setContentDisposition( U("form-data") ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); content->setContentType( contentType ); content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(value) ) ) ); return content; @@ -100,7 +100,7 @@ std::shared_ptr ModelBase::toHttpContent( const utility::string_t& { std::shared_ptr content( new HttpContent ); content->setName( name ); - content->setContentDisposition( U("form-data") ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); content->setContentType( contentType ); content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(value.to_string(utility::datetime::ISO_8601) ) ) ) ); return content; @@ -119,7 +119,7 @@ std::shared_ptr ModelBase::toHttpContent( const utility::string_t& { std::shared_ptr content( new HttpContent ); content->setName( name ); - content->setContentDisposition( U("form-data") ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); content->setContentType( contentType ); content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(value.serialize()) ) ) ); return content; @@ -128,7 +128,7 @@ std::shared_ptr ModelBase::toHttpContent( const utility::string_t& { std::shared_ptr content( new HttpContent ); content->setName( name ); - content->setContentDisposition( U("form-data") ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); content->setContentType( contentType ); std::stringstream* valueAsStringStream = new std::stringstream(); (*valueAsStringStream) << value; @@ -139,7 +139,7 @@ std::shared_ptr ModelBase::toHttpContent( const utility::string_t& { std::shared_ptr content( new HttpContent ); content->setName( name ); - content->setContentDisposition( U("form-data") ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); content->setContentType( contentType ); std::stringstream* valueAsStringStream = new std::stringstream(); (*valueAsStringStream) << value; @@ -150,7 +150,7 @@ std::shared_ptr ModelBase::toHttpContent( const utility::string_t& { std::shared_ptr content( new HttpContent ); content->setName( name ); - content->setContentDisposition( U("form-data") ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); content->setContentType( contentType ); std::stringstream* valueAsStringStream = new std::stringstream(); (*valueAsStringStream) << value; @@ -256,12 +256,12 @@ std::shared_ptr ModelBase::fromBase64( const utility::string_t& en result->write( outBuf, 1 ); return result; default: - throw web::json::json_exception( U( "Invalid Padding in Base 64!" ) ); + throw web::json::json_exception( utility::conversions::to_string_t( "Invalid Padding in Base 64!" ).c_str() ); } } else { - throw web::json::json_exception( U( "Non-Valid Character in Base 64!" ) ); + throw web::json::json_exception( utility::conversions::to_string_t( "Non-Valid Character in Base 64!" ).c_str() ); } ++cursor; } @@ -289,7 +289,7 @@ float ModelBase::floatFromJson(web::json::value& val) } utility::string_t ModelBase::stringFromJson(web::json::value& val) { - return val.is_string() ? val.as_string() : U(""); + return val.is_string() ? val.as_string() : utility::conversions::to_string_t(""); } utility::datetime ModelBase::dateFromJson(web::json::value& val) diff --git a/samples/client/petstore/cpprest/ModelBase.h b/samples/client/petstore/cpprest/ModelBase.h index 7d2e5c1ecda..0c13101ef57 100644 --- a/samples/client/petstore/cpprest/ModelBase.h +++ b/samples/client/petstore/cpprest/ModelBase.h @@ -16,8 +16,8 @@ * This is the base class for all model classes */ -#ifndef ModelBase_H_ -#define ModelBase_H_ +#ifndef IO_SWAGGER_CLIENT_MODEL_ModelBase_H_ +#define IO_SWAGGER_CLIENT_MODEL_ModelBase_H_ #include "HttpContent.h" @@ -63,13 +63,13 @@ public: static bool boolFromJson(web::json::value& val); static std::shared_ptr fileFromJson(web::json::value& val); - static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::string_t& value, const utility::string_t& contentType = U("")); - static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::datetime& value, const utility::string_t& contentType = U("")); + static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::string_t& value, const utility::string_t& contentType = utility::conversions::to_string_t("")); + static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::datetime& value, const utility::string_t& contentType = utility::conversions::to_string_t("")); static std::shared_ptr toHttpContent( const utility::string_t& name, std::shared_ptr value ); - static std::shared_ptr toHttpContent( const utility::string_t& name, const web::json::value& value, const utility::string_t& contentType = U("application/json") ); - static std::shared_ptr toHttpContent( const utility::string_t& name, int32_t value, const utility::string_t& contentType = U("") ); - static std::shared_ptr toHttpContent( const utility::string_t& name, int64_t value, const utility::string_t& contentType = U("") ); - static std::shared_ptr toHttpContent( const utility::string_t& name, double value, const utility::string_t& contentType = U("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, const web::json::value& value, const utility::string_t& contentType = utility::conversions::to_string_t("application/json") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, int32_t value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, int64_t value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, double value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); static int64_t int64_tFromHttpContent(std::shared_ptr val); static int32_t int32_tFromHttpContent(std::shared_ptr val); @@ -90,4 +90,4 @@ public: } } -#endif /* ModelBase_H_ */ +#endif /* IO_SWAGGER_CLIENT_MODEL_ModelBase_H_ */ diff --git a/samples/client/petstore/cpprest/MultipartFormData.h b/samples/client/petstore/cpprest/MultipartFormData.h index 1fabb33cb69..6a259f43cbc 100644 --- a/samples/client/petstore/cpprest/MultipartFormData.h +++ b/samples/client/petstore/cpprest/MultipartFormData.h @@ -16,8 +16,8 @@ * This class represents a container for building a application/x-multipart-formdata requests. */ -#ifndef MultipartFormData_H_ -#define MultipartFormData_H_ +#ifndef IO_SWAGGER_CLIENT_MODEL_MultipartFormData_H_ +#define IO_SWAGGER_CLIENT_MODEL_MultipartFormData_H_ #include "IHttpBody.h" @@ -60,4 +60,4 @@ protected: } } -#endif /* MultipartFormData_H_ */ +#endif /* IO_SWAGGER_CLIENT_MODEL_MultipartFormData_H_ */ diff --git a/samples/client/petstore/cpprest/api/PetApi.cpp b/samples/client/petstore/cpprest/api/PetApi.cpp index 96fd6d669f3..e709c13d8f2 100644 --- a/samples/client/petstore/cpprest/api/PetApi.cpp +++ b/samples/client/petstore/cpprest/api/PetApi.cpp @@ -42,12 +42,12 @@ pplx::task PetApi::addPet(std::shared_ptr body) // verify the required parameter 'body' is set if (body == nullptr) { - throw ApiException(400, U("Missing required parameter 'body' when calling PetApi->addPet")); + throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'body' when calling PetApi->addPet")); } std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/pet"); + utility::string_t path = utility::conversions::to_string_t("/pet"); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -55,45 +55,45 @@ pplx::task PetApi::addPet(std::shared_ptr body) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("PetApi->addPet does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("PetApi->addPet does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; - consumeHttpContentTypes.insert( U("application/json") ); - consumeHttpContentTypes.insert( U("application/xml") ); + consumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); + consumeHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); std::shared_ptr httpBody; utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); web::json::value json; json = ModelBase::toJson(body); @@ -101,27 +101,27 @@ pplx::task PetApi::addPet(std::shared_ptr body) httpBody = std::shared_ptr( new JsonBody( json ) ); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); std::shared_ptr multipart(new MultipartFormData); if(body.get()) { - body->toMultipart(multipart, U("body")); + body->toMultipart(multipart, utility::conversions::to_string_t("body")); } httpBody = multipart; - requestHttpContentType += U("; boundary=") + multipart->getBoundary(); + requestHttpContentType += utility::conversions::to_string_t("; boundary=") + multipart->getBoundary(); } else { - throw ApiException(415, U("PetApi->addPet does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("PetApi->addPet does not consume any supported media type")); } // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config - return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -132,18 +132,18 @@ pplx::task PetApi::addPet(std::shared_ptr body) if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling addPet: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling addPet: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling addPet: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling addPet: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -160,8 +160,8 @@ pplx::task PetApi::deletePet(int64_t petId, utility::string_t apiKey) std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/pet/{petId}"); - boost::replace_all(path, U("{") U("petId") U("}"), ApiClient::parameterToString(petId)); + utility::string_t path = utility::conversions::to_string_t("/pet/{petId}"); + boost::replace_all(path, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("petId") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(petId)); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -169,62 +169,62 @@ pplx::task PetApi::deletePet(int64_t petId, utility::string_t apiKey) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("PetApi->deletePet does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("PetApi->deletePet does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; { - headerParams[U("api_key")] = ApiClient::parameterToString(apiKey); + headerParams[utility::conversions::to_string_t("api_key")] = ApiClient::parameterToString(apiKey); } std::shared_ptr httpBody; utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(415, U("PetApi->deletePet does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("PetApi->deletePet does not consume any supported media type")); } // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config - return m_ApiClient->callApi(path, U("DELETE"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("DELETE"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -235,18 +235,18 @@ pplx::task PetApi::deletePet(int64_t petId, utility::string_t apiKey) if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling deletePet: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling deletePet: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling deletePet: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling deletePet: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -263,7 +263,7 @@ pplx::task>> PetApi::findPetsByStatus(std::vect std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/pet/findByStatus"); + utility::string_t path = utility::conversions::to_string_t("/pet/findByStatus"); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -271,62 +271,62 @@ pplx::task>> PetApi::findPetsByStatus(std::vect std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("PetApi->findPetsByStatus does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("PetApi->findPetsByStatus does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; { - queryParams[U("status")] = ApiClient::parameterToArrayString(status); + queryParams[utility::conversions::to_string_t("status")] = ApiClient::parameterToArrayString(status); } std::shared_ptr httpBody; utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(415, U("PetApi->findPetsByStatus does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("PetApi->findPetsByStatus does not consume any supported media type")); } // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config - return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -337,18 +337,18 @@ pplx::task>> PetApi::findPetsByStatus(std::vect if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling findPetsByStatus: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling findPetsByStatus: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling findPetsByStatus: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling findPetsByStatus: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -359,7 +359,7 @@ pplx::task>> PetApi::findPetsByStatus(std::vect { std::vector> result; - if(responseHttpContentType == U("application/json")) + if(responseHttpContentType == utility::conversions::to_string_t("application/json")) { web::json::value json = web::json::value::parse(response); @@ -372,14 +372,14 @@ pplx::task>> PetApi::findPetsByStatus(std::vect } } - // else if(responseHttpContentType == U("multipart/form-data")) + // else if(responseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) // { // TODO multipart response parsing // } else { throw ApiException(500 - , U("error calling findPetsByStatus: unsupported response type")); + , utility::conversions::to_string_t("error calling findPetsByStatus: unsupported response type")); } return result; @@ -390,7 +390,7 @@ pplx::task>> PetApi::findPetsByTags(std::vector std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/pet/findByTags"); + utility::string_t path = utility::conversions::to_string_t("/pet/findByTags"); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -398,62 +398,62 @@ pplx::task>> PetApi::findPetsByTags(std::vector std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("PetApi->findPetsByTags does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("PetApi->findPetsByTags does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; { - queryParams[U("tags")] = ApiClient::parameterToArrayString(tags); + queryParams[utility::conversions::to_string_t("tags")] = ApiClient::parameterToArrayString(tags); } std::shared_ptr httpBody; utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(415, U("PetApi->findPetsByTags does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("PetApi->findPetsByTags does not consume any supported media type")); } // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config - return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -464,18 +464,18 @@ pplx::task>> PetApi::findPetsByTags(std::vector if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling findPetsByTags: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling findPetsByTags: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling findPetsByTags: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling findPetsByTags: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -486,7 +486,7 @@ pplx::task>> PetApi::findPetsByTags(std::vector { std::vector> result; - if(responseHttpContentType == U("application/json")) + if(responseHttpContentType == utility::conversions::to_string_t("application/json")) { web::json::value json = web::json::value::parse(response); @@ -499,14 +499,14 @@ pplx::task>> PetApi::findPetsByTags(std::vector } } - // else if(responseHttpContentType == U("multipart/form-data")) + // else if(responseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) // { // TODO multipart response parsing // } else { throw ApiException(500 - , U("error calling findPetsByTags: unsupported response type")); + , utility::conversions::to_string_t("error calling findPetsByTags: unsupported response type")); } return result; @@ -517,8 +517,8 @@ pplx::task> PetApi::getPetById(int64_t petId) std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/pet/{petId}"); - boost::replace_all(path, U("{") U("petId") U("}"), ApiClient::parameterToString(petId)); + utility::string_t path = utility::conversions::to_string_t("/pet/{petId}"); + boost::replace_all(path, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("petId") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(petId)); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -526,32 +526,32 @@ pplx::task> PetApi::getPetById(int64_t petId) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("PetApi->getPetById does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("PetApi->getPetById does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; @@ -560,30 +560,30 @@ pplx::task> PetApi::getPetById(int64_t petId) utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(415, U("PetApi->getPetById does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("PetApi->getPetById does not consume any supported media type")); } // authentication (api_key) required { - utility::string_t apiKey = apiConfiguration->getApiKey(U("api_key")); + utility::string_t apiKey = apiConfiguration->getApiKey(utility::conversions::to_string_t("api_key")); if ( apiKey.size() > 0 ) { - headerParams[U("api_key")] = apiKey; + headerParams[utility::conversions::to_string_t("api_key")] = apiKey; } } - return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -594,18 +594,18 @@ pplx::task> PetApi::getPetById(int64_t petId) if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling getPetById: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling getPetById: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling getPetById: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling getPetById: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -616,20 +616,20 @@ pplx::task> PetApi::getPetById(int64_t petId) { std::shared_ptr result(new Pet()); - if(responseHttpContentType == U("application/json")) + if(responseHttpContentType == utility::conversions::to_string_t("application/json")) { web::json::value json = web::json::value::parse(response); result->fromJson(json); } - // else if(responseHttpContentType == U("multipart/form-data")) + // else if(responseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) // { // TODO multipart response parsing // } else { throw ApiException(500 - , U("error calling getPetById: unsupported response type")); + , utility::conversions::to_string_t("error calling getPetById: unsupported response type")); } return result; @@ -641,12 +641,12 @@ pplx::task PetApi::updatePet(std::shared_ptr body) // verify the required parameter 'body' is set if (body == nullptr) { - throw ApiException(400, U("Missing required parameter 'body' when calling PetApi->updatePet")); + throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'body' when calling PetApi->updatePet")); } std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/pet"); + utility::string_t path = utility::conversions::to_string_t("/pet"); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -654,45 +654,45 @@ pplx::task PetApi::updatePet(std::shared_ptr body) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("PetApi->updatePet does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("PetApi->updatePet does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; - consumeHttpContentTypes.insert( U("application/json") ); - consumeHttpContentTypes.insert( U("application/xml") ); + consumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); + consumeHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); std::shared_ptr httpBody; utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); web::json::value json; json = ModelBase::toJson(body); @@ -700,27 +700,27 @@ pplx::task PetApi::updatePet(std::shared_ptr body) httpBody = std::shared_ptr( new JsonBody( json ) ); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); std::shared_ptr multipart(new MultipartFormData); if(body.get()) { - body->toMultipart(multipart, U("body")); + body->toMultipart(multipart, utility::conversions::to_string_t("body")); } httpBody = multipart; - requestHttpContentType += U("; boundary=") + multipart->getBoundary(); + requestHttpContentType += utility::conversions::to_string_t("; boundary=") + multipart->getBoundary(); } else { - throw ApiException(415, U("PetApi->updatePet does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("PetApi->updatePet does not consume any supported media type")); } // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config - return m_ApiClient->callApi(path, U("PUT"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("PUT"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -731,18 +731,18 @@ pplx::task PetApi::updatePet(std::shared_ptr body) if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling updatePet: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling updatePet: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling updatePet: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling updatePet: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -759,8 +759,8 @@ pplx::task PetApi::updatePetWithForm(int64_t petId, utility::string_t name std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/pet/{petId}"); - boost::replace_all(path, U("{") U("petId") U("}"), ApiClient::parameterToString(petId)); + utility::string_t path = utility::conversions::to_string_t("/pet/{petId}"); + boost::replace_all(path, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("petId") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(petId)); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -768,67 +768,67 @@ pplx::task PetApi::updatePetWithForm(int64_t petId, utility::string_t name std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("PetApi->updatePetWithForm does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("PetApi->updatePetWithForm does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; - consumeHttpContentTypes.insert( U("application/x-www-form-urlencoded") ); + consumeHttpContentTypes.insert( utility::conversions::to_string_t("application/x-www-form-urlencoded") ); { - formParams[ U("name") ] = ApiClient::parameterToString(name); + formParams[ utility::conversions::to_string_t("name") ] = ApiClient::parameterToString(name); } { - formParams[ U("status") ] = ApiClient::parameterToString(status); + formParams[ utility::conversions::to_string_t("status") ] = ApiClient::parameterToString(status); } std::shared_ptr httpBody; utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(415, U("PetApi->updatePetWithForm does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("PetApi->updatePetWithForm does not consume any supported media type")); } // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config - return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -839,18 +839,18 @@ pplx::task PetApi::updatePetWithForm(int64_t petId, utility::string_t name if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling updatePetWithForm: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling updatePetWithForm: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling updatePetWithForm: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling updatePetWithForm: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -867,8 +867,8 @@ pplx::task> PetApi::uploadFile(int64_t petId, utili std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/pet/{petId}/uploadImage"); - boost::replace_all(path, U("{") U("petId") U("}"), ApiClient::parameterToString(petId)); + utility::string_t path = utility::conversions::to_string_t("/pet/{petId}/uploadImage"); + boost::replace_all(path, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("petId") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(petId)); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -876,66 +876,66 @@ pplx::task> PetApi::uploadFile(int64_t petId, utili std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("PetApi->uploadFile does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("PetApi->uploadFile does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; - consumeHttpContentTypes.insert( U("multipart/form-data") ); + consumeHttpContentTypes.insert( utility::conversions::to_string_t("multipart/form-data") ); { - formParams[ U("additionalMetadata") ] = ApiClient::parameterToString(additionalMetadata); + formParams[ utility::conversions::to_string_t("additionalMetadata") ] = ApiClient::parameterToString(additionalMetadata); } if (file != nullptr) { - fileParams[ U("file") ] = file; + fileParams[ utility::conversions::to_string_t("file") ] = file; } std::shared_ptr httpBody; utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(415, U("PetApi->uploadFile does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("PetApi->uploadFile does not consume any supported media type")); } // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config - return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -946,18 +946,18 @@ pplx::task> PetApi::uploadFile(int64_t petId, utili if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling uploadFile: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling uploadFile: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling uploadFile: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling uploadFile: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -968,20 +968,20 @@ pplx::task> PetApi::uploadFile(int64_t petId, utili { std::shared_ptr result(new ApiResponse()); - if(responseHttpContentType == U("application/json")) + if(responseHttpContentType == utility::conversions::to_string_t("application/json")) { web::json::value json = web::json::value::parse(response); result->fromJson(json); } - // else if(responseHttpContentType == U("multipart/form-data")) + // else if(responseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) // { // TODO multipart response parsing // } else { throw ApiException(500 - , U("error calling uploadFile: unsupported response type")); + , utility::conversions::to_string_t("error calling uploadFile: unsupported response type")); } return result; diff --git a/samples/client/petstore/cpprest/api/PetApi.h b/samples/client/petstore/cpprest/api/PetApi.h index 62dab57218b..f76d7f93e2c 100644 --- a/samples/client/petstore/cpprest/api/PetApi.h +++ b/samples/client/petstore/cpprest/api/PetApi.h @@ -16,8 +16,8 @@ * */ -#ifndef PetApi_H_ -#define PetApi_H_ +#ifndef IO_SWAGGER_CLIENT_API_PetApi_H_ +#define IO_SWAGGER_CLIENT_API_PetApi_H_ #include "ApiClient.h" @@ -113,5 +113,5 @@ protected: } } -#endif /* PetApi_H_ */ +#endif /* IO_SWAGGER_CLIENT_API_PetApi_H_ */ diff --git a/samples/client/petstore/cpprest/api/StoreApi.cpp b/samples/client/petstore/cpprest/api/StoreApi.cpp index 4f897327d6e..03a10677b85 100644 --- a/samples/client/petstore/cpprest/api/StoreApi.cpp +++ b/samples/client/petstore/cpprest/api/StoreApi.cpp @@ -41,8 +41,8 @@ pplx::task StoreApi::deleteOrder(utility::string_t orderId) std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/store/order/{orderId}"); - boost::replace_all(path, U("{") U("orderId") U("}"), ApiClient::parameterToString(orderId)); + utility::string_t path = utility::conversions::to_string_t("/store/order/{orderId}"); + boost::replace_all(path, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("orderId") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(orderId)); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -50,32 +50,32 @@ pplx::task StoreApi::deleteOrder(utility::string_t orderId) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("StoreApi->deleteOrder does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("StoreApi->deleteOrder does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; @@ -84,22 +84,22 @@ pplx::task StoreApi::deleteOrder(utility::string_t orderId) utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(415, U("StoreApi->deleteOrder does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("StoreApi->deleteOrder does not consume any supported media type")); } - return m_ApiClient->callApi(path, U("DELETE"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("DELETE"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -110,18 +110,18 @@ pplx::task StoreApi::deleteOrder(utility::string_t orderId) if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling deleteOrder: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling deleteOrder: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling deleteOrder: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling deleteOrder: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -138,7 +138,7 @@ pplx::task> StoreApi::getInventory() std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/store/inventory"); + utility::string_t path = utility::conversions::to_string_t("/store/inventory"); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -146,31 +146,31 @@ pplx::task> StoreApi::getInventory() std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("StoreApi->getInventory does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("StoreApi->getInventory does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; @@ -179,30 +179,30 @@ pplx::task> StoreApi::getInventory() utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(415, U("StoreApi->getInventory does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("StoreApi->getInventory does not consume any supported media type")); } // authentication (api_key) required { - utility::string_t apiKey = apiConfiguration->getApiKey(U("api_key")); + utility::string_t apiKey = apiConfiguration->getApiKey(utility::conversions::to_string_t("api_key")); if ( apiKey.size() > 0 ) { - headerParams[U("api_key")] = apiKey; + headerParams[utility::conversions::to_string_t("api_key")] = apiKey; } } - return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -213,18 +213,18 @@ pplx::task> StoreApi::getInventory() if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling getInventory: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling getInventory: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling getInventory: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling getInventory: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -235,7 +235,7 @@ pplx::task> StoreApi::getInventory() { std::map result; - if(responseHttpContentType == U("application/json")) + if(responseHttpContentType == utility::conversions::to_string_t("application/json")) { web::json::value json = web::json::value::parse(response); @@ -246,14 +246,14 @@ pplx::task> StoreApi::getInventory() } } - // else if(responseHttpContentType == U("multipart/form-data")) + // else if(responseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) // { // TODO multipart response parsing // } else { throw ApiException(500 - , U("error calling getInventory: unsupported response type")); + , utility::conversions::to_string_t("error calling getInventory: unsupported response type")); } return result; @@ -264,8 +264,8 @@ pplx::task> StoreApi::getOrderById(int64_t orderId) std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/store/order/{orderId}"); - boost::replace_all(path, U("{") U("orderId") U("}"), ApiClient::parameterToString(orderId)); + utility::string_t path = utility::conversions::to_string_t("/store/order/{orderId}"); + boost::replace_all(path, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("orderId") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(orderId)); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -273,32 +273,32 @@ pplx::task> StoreApi::getOrderById(int64_t orderId) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("StoreApi->getOrderById does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("StoreApi->getOrderById does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; @@ -307,22 +307,22 @@ pplx::task> StoreApi::getOrderById(int64_t orderId) utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(415, U("StoreApi->getOrderById does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("StoreApi->getOrderById does not consume any supported media type")); } - return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -333,18 +333,18 @@ pplx::task> StoreApi::getOrderById(int64_t orderId) if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling getOrderById: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling getOrderById: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling getOrderById: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling getOrderById: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -355,20 +355,20 @@ pplx::task> StoreApi::getOrderById(int64_t orderId) { std::shared_ptr result(new Order()); - if(responseHttpContentType == U("application/json")) + if(responseHttpContentType == utility::conversions::to_string_t("application/json")) { web::json::value json = web::json::value::parse(response); result->fromJson(json); } - // else if(responseHttpContentType == U("multipart/form-data")) + // else if(responseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) // { // TODO multipart response parsing // } else { throw ApiException(500 - , U("error calling getOrderById: unsupported response type")); + , utility::conversions::to_string_t("error calling getOrderById: unsupported response type")); } return result; @@ -380,12 +380,12 @@ pplx::task> StoreApi::placeOrder(std::shared_ptr b // verify the required parameter 'body' is set if (body == nullptr) { - throw ApiException(400, U("Missing required parameter 'body' when calling StoreApi->placeOrder")); + throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'body' when calling StoreApi->placeOrder")); } std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/store/order"); + utility::string_t path = utility::conversions::to_string_t("/store/order"); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -393,32 +393,32 @@ pplx::task> StoreApi::placeOrder(std::shared_ptr b std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("StoreApi->placeOrder does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("StoreApi->placeOrder does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; @@ -427,9 +427,9 @@ pplx::task> StoreApi::placeOrder(std::shared_ptr b utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); web::json::value json; json = ModelBase::toJson(body); @@ -437,25 +437,25 @@ pplx::task> StoreApi::placeOrder(std::shared_ptr b httpBody = std::shared_ptr( new JsonBody( json ) ); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); std::shared_ptr multipart(new MultipartFormData); if(body.get()) { - body->toMultipart(multipart, U("body")); + body->toMultipart(multipart, utility::conversions::to_string_t("body")); } httpBody = multipart; - requestHttpContentType += U("; boundary=") + multipart->getBoundary(); + requestHttpContentType += utility::conversions::to_string_t("; boundary=") + multipart->getBoundary(); } else { - throw ApiException(415, U("StoreApi->placeOrder does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("StoreApi->placeOrder does not consume any supported media type")); } - return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -466,18 +466,18 @@ pplx::task> StoreApi::placeOrder(std::shared_ptr b if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling placeOrder: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling placeOrder: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling placeOrder: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling placeOrder: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -488,20 +488,20 @@ pplx::task> StoreApi::placeOrder(std::shared_ptr b { std::shared_ptr result(new Order()); - if(responseHttpContentType == U("application/json")) + if(responseHttpContentType == utility::conversions::to_string_t("application/json")) { web::json::value json = web::json::value::parse(response); result->fromJson(json); } - // else if(responseHttpContentType == U("multipart/form-data")) + // else if(responseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) // { // TODO multipart response parsing // } else { throw ApiException(500 - , U("error calling placeOrder: unsupported response type")); + , utility::conversions::to_string_t("error calling placeOrder: unsupported response type")); } return result; diff --git a/samples/client/petstore/cpprest/api/StoreApi.h b/samples/client/petstore/cpprest/api/StoreApi.h index 7962595aaa0..1f283e34a33 100644 --- a/samples/client/petstore/cpprest/api/StoreApi.h +++ b/samples/client/petstore/cpprest/api/StoreApi.h @@ -16,8 +16,8 @@ * */ -#ifndef StoreApi_H_ -#define StoreApi_H_ +#ifndef IO_SWAGGER_CLIENT_API_StoreApi_H_ +#define IO_SWAGGER_CLIENT_API_StoreApi_H_ #include "ApiClient.h" @@ -80,5 +80,5 @@ protected: } } -#endif /* StoreApi_H_ */ +#endif /* IO_SWAGGER_CLIENT_API_StoreApi_H_ */ diff --git a/samples/client/petstore/cpprest/api/UserApi.cpp b/samples/client/petstore/cpprest/api/UserApi.cpp index 50badbae649..8a820c52ae4 100644 --- a/samples/client/petstore/cpprest/api/UserApi.cpp +++ b/samples/client/petstore/cpprest/api/UserApi.cpp @@ -42,12 +42,12 @@ pplx::task UserApi::createUser(std::shared_ptr body) // verify the required parameter 'body' is set if (body == nullptr) { - throw ApiException(400, U("Missing required parameter 'body' when calling UserApi->createUser")); + throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'body' when calling UserApi->createUser")); } std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/user"); + utility::string_t path = utility::conversions::to_string_t("/user"); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -55,32 +55,32 @@ pplx::task UserApi::createUser(std::shared_ptr body) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("UserApi->createUser does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("UserApi->createUser does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; @@ -89,9 +89,9 @@ pplx::task UserApi::createUser(std::shared_ptr body) utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); web::json::value json; json = ModelBase::toJson(body); @@ -99,25 +99,25 @@ pplx::task UserApi::createUser(std::shared_ptr body) httpBody = std::shared_ptr( new JsonBody( json ) ); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); std::shared_ptr multipart(new MultipartFormData); if(body.get()) { - body->toMultipart(multipart, U("body")); + body->toMultipart(multipart, utility::conversions::to_string_t("body")); } httpBody = multipart; - requestHttpContentType += U("; boundary=") + multipart->getBoundary(); + requestHttpContentType += utility::conversions::to_string_t("; boundary=") + multipart->getBoundary(); } else { - throw ApiException(415, U("UserApi->createUser does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("UserApi->createUser does not consume any supported media type")); } - return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -128,18 +128,18 @@ pplx::task UserApi::createUser(std::shared_ptr body) if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling createUser: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling createUser: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling createUser: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling createUser: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -156,7 +156,7 @@ pplx::task UserApi::createUsersWithArrayInput(std::vector apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/user/createWithArray"); + utility::string_t path = utility::conversions::to_string_t("/user/createWithArray"); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -164,32 +164,32 @@ pplx::task UserApi::createUsersWithArrayInput(std::vector> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("UserApi->createUsersWithArrayInput does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("UserApi->createUsersWithArrayInput does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; @@ -198,9 +198,9 @@ pplx::task UserApi::createUsersWithArrayInput(std::vector UserApi::createUsersWithArrayInput(std::vector( new JsonBody( json ) ); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); std::shared_ptr multipart(new MultipartFormData); { std::vector jsonArray; @@ -227,19 +227,19 @@ pplx::task UserApi::createUsersWithArrayInput(std::vectortoJson() : web::json::value::null() ); } - multipart->add(ModelBase::toHttpContent(U("body"), web::json::value::array(jsonArray), U("application/json"))); + multipart->add(ModelBase::toHttpContent(utility::conversions::to_string_t("body"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json"))); } httpBody = multipart; - requestHttpContentType += U("; boundary=") + multipart->getBoundary(); + requestHttpContentType += utility::conversions::to_string_t("; boundary=") + multipart->getBoundary(); } else { - throw ApiException(415, U("UserApi->createUsersWithArrayInput does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("UserApi->createUsersWithArrayInput does not consume any supported media type")); } - return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -250,18 +250,18 @@ pplx::task UserApi::createUsersWithArrayInput(std::vector= 400) { throw ApiException(response.status_code() - , U("error calling createUsersWithArrayInput: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling createUsersWithArrayInput: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling createUsersWithArrayInput: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling createUsersWithArrayInput: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -278,7 +278,7 @@ pplx::task UserApi::createUsersWithListInput(std::vector apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/user/createWithList"); + utility::string_t path = utility::conversions::to_string_t("/user/createWithList"); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -286,32 +286,32 @@ pplx::task UserApi::createUsersWithListInput(std::vector> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("UserApi->createUsersWithListInput does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("UserApi->createUsersWithListInput does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; @@ -320,9 +320,9 @@ pplx::task UserApi::createUsersWithListInput(std::vector UserApi::createUsersWithListInput(std::vector( new JsonBody( json ) ); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); std::shared_ptr multipart(new MultipartFormData); { std::vector jsonArray; @@ -349,19 +349,19 @@ pplx::task UserApi::createUsersWithListInput(std::vectortoJson() : web::json::value::null() ); } - multipart->add(ModelBase::toHttpContent(U("body"), web::json::value::array(jsonArray), U("application/json"))); + multipart->add(ModelBase::toHttpContent(utility::conversions::to_string_t("body"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json"))); } httpBody = multipart; - requestHttpContentType += U("; boundary=") + multipart->getBoundary(); + requestHttpContentType += utility::conversions::to_string_t("; boundary=") + multipart->getBoundary(); } else { - throw ApiException(415, U("UserApi->createUsersWithListInput does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("UserApi->createUsersWithListInput does not consume any supported media type")); } - return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -372,18 +372,18 @@ pplx::task UserApi::createUsersWithListInput(std::vector= 400) { throw ApiException(response.status_code() - , U("error calling createUsersWithListInput: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling createUsersWithListInput: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling createUsersWithListInput: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling createUsersWithListInput: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -400,8 +400,8 @@ pplx::task UserApi::deleteUser(utility::string_t username) std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/user/{username}"); - boost::replace_all(path, U("{") U("username") U("}"), ApiClient::parameterToString(username)); + utility::string_t path = utility::conversions::to_string_t("/user/{username}"); + boost::replace_all(path, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("username") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(username)); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -409,32 +409,32 @@ pplx::task UserApi::deleteUser(utility::string_t username) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("UserApi->deleteUser does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("UserApi->deleteUser does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; @@ -443,22 +443,22 @@ pplx::task UserApi::deleteUser(utility::string_t username) utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(415, U("UserApi->deleteUser does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("UserApi->deleteUser does not consume any supported media type")); } - return m_ApiClient->callApi(path, U("DELETE"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("DELETE"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -469,18 +469,18 @@ pplx::task UserApi::deleteUser(utility::string_t username) if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling deleteUser: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling deleteUser: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling deleteUser: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling deleteUser: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -497,8 +497,8 @@ pplx::task> UserApi::getUserByName(utility::string_t usern std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/user/{username}"); - boost::replace_all(path, U("{") U("username") U("}"), ApiClient::parameterToString(username)); + utility::string_t path = utility::conversions::to_string_t("/user/{username}"); + boost::replace_all(path, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("username") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(username)); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -506,32 +506,32 @@ pplx::task> UserApi::getUserByName(utility::string_t usern std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("UserApi->getUserByName does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("UserApi->getUserByName does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; @@ -540,22 +540,22 @@ pplx::task> UserApi::getUserByName(utility::string_t usern utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(415, U("UserApi->getUserByName does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("UserApi->getUserByName does not consume any supported media type")); } - return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -566,18 +566,18 @@ pplx::task> UserApi::getUserByName(utility::string_t usern if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling getUserByName: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling getUserByName: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling getUserByName: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling getUserByName: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -588,20 +588,20 @@ pplx::task> UserApi::getUserByName(utility::string_t usern { std::shared_ptr result(new User()); - if(responseHttpContentType == U("application/json")) + if(responseHttpContentType == utility::conversions::to_string_t("application/json")) { web::json::value json = web::json::value::parse(response); result->fromJson(json); } - // else if(responseHttpContentType == U("multipart/form-data")) + // else if(responseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) // { // TODO multipart response parsing // } else { throw ApiException(500 - , U("error calling getUserByName: unsupported response type")); + , utility::conversions::to_string_t("error calling getUserByName: unsupported response type")); } return result; @@ -612,7 +612,7 @@ pplx::task UserApi::loginUser(utility::string_t username, uti std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/user/login"); + utility::string_t path = utility::conversions::to_string_t("/user/login"); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -620,69 +620,69 @@ pplx::task UserApi::loginUser(utility::string_t username, uti std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("text/plain"); + responseHttpContentType = utility::conversions::to_string_t("text/plain"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } // plain text - else if( responseHttpContentTypes.find(U("text/plain")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("text/plain")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("text/plain"); + responseHttpContentType = utility::conversions::to_string_t("text/plain"); } else { - throw ApiException(400, U("UserApi->loginUser does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("UserApi->loginUser does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; { - queryParams[U("username")] = ApiClient::parameterToString(username); + queryParams[utility::conversions::to_string_t("username")] = ApiClient::parameterToString(username); } { - queryParams[U("password")] = ApiClient::parameterToString(password); + queryParams[utility::conversions::to_string_t("password")] = ApiClient::parameterToString(password); } std::shared_ptr httpBody; utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(415, U("UserApi->loginUser does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("UserApi->loginUser does not consume any supported media type")); } - return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -693,18 +693,18 @@ pplx::task UserApi::loginUser(utility::string_t username, uti if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling loginUser: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling loginUser: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling loginUser: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling loginUser: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -713,27 +713,27 @@ pplx::task UserApi::loginUser(utility::string_t username, uti }) .then([=](utility::string_t response) { - utility::string_t result(U("")); + utility::string_t result(utility::conversions::to_string_t("")); - if(responseHttpContentType == U("application/json")) + if(responseHttpContentType == utility::conversions::to_string_t("application/json")) { web::json::value json = web::json::value::parse(response); result = ModelBase::stringFromJson(json); } - else if(responseHttpContentType == U("text/plain")) + else if(responseHttpContentType == utility::conversions::to_string_t("text/plain")) { result = response; } - // else if(responseHttpContentType == U("multipart/form-data")) + // else if(responseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) // { // TODO multipart response parsing // } else { throw ApiException(500 - , U("error calling loginUser: unsupported response type")); + , utility::conversions::to_string_t("error calling loginUser: unsupported response type")); } return result; @@ -744,7 +744,7 @@ pplx::task UserApi::logoutUser() std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/user/logout"); + utility::string_t path = utility::conversions::to_string_t("/user/logout"); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -752,32 +752,32 @@ pplx::task UserApi::logoutUser() std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("UserApi->logoutUser does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("UserApi->logoutUser does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; @@ -786,22 +786,22 @@ pplx::task UserApi::logoutUser() utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(415, U("UserApi->logoutUser does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("UserApi->logoutUser does not consume any supported media type")); } - return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -812,18 +812,18 @@ pplx::task UserApi::logoutUser() if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling logoutUser: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling logoutUser: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling logoutUser: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling logoutUser: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } @@ -841,13 +841,13 @@ pplx::task UserApi::updateUser(utility::string_t username, std::shared_ptr // verify the required parameter 'body' is set if (body == nullptr) { - throw ApiException(400, U("Missing required parameter 'body' when calling UserApi->updateUser")); + throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'body' when calling UserApi->updateUser")); } std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); - utility::string_t path = U("/user/{username}"); - boost::replace_all(path, U("{") U("username") U("}"), ApiClient::parameterToString(username)); + utility::string_t path = utility::conversions::to_string_t("/user/{username}"); + boost::replace_all(path, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("username") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(username)); std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); @@ -855,32 +855,32 @@ pplx::task UserApi::updateUser(utility::string_t username, std::shared_ptr std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); - responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/xml") ); + responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON - else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("application/json"); + responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata - else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { - responseHttpContentType = U("multipart/form-data"); + responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { - throw ApiException(400, U("UserApi->updateUser does not produce any supported media type")); + throw ApiException(400, utility::conversions::to_string_t("UserApi->updateUser does not produce any supported media type")); } - headerParams[U("Accept")] = responseHttpContentType; + headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set consumeHttpContentTypes; @@ -889,9 +889,9 @@ pplx::task UserApi::updateUser(utility::string_t username, std::shared_ptr utility::string_t requestHttpContentType; // use JSON if possible - if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("application/json"); + requestHttpContentType = utility::conversions::to_string_t("application/json"); web::json::value json; json = ModelBase::toJson(body); @@ -899,25 +899,25 @@ pplx::task UserApi::updateUser(utility::string_t username, std::shared_ptr httpBody = std::shared_ptr( new JsonBody( json ) ); } // multipart formdata - else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { - requestHttpContentType = U("multipart/form-data"); + requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); std::shared_ptr multipart(new MultipartFormData); if(body.get()) { - body->toMultipart(multipart, U("body")); + body->toMultipart(multipart, utility::conversions::to_string_t("body")); } httpBody = multipart; - requestHttpContentType += U("; boundary=") + multipart->getBoundary(); + requestHttpContentType += utility::conversions::to_string_t("; boundary=") + multipart->getBoundary(); } else { - throw ApiException(415, U("UserApi->updateUser does not consume any supported media type")); + throw ApiException(415, utility::conversions::to_string_t("UserApi->updateUser does not consume any supported media type")); } - return m_ApiClient->callApi(path, U("PUT"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + return m_ApiClient->callApi(path, utility::conversions::to_string_t("PUT"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK @@ -928,18 +928,18 @@ pplx::task UserApi::updateUser(utility::string_t username, std::shared_ptr if (response.status_code() >= 400) { throw ApiException(response.status_code() - , U("error calling updateUser: ") + response.reason_phrase() + , utility::conversions::to_string_t("error calling updateUser: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } // check response content type - if(response.headers().has(U("Content-Type"))) + if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { - utility::string_t contentType = response.headers()[U("Content-Type")]; + utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 - , U("error calling updateUser: unexpected response type: ") + contentType + , utility::conversions::to_string_t("error calling updateUser: unexpected response type: ") + contentType , std::make_shared(response.extract_utf8string(true).get())); } } diff --git a/samples/client/petstore/cpprest/api/UserApi.h b/samples/client/petstore/cpprest/api/UserApi.h index 92d720c6a00..4b694b8626b 100644 --- a/samples/client/petstore/cpprest/api/UserApi.h +++ b/samples/client/petstore/cpprest/api/UserApi.h @@ -16,8 +16,8 @@ * */ -#ifndef UserApi_H_ -#define UserApi_H_ +#ifndef IO_SWAGGER_CLIENT_API_UserApi_H_ +#define IO_SWAGGER_CLIENT_API_UserApi_H_ #include "ApiClient.h" @@ -112,5 +112,5 @@ protected: } } -#endif /* UserApi_H_ */ +#endif /* IO_SWAGGER_CLIENT_API_UserApi_H_ */ diff --git a/samples/client/petstore/cpprest/model/ApiResponse.cpp b/samples/client/petstore/cpprest/model/ApiResponse.cpp index ec763752cb7..7b51c7b94d5 100644 --- a/samples/client/petstore/cpprest/model/ApiResponse.cpp +++ b/samples/client/petstore/cpprest/model/ApiResponse.cpp @@ -23,9 +23,9 @@ ApiResponse::ApiResponse() { m_Code = 0; m_CodeIsSet = false; - m_Type = U(""); + m_Type = utility::conversions::to_string_t(""); m_TypeIsSet = false; - m_Message = U(""); + m_Message = utility::conversions::to_string_t(""); m_MessageIsSet = false; } @@ -44,15 +44,15 @@ web::json::value ApiResponse::toJson() const if(m_CodeIsSet) { - val[U("code")] = ModelBase::toJson(m_Code); + val[utility::conversions::to_string_t("code")] = ModelBase::toJson(m_Code); } if(m_TypeIsSet) { - val[U("type")] = ModelBase::toJson(m_Type); + val[utility::conversions::to_string_t("type")] = ModelBase::toJson(m_Type); } if(m_MessageIsSet) { - val[U("message")] = ModelBase::toJson(m_Message); + val[utility::conversions::to_string_t("message")] = ModelBase::toJson(m_Message); } return val; @@ -60,40 +60,40 @@ web::json::value ApiResponse::toJson() const void ApiResponse::fromJson(web::json::value& val) { - if(val.has_field(U("code"))) + if(val.has_field(utility::conversions::to_string_t("code"))) { - setCode(ModelBase::int32_tFromJson(val[U("code")])); + setCode(ModelBase::int32_tFromJson(val[utility::conversions::to_string_t("code")])); } - if(val.has_field(U("type"))) + if(val.has_field(utility::conversions::to_string_t("type"))) { - setType(ModelBase::stringFromJson(val[U("type")])); + setType(ModelBase::stringFromJson(val[utility::conversions::to_string_t("type")])); } - if(val.has_field(U("message"))) + if(val.has_field(utility::conversions::to_string_t("message"))) { - setMessage(ModelBase::stringFromJson(val[U("message")])); + setMessage(ModelBase::stringFromJson(val[utility::conversions::to_string_t("message")])); } } void ApiResponse::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const { utility::string_t namePrefix = prefix; - if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { - namePrefix += U("."); + namePrefix += utility::conversions::to_string_t("."); } if(m_CodeIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("code"), m_Code)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("code"), m_Code)); } if(m_TypeIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("type"), m_Type)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("type"), m_Type)); } if(m_MessageIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("message"), m_Message)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("message"), m_Message)); } } @@ -101,22 +101,22 @@ void ApiResponse::toMultipart(std::shared_ptr multipart, cons void ApiResponse::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) { utility::string_t namePrefix = prefix; - if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { - namePrefix += U("."); + namePrefix += utility::conversions::to_string_t("."); } - if(multipart->hasContent(U("code"))) + if(multipart->hasContent(utility::conversions::to_string_t("code"))) { - setCode(ModelBase::int32_tFromHttpContent(multipart->getContent(U("code")))); + setCode(ModelBase::int32_tFromHttpContent(multipart->getContent(utility::conversions::to_string_t("code")))); } - if(multipart->hasContent(U("type"))) + if(multipart->hasContent(utility::conversions::to_string_t("type"))) { - setType(ModelBase::stringFromHttpContent(multipart->getContent(U("type")))); + setType(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("type")))); } - if(multipart->hasContent(U("message"))) + if(multipart->hasContent(utility::conversions::to_string_t("message"))) { - setMessage(ModelBase::stringFromHttpContent(multipart->getContent(U("message")))); + setMessage(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("message")))); } } diff --git a/samples/client/petstore/cpprest/model/ApiResponse.h b/samples/client/petstore/cpprest/model/ApiResponse.h index ff7ebe5f8f2..248d080d830 100644 --- a/samples/client/petstore/cpprest/model/ApiResponse.h +++ b/samples/client/petstore/cpprest/model/ApiResponse.h @@ -16,8 +16,8 @@ * Describes the result of uploading an image resource */ -#ifndef ApiResponse_H_ -#define ApiResponse_H_ +#ifndef IO_SWAGGER_CLIENT_MODEL_ApiResponse_H_ +#define IO_SWAGGER_CLIENT_MODEL_ApiResponse_H_ #include "ModelBase.h" @@ -89,4 +89,4 @@ protected: } } -#endif /* ApiResponse_H_ */ +#endif /* IO_SWAGGER_CLIENT_MODEL_ApiResponse_H_ */ diff --git a/samples/client/petstore/cpprest/model/Category.cpp b/samples/client/petstore/cpprest/model/Category.cpp index 5c5c3368f65..4362719cb9c 100644 --- a/samples/client/petstore/cpprest/model/Category.cpp +++ b/samples/client/petstore/cpprest/model/Category.cpp @@ -23,7 +23,7 @@ Category::Category() { m_Id = 0L; m_IdIsSet = false; - m_Name = U(""); + m_Name = utility::conversions::to_string_t(""); m_NameIsSet = false; } @@ -42,11 +42,11 @@ web::json::value Category::toJson() const if(m_IdIsSet) { - val[U("id")] = ModelBase::toJson(m_Id); + val[utility::conversions::to_string_t("id")] = ModelBase::toJson(m_Id); } if(m_NameIsSet) { - val[U("name")] = ModelBase::toJson(m_Name); + val[utility::conversions::to_string_t("name")] = ModelBase::toJson(m_Name); } return val; @@ -54,31 +54,31 @@ web::json::value Category::toJson() const void Category::fromJson(web::json::value& val) { - if(val.has_field(U("id"))) + if(val.has_field(utility::conversions::to_string_t("id"))) { - setId(ModelBase::int64_tFromJson(val[U("id")])); + setId(ModelBase::int64_tFromJson(val[utility::conversions::to_string_t("id")])); } - if(val.has_field(U("name"))) + if(val.has_field(utility::conversions::to_string_t("name"))) { - setName(ModelBase::stringFromJson(val[U("name")])); + setName(ModelBase::stringFromJson(val[utility::conversions::to_string_t("name")])); } } void Category::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const { utility::string_t namePrefix = prefix; - if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { - namePrefix += U("."); + namePrefix += utility::conversions::to_string_t("."); } if(m_IdIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("id"), m_Id)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("id"), m_Id)); } if(m_NameIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("name"), m_Name)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("name"), m_Name)); } } @@ -86,18 +86,18 @@ void Category::toMultipart(std::shared_ptr multipart, const u void Category::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) { utility::string_t namePrefix = prefix; - if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { - namePrefix += U("."); + namePrefix += utility::conversions::to_string_t("."); } - if(multipart->hasContent(U("id"))) + if(multipart->hasContent(utility::conversions::to_string_t("id"))) { - setId(ModelBase::int64_tFromHttpContent(multipart->getContent(U("id")))); + setId(ModelBase::int64_tFromHttpContent(multipart->getContent(utility::conversions::to_string_t("id")))); } - if(multipart->hasContent(U("name"))) + if(multipart->hasContent(utility::conversions::to_string_t("name"))) { - setName(ModelBase::stringFromHttpContent(multipart->getContent(U("name")))); + setName(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("name")))); } } diff --git a/samples/client/petstore/cpprest/model/Category.h b/samples/client/petstore/cpprest/model/Category.h index c07a4f55b4d..16b94d97cf0 100644 --- a/samples/client/petstore/cpprest/model/Category.h +++ b/samples/client/petstore/cpprest/model/Category.h @@ -16,8 +16,8 @@ * A category for a pet */ -#ifndef Category_H_ -#define Category_H_ +#ifndef IO_SWAGGER_CLIENT_MODEL_Category_H_ +#define IO_SWAGGER_CLIENT_MODEL_Category_H_ #include "ModelBase.h" @@ -80,4 +80,4 @@ protected: } } -#endif /* Category_H_ */ +#endif /* IO_SWAGGER_CLIENT_MODEL_Category_H_ */ diff --git a/samples/client/petstore/cpprest/model/Order.cpp b/samples/client/petstore/cpprest/model/Order.cpp index b95222f10d2..60b30a9a46d 100644 --- a/samples/client/petstore/cpprest/model/Order.cpp +++ b/samples/client/petstore/cpprest/model/Order.cpp @@ -29,7 +29,7 @@ Order::Order() m_QuantityIsSet = false; m_ShipDate = utility::datetime(); m_ShipDateIsSet = false; - m_Status = U(""); + m_Status = utility::conversions::to_string_t(""); m_StatusIsSet = false; m_Complete = false; m_CompleteIsSet = false; @@ -50,27 +50,27 @@ web::json::value Order::toJson() const if(m_IdIsSet) { - val[U("id")] = ModelBase::toJson(m_Id); + val[utility::conversions::to_string_t("id")] = ModelBase::toJson(m_Id); } if(m_PetIdIsSet) { - val[U("petId")] = ModelBase::toJson(m_PetId); + val[utility::conversions::to_string_t("petId")] = ModelBase::toJson(m_PetId); } if(m_QuantityIsSet) { - val[U("quantity")] = ModelBase::toJson(m_Quantity); + val[utility::conversions::to_string_t("quantity")] = ModelBase::toJson(m_Quantity); } if(m_ShipDateIsSet) { - val[U("shipDate")] = ModelBase::toJson(m_ShipDate); + val[utility::conversions::to_string_t("shipDate")] = ModelBase::toJson(m_ShipDate); } if(m_StatusIsSet) { - val[U("status")] = ModelBase::toJson(m_Status); + val[utility::conversions::to_string_t("status")] = ModelBase::toJson(m_Status); } if(m_CompleteIsSet) { - val[U("complete")] = ModelBase::toJson(m_Complete); + val[utility::conversions::to_string_t("complete")] = ModelBase::toJson(m_Complete); } return val; @@ -78,99 +78,99 @@ web::json::value Order::toJson() const void Order::fromJson(web::json::value& val) { - if(val.has_field(U("id"))) + if(val.has_field(utility::conversions::to_string_t("id"))) { - setId(ModelBase::int64_tFromJson(val[U("id")])); + setId(ModelBase::int64_tFromJson(val[utility::conversions::to_string_t("id")])); } - if(val.has_field(U("petId"))) + if(val.has_field(utility::conversions::to_string_t("petId"))) { - setPetId(ModelBase::int64_tFromJson(val[U("petId")])); + setPetId(ModelBase::int64_tFromJson(val[utility::conversions::to_string_t("petId")])); } - if(val.has_field(U("quantity"))) + if(val.has_field(utility::conversions::to_string_t("quantity"))) { - setQuantity(ModelBase::int32_tFromJson(val[U("quantity")])); + setQuantity(ModelBase::int32_tFromJson(val[utility::conversions::to_string_t("quantity")])); } - if(val.has_field(U("shipDate"))) + if(val.has_field(utility::conversions::to_string_t("shipDate"))) { - setShipDate(ModelBase::dateFromJson(val[U("shipDate")])); + setShipDate(ModelBase::dateFromJson(val[utility::conversions::to_string_t("shipDate")])); } - if(val.has_field(U("status"))) + if(val.has_field(utility::conversions::to_string_t("status"))) { - setStatus(ModelBase::stringFromJson(val[U("status")])); + setStatus(ModelBase::stringFromJson(val[utility::conversions::to_string_t("status")])); } - if(val.has_field(U("complete"))) + if(val.has_field(utility::conversions::to_string_t("complete"))) { - setComplete(ModelBase::boolFromJson(val[U("complete")])); + setComplete(ModelBase::boolFromJson(val[utility::conversions::to_string_t("complete")])); } } void Order::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const { utility::string_t namePrefix = prefix; - if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { - namePrefix += U("."); + namePrefix += utility::conversions::to_string_t("."); } if(m_IdIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("id"), m_Id)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("id"), m_Id)); } if(m_PetIdIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("petId"), m_PetId)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("petId"), m_PetId)); } if(m_QuantityIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("quantity"), m_Quantity)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("quantity"), m_Quantity)); } if(m_ShipDateIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("shipDate"), m_ShipDate)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("shipDate"), m_ShipDate)); } if(m_StatusIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("status"), m_Status)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("status"), m_Status)); } if(m_CompleteIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("complete"), m_Complete)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("complete"), m_Complete)); } } void Order::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) { utility::string_t namePrefix = prefix; - if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { - namePrefix += U("."); + namePrefix += utility::conversions::to_string_t("."); } - if(multipart->hasContent(U("id"))) + if(multipart->hasContent(utility::conversions::to_string_t("id"))) { - setId(ModelBase::int64_tFromHttpContent(multipart->getContent(U("id")))); + setId(ModelBase::int64_tFromHttpContent(multipart->getContent(utility::conversions::to_string_t("id")))); } - if(multipart->hasContent(U("petId"))) + if(multipart->hasContent(utility::conversions::to_string_t("petId"))) { - setPetId(ModelBase::int64_tFromHttpContent(multipart->getContent(U("petId")))); + setPetId(ModelBase::int64_tFromHttpContent(multipart->getContent(utility::conversions::to_string_t("petId")))); } - if(multipart->hasContent(U("quantity"))) + if(multipart->hasContent(utility::conversions::to_string_t("quantity"))) { - setQuantity(ModelBase::int32_tFromHttpContent(multipart->getContent(U("quantity")))); + setQuantity(ModelBase::int32_tFromHttpContent(multipart->getContent(utility::conversions::to_string_t("quantity")))); } - if(multipart->hasContent(U("shipDate"))) + if(multipart->hasContent(utility::conversions::to_string_t("shipDate"))) { - setShipDate(ModelBase::dateFromHttpContent(multipart->getContent(U("shipDate")))); + setShipDate(ModelBase::dateFromHttpContent(multipart->getContent(utility::conversions::to_string_t("shipDate")))); } - if(multipart->hasContent(U("status"))) + if(multipart->hasContent(utility::conversions::to_string_t("status"))) { - setStatus(ModelBase::stringFromHttpContent(multipart->getContent(U("status")))); + setStatus(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("status")))); } - if(multipart->hasContent(U("complete"))) + if(multipart->hasContent(utility::conversions::to_string_t("complete"))) { - setComplete(ModelBase::boolFromHttpContent(multipart->getContent(U("complete")))); + setComplete(ModelBase::boolFromHttpContent(multipart->getContent(utility::conversions::to_string_t("complete")))); } } @@ -279,7 +279,7 @@ void Order::unsetStatus() m_StatusIsSet = false; } -bool Order::getComplete() const +bool Order::isComplete() const { return m_Complete; } diff --git a/samples/client/petstore/cpprest/model/Order.h b/samples/client/petstore/cpprest/model/Order.h index fe47916f1e1..844a0fcd9fe 100644 --- a/samples/client/petstore/cpprest/model/Order.h +++ b/samples/client/petstore/cpprest/model/Order.h @@ -16,8 +16,8 @@ * An order for a pets from the pet store */ -#ifndef Order_H_ -#define Order_H_ +#ifndef IO_SWAGGER_CLIENT_MODEL_Order_H_ +#define IO_SWAGGER_CLIENT_MODEL_Order_H_ #include "ModelBase.h" @@ -91,7 +91,7 @@ public: /// /// /// - bool getComplete() const; + bool isComplete() const; bool completeIsSet() const; void unsetComplete(); void setComplete(bool value); @@ -116,4 +116,4 @@ protected: } } -#endif /* Order_H_ */ +#endif /* IO_SWAGGER_CLIENT_MODEL_Order_H_ */ diff --git a/samples/client/petstore/cpprest/model/Pet.cpp b/samples/client/petstore/cpprest/model/Pet.cpp index e6e973809b7..f2e23fb8ea7 100644 --- a/samples/client/petstore/cpprest/model/Pet.cpp +++ b/samples/client/petstore/cpprest/model/Pet.cpp @@ -24,9 +24,9 @@ Pet::Pet() m_Id = 0L; m_IdIsSet = false; m_CategoryIsSet = false; - m_Name = U(""); + m_Name = utility::conversions::to_string_t(""); m_TagsIsSet = false; - m_Status = U(""); + m_Status = utility::conversions::to_string_t(""); m_StatusIsSet = false; } @@ -45,20 +45,20 @@ web::json::value Pet::toJson() const if(m_IdIsSet) { - val[U("id")] = ModelBase::toJson(m_Id); + val[utility::conversions::to_string_t("id")] = ModelBase::toJson(m_Id); } if(m_CategoryIsSet) { - val[U("category")] = ModelBase::toJson(m_Category); + val[utility::conversions::to_string_t("category")] = ModelBase::toJson(m_Category); } - val[U("name")] = ModelBase::toJson(m_Name); + val[utility::conversions::to_string_t("name")] = ModelBase::toJson(m_Name); { std::vector jsonArray; for( auto& item : m_PhotoUrls ) { jsonArray.push_back(ModelBase::toJson(item)); } - val[U("photoUrls")] = web::json::value::array(jsonArray); + val[utility::conversions::to_string_t("photoUrls")] = web::json::value::array(jsonArray); } { std::vector jsonArray; @@ -68,12 +68,12 @@ web::json::value Pet::toJson() const } if(jsonArray.size() > 0) { - val[U("tags")] = web::json::value::array(jsonArray); + val[utility::conversions::to_string_t("tags")] = web::json::value::array(jsonArray); } } if(m_StatusIsSet) { - val[U("status")] = ModelBase::toJson(m_Status); + val[utility::conversions::to_string_t("status")] = ModelBase::toJson(m_Status); } return val; @@ -81,24 +81,24 @@ web::json::value Pet::toJson() const void Pet::fromJson(web::json::value& val) { - if(val.has_field(U("id"))) + if(val.has_field(utility::conversions::to_string_t("id"))) { - setId(ModelBase::int64_tFromJson(val[U("id")])); + setId(ModelBase::int64_tFromJson(val[utility::conversions::to_string_t("id")])); } - if(val.has_field(U("category"))) + if(val.has_field(utility::conversions::to_string_t("category"))) { - if(!val[U("category")].is_null()) + if(!val[utility::conversions::to_string_t("category")].is_null()) { std::shared_ptr newItem(new Category()); - newItem->fromJson(val[U("category")]); + newItem->fromJson(val[utility::conversions::to_string_t("category")]); setCategory( newItem ); } } - setName(ModelBase::stringFromJson(val[U("name")])); + setName(ModelBase::stringFromJson(val[utility::conversions::to_string_t("name")])); { m_PhotoUrls.clear(); std::vector jsonArray; - for( auto& item : val[U("photoUrls")].as_array() ) + for( auto& item : val[utility::conversions::to_string_t("photoUrls")].as_array() ) { m_PhotoUrls.push_back(ModelBase::stringFromJson(item)); } @@ -106,9 +106,9 @@ void Pet::fromJson(web::json::value& val) { m_Tags.clear(); std::vector jsonArray; - if(val.has_field(U("tags"))) + if(val.has_field(utility::conversions::to_string_t("tags"))) { - for( auto& item : val[U("tags")].as_array() ) + for( auto& item : val[utility::conversions::to_string_t("tags")].as_array() ) { if(item.is_null()) { @@ -123,40 +123,40 @@ void Pet::fromJson(web::json::value& val) } } } - if(val.has_field(U("status"))) + if(val.has_field(utility::conversions::to_string_t("status"))) { - setStatus(ModelBase::stringFromJson(val[U("status")])); + setStatus(ModelBase::stringFromJson(val[utility::conversions::to_string_t("status")])); } } void Pet::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const { utility::string_t namePrefix = prefix; - if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { - namePrefix += U("."); + namePrefix += utility::conversions::to_string_t("."); } if(m_IdIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("id"), m_Id)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("id"), m_Id)); } if(m_CategoryIsSet) { if (m_Category.get()) { - m_Category->toMultipart(multipart, U("category.")); + m_Category->toMultipart(multipart, utility::conversions::to_string_t("category.")); } } - multipart->add(ModelBase::toHttpContent(namePrefix + U("name"), m_Name)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("name"), m_Name)); { std::vector jsonArray; for( auto& item : m_PhotoUrls ) { jsonArray.push_back(ModelBase::toJson(item)); } - multipart->add(ModelBase::toHttpContent(namePrefix + U("photoUrls"), web::json::value::array(jsonArray), U("application/json"))); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("photoUrls"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json"))); } { std::vector jsonArray; @@ -167,12 +167,12 @@ void Pet::toMultipart(std::shared_ptr multipart, const utilit if(jsonArray.size() > 0) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("tags"), web::json::value::array(jsonArray), U("application/json"))); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("tags"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json"))); } } if(m_StatusIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("status"), m_Status)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("status"), m_Status)); } } @@ -180,29 +180,29 @@ void Pet::toMultipart(std::shared_ptr multipart, const utilit void Pet::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) { utility::string_t namePrefix = prefix; - if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { - namePrefix += U("."); + namePrefix += utility::conversions::to_string_t("."); } - if(multipart->hasContent(U("id"))) + if(multipart->hasContent(utility::conversions::to_string_t("id"))) { - setId(ModelBase::int64_tFromHttpContent(multipart->getContent(U("id")))); + setId(ModelBase::int64_tFromHttpContent(multipart->getContent(utility::conversions::to_string_t("id")))); } - if(multipart->hasContent(U("category"))) + if(multipart->hasContent(utility::conversions::to_string_t("category"))) { - if(multipart->hasContent(U("category"))) + if(multipart->hasContent(utility::conversions::to_string_t("category"))) { std::shared_ptr newItem(new Category()); - newItem->fromMultiPart(multipart, U("category.")); + newItem->fromMultiPart(multipart, utility::conversions::to_string_t("category.")); setCategory( newItem ); } } - setName(ModelBase::stringFromHttpContent(multipart->getContent(U("name")))); + setName(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("name")))); { m_PhotoUrls.clear(); - web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(U("photoUrls")))); + web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("photoUrls")))); for( auto& item : jsonArray.as_array() ) { m_PhotoUrls.push_back(ModelBase::stringFromJson(item)); @@ -210,10 +210,10 @@ void Pet::fromMultiPart(std::shared_ptr multipart, const util } { m_Tags.clear(); - if(multipart->hasContent(U("tags"))) + if(multipart->hasContent(utility::conversions::to_string_t("tags"))) { - web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(U("tags")))); + web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("tags")))); for( auto& item : jsonArray.as_array() ) { if(item.is_null()) @@ -229,9 +229,9 @@ void Pet::fromMultiPart(std::shared_ptr multipart, const util } } } - if(multipart->hasContent(U("status"))) + if(multipart->hasContent(utility::conversions::to_string_t("status"))) { - setStatus(ModelBase::stringFromHttpContent(multipart->getContent(U("status")))); + setStatus(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("status")))); } } diff --git a/samples/client/petstore/cpprest/model/Pet.h b/samples/client/petstore/cpprest/model/Pet.h index 42e534ae4e1..0360c6777c6 100644 --- a/samples/client/petstore/cpprest/model/Pet.h +++ b/samples/client/petstore/cpprest/model/Pet.h @@ -16,16 +16,16 @@ * A pet for sale in the pet store */ -#ifndef Pet_H_ -#define Pet_H_ +#ifndef IO_SWAGGER_CLIENT_MODEL_Pet_H_ +#define IO_SWAGGER_CLIENT_MODEL_Pet_H_ #include "ModelBase.h" -#include "Category.h" -#include -#include #include "Tag.h" +#include +#include "Category.h" +#include namespace io { namespace swagger { @@ -113,4 +113,4 @@ protected: } } -#endif /* Pet_H_ */ +#endif /* IO_SWAGGER_CLIENT_MODEL_Pet_H_ */ diff --git a/samples/client/petstore/cpprest/model/Tag.cpp b/samples/client/petstore/cpprest/model/Tag.cpp index 7bf3333a5c6..2594f8553d3 100644 --- a/samples/client/petstore/cpprest/model/Tag.cpp +++ b/samples/client/petstore/cpprest/model/Tag.cpp @@ -23,7 +23,7 @@ Tag::Tag() { m_Id = 0L; m_IdIsSet = false; - m_Name = U(""); + m_Name = utility::conversions::to_string_t(""); m_NameIsSet = false; } @@ -42,11 +42,11 @@ web::json::value Tag::toJson() const if(m_IdIsSet) { - val[U("id")] = ModelBase::toJson(m_Id); + val[utility::conversions::to_string_t("id")] = ModelBase::toJson(m_Id); } if(m_NameIsSet) { - val[U("name")] = ModelBase::toJson(m_Name); + val[utility::conversions::to_string_t("name")] = ModelBase::toJson(m_Name); } return val; @@ -54,31 +54,31 @@ web::json::value Tag::toJson() const void Tag::fromJson(web::json::value& val) { - if(val.has_field(U("id"))) + if(val.has_field(utility::conversions::to_string_t("id"))) { - setId(ModelBase::int64_tFromJson(val[U("id")])); + setId(ModelBase::int64_tFromJson(val[utility::conversions::to_string_t("id")])); } - if(val.has_field(U("name"))) + if(val.has_field(utility::conversions::to_string_t("name"))) { - setName(ModelBase::stringFromJson(val[U("name")])); + setName(ModelBase::stringFromJson(val[utility::conversions::to_string_t("name")])); } } void Tag::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const { utility::string_t namePrefix = prefix; - if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { - namePrefix += U("."); + namePrefix += utility::conversions::to_string_t("."); } if(m_IdIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("id"), m_Id)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("id"), m_Id)); } if(m_NameIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("name"), m_Name)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("name"), m_Name)); } } @@ -86,18 +86,18 @@ void Tag::toMultipart(std::shared_ptr multipart, const utilit void Tag::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) { utility::string_t namePrefix = prefix; - if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { - namePrefix += U("."); + namePrefix += utility::conversions::to_string_t("."); } - if(multipart->hasContent(U("id"))) + if(multipart->hasContent(utility::conversions::to_string_t("id"))) { - setId(ModelBase::int64_tFromHttpContent(multipart->getContent(U("id")))); + setId(ModelBase::int64_tFromHttpContent(multipart->getContent(utility::conversions::to_string_t("id")))); } - if(multipart->hasContent(U("name"))) + if(multipart->hasContent(utility::conversions::to_string_t("name"))) { - setName(ModelBase::stringFromHttpContent(multipart->getContent(U("name")))); + setName(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("name")))); } } diff --git a/samples/client/petstore/cpprest/model/Tag.h b/samples/client/petstore/cpprest/model/Tag.h index 24b9e654188..17bd0a0ebb4 100644 --- a/samples/client/petstore/cpprest/model/Tag.h +++ b/samples/client/petstore/cpprest/model/Tag.h @@ -16,8 +16,8 @@ * A tag for a pet */ -#ifndef Tag_H_ -#define Tag_H_ +#ifndef IO_SWAGGER_CLIENT_MODEL_Tag_H_ +#define IO_SWAGGER_CLIENT_MODEL_Tag_H_ #include "ModelBase.h" @@ -80,4 +80,4 @@ protected: } } -#endif /* Tag_H_ */ +#endif /* IO_SWAGGER_CLIENT_MODEL_Tag_H_ */ diff --git a/samples/client/petstore/cpprest/model/User.cpp b/samples/client/petstore/cpprest/model/User.cpp index 87c7929a202..53fe5e3fd87 100644 --- a/samples/client/petstore/cpprest/model/User.cpp +++ b/samples/client/petstore/cpprest/model/User.cpp @@ -23,17 +23,17 @@ User::User() { m_Id = 0L; m_IdIsSet = false; - m_Username = U(""); + m_Username = utility::conversions::to_string_t(""); m_UsernameIsSet = false; - m_FirstName = U(""); + m_FirstName = utility::conversions::to_string_t(""); m_FirstNameIsSet = false; - m_LastName = U(""); + m_LastName = utility::conversions::to_string_t(""); m_LastNameIsSet = false; - m_Email = U(""); + m_Email = utility::conversions::to_string_t(""); m_EmailIsSet = false; - m_Password = U(""); + m_Password = utility::conversions::to_string_t(""); m_PasswordIsSet = false; - m_Phone = U(""); + m_Phone = utility::conversions::to_string_t(""); m_PhoneIsSet = false; m_UserStatus = 0; m_UserStatusIsSet = false; @@ -54,35 +54,35 @@ web::json::value User::toJson() const if(m_IdIsSet) { - val[U("id")] = ModelBase::toJson(m_Id); + val[utility::conversions::to_string_t("id")] = ModelBase::toJson(m_Id); } if(m_UsernameIsSet) { - val[U("username")] = ModelBase::toJson(m_Username); + val[utility::conversions::to_string_t("username")] = ModelBase::toJson(m_Username); } if(m_FirstNameIsSet) { - val[U("firstName")] = ModelBase::toJson(m_FirstName); + val[utility::conversions::to_string_t("firstName")] = ModelBase::toJson(m_FirstName); } if(m_LastNameIsSet) { - val[U("lastName")] = ModelBase::toJson(m_LastName); + val[utility::conversions::to_string_t("lastName")] = ModelBase::toJson(m_LastName); } if(m_EmailIsSet) { - val[U("email")] = ModelBase::toJson(m_Email); + val[utility::conversions::to_string_t("email")] = ModelBase::toJson(m_Email); } if(m_PasswordIsSet) { - val[U("password")] = ModelBase::toJson(m_Password); + val[utility::conversions::to_string_t("password")] = ModelBase::toJson(m_Password); } if(m_PhoneIsSet) { - val[U("phone")] = ModelBase::toJson(m_Phone); + val[utility::conversions::to_string_t("phone")] = ModelBase::toJson(m_Phone); } if(m_UserStatusIsSet) { - val[U("userStatus")] = ModelBase::toJson(m_UserStatus); + val[utility::conversions::to_string_t("userStatus")] = ModelBase::toJson(m_UserStatus); } return val; @@ -90,127 +90,127 @@ web::json::value User::toJson() const void User::fromJson(web::json::value& val) { - if(val.has_field(U("id"))) + if(val.has_field(utility::conversions::to_string_t("id"))) { - setId(ModelBase::int64_tFromJson(val[U("id")])); + setId(ModelBase::int64_tFromJson(val[utility::conversions::to_string_t("id")])); } - if(val.has_field(U("username"))) + if(val.has_field(utility::conversions::to_string_t("username"))) { - setUsername(ModelBase::stringFromJson(val[U("username")])); + setUsername(ModelBase::stringFromJson(val[utility::conversions::to_string_t("username")])); } - if(val.has_field(U("firstName"))) + if(val.has_field(utility::conversions::to_string_t("firstName"))) { - setFirstName(ModelBase::stringFromJson(val[U("firstName")])); + setFirstName(ModelBase::stringFromJson(val[utility::conversions::to_string_t("firstName")])); } - if(val.has_field(U("lastName"))) + if(val.has_field(utility::conversions::to_string_t("lastName"))) { - setLastName(ModelBase::stringFromJson(val[U("lastName")])); + setLastName(ModelBase::stringFromJson(val[utility::conversions::to_string_t("lastName")])); } - if(val.has_field(U("email"))) + if(val.has_field(utility::conversions::to_string_t("email"))) { - setEmail(ModelBase::stringFromJson(val[U("email")])); + setEmail(ModelBase::stringFromJson(val[utility::conversions::to_string_t("email")])); } - if(val.has_field(U("password"))) + if(val.has_field(utility::conversions::to_string_t("password"))) { - setPassword(ModelBase::stringFromJson(val[U("password")])); + setPassword(ModelBase::stringFromJson(val[utility::conversions::to_string_t("password")])); } - if(val.has_field(U("phone"))) + if(val.has_field(utility::conversions::to_string_t("phone"))) { - setPhone(ModelBase::stringFromJson(val[U("phone")])); + setPhone(ModelBase::stringFromJson(val[utility::conversions::to_string_t("phone")])); } - if(val.has_field(U("userStatus"))) + if(val.has_field(utility::conversions::to_string_t("userStatus"))) { - setUserStatus(ModelBase::int32_tFromJson(val[U("userStatus")])); + setUserStatus(ModelBase::int32_tFromJson(val[utility::conversions::to_string_t("userStatus")])); } } void User::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const { utility::string_t namePrefix = prefix; - if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { - namePrefix += U("."); + namePrefix += utility::conversions::to_string_t("."); } if(m_IdIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("id"), m_Id)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("id"), m_Id)); } if(m_UsernameIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("username"), m_Username)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("username"), m_Username)); } if(m_FirstNameIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("firstName"), m_FirstName)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("firstName"), m_FirstName)); } if(m_LastNameIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("lastName"), m_LastName)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("lastName"), m_LastName)); } if(m_EmailIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("email"), m_Email)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("email"), m_Email)); } if(m_PasswordIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("password"), m_Password)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("password"), m_Password)); } if(m_PhoneIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("phone"), m_Phone)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("phone"), m_Phone)); } if(m_UserStatusIsSet) { - multipart->add(ModelBase::toHttpContent(namePrefix + U("userStatus"), m_UserStatus)); + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("userStatus"), m_UserStatus)); } } void User::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) { utility::string_t namePrefix = prefix; - if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { - namePrefix += U("."); + namePrefix += utility::conversions::to_string_t("."); } - if(multipart->hasContent(U("id"))) + if(multipart->hasContent(utility::conversions::to_string_t("id"))) { - setId(ModelBase::int64_tFromHttpContent(multipart->getContent(U("id")))); + setId(ModelBase::int64_tFromHttpContent(multipart->getContent(utility::conversions::to_string_t("id")))); } - if(multipart->hasContent(U("username"))) + if(multipart->hasContent(utility::conversions::to_string_t("username"))) { - setUsername(ModelBase::stringFromHttpContent(multipart->getContent(U("username")))); + setUsername(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("username")))); } - if(multipart->hasContent(U("firstName"))) + if(multipart->hasContent(utility::conversions::to_string_t("firstName"))) { - setFirstName(ModelBase::stringFromHttpContent(multipart->getContent(U("firstName")))); + setFirstName(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("firstName")))); } - if(multipart->hasContent(U("lastName"))) + if(multipart->hasContent(utility::conversions::to_string_t("lastName"))) { - setLastName(ModelBase::stringFromHttpContent(multipart->getContent(U("lastName")))); + setLastName(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("lastName")))); } - if(multipart->hasContent(U("email"))) + if(multipart->hasContent(utility::conversions::to_string_t("email"))) { - setEmail(ModelBase::stringFromHttpContent(multipart->getContent(U("email")))); + setEmail(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("email")))); } - if(multipart->hasContent(U("password"))) + if(multipart->hasContent(utility::conversions::to_string_t("password"))) { - setPassword(ModelBase::stringFromHttpContent(multipart->getContent(U("password")))); + setPassword(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("password")))); } - if(multipart->hasContent(U("phone"))) + if(multipart->hasContent(utility::conversions::to_string_t("phone"))) { - setPhone(ModelBase::stringFromHttpContent(multipart->getContent(U("phone")))); + setPhone(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("phone")))); } - if(multipart->hasContent(U("userStatus"))) + if(multipart->hasContent(utility::conversions::to_string_t("userStatus"))) { - setUserStatus(ModelBase::int32_tFromHttpContent(multipart->getContent(U("userStatus")))); + setUserStatus(ModelBase::int32_tFromHttpContent(multipart->getContent(utility::conversions::to_string_t("userStatus")))); } } diff --git a/samples/client/petstore/cpprest/model/User.h b/samples/client/petstore/cpprest/model/User.h index 69eedb0fcfa..f213883e4c4 100644 --- a/samples/client/petstore/cpprest/model/User.h +++ b/samples/client/petstore/cpprest/model/User.h @@ -16,8 +16,8 @@ * A User who is purchasing from the pet store */ -#ifndef User_H_ -#define User_H_ +#ifndef IO_SWAGGER_CLIENT_MODEL_User_H_ +#define IO_SWAGGER_CLIENT_MODEL_User_H_ #include "ModelBase.h" @@ -134,4 +134,4 @@ protected: } } -#endif /* User_H_ */ +#endif /* IO_SWAGGER_CLIENT_MODEL_User_H_ */ diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/.gitignore b/samples/client/petstore/csharp/SwaggerClientNet40/.gitignore new file mode 100644 index 00000000000..d3f4f7b6f55 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/.gitignore @@ -0,0 +1,185 @@ +# Ref: https://gist.github.com/kmorcinek/2710267 +# Download this file using PowerShell v3 under Windows with the following comand +# Invoke-WebRequest https://gist.githubusercontent.com/kmorcinek/2710267/raw/ -OutFile .gitignore + +# User-specific files +*.suo +*.user +*.sln.docstates + +# Build results + +[Dd]ebug/ +[Rr]elease/ +x64/ +build/ +[Bb]in/ +[Oo]bj/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +*_i.c +*_p.c +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.log +*.scc + +# OS generated files # +.DS_Store* +ehthumbs.db +Icon? +Thumbs.db + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf +*.cachefile + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +*.ncrunch* +.*crunch*.local.xml + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.Publish.xml + +# Windows Azure Build Output +csx +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +sql/ +*.Cache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.[Pp]ublish.xml +*.pfx +*.publishsettings +modulesbin/ +tempbin/ + +# EPiServer Site file (VPP) +AppData/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file to a newer +# Visual Studio version. Backup files are not needed, because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# vim +*.txt~ +*.swp +*.swo + +# svn +.svn + +# SQL Server files +**/App_Data/*.mdf +**/App_Data/*.ldf +**/App_Data/*.sdf + + +#LightSwitch generated files +GeneratedArtifacts/ +_Pvt_Extensions/ +ModelManifest.xml + +# ========================= +# Windows detritus +# ========================= + +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Mac desktop service store files +.DS_Store + +# SASS Compiler cache +.sass-cache + +# Visual Studio 2014 CTP +**/*.sln.ide diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/.swagger-codegen-ignore b/samples/client/petstore/csharp/SwaggerClientNet40/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/.swagger-codegen/VERSION b/samples/client/petstore/csharp/SwaggerClientNet40/.swagger-codegen/VERSION new file mode 100644 index 00000000000..f9f7450d135 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/.travis.yml b/samples/client/petstore/csharp/SwaggerClientNet40/.travis.yml new file mode 100644 index 00000000000..805caf43c2c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/.travis.yml @@ -0,0 +1,9 @@ +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +language: csharp +mono: + - latest +solution: IO.Swagger.sln +script: + - /bin/sh ./mono_nunit_test.sh diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClientNet40/IO.Swagger.sln new file mode 100644 index 00000000000..05f9d7c8586 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/IO.Swagger.sln @@ -0,0 +1,27 @@ +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", "{321C8C3F-0156-40C1-AE42-D59761FB9B6C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.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 + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/README.md b/samples/client/petstore/csharp/SwaggerClientNet40/README.md new file mode 100644 index 00000000000..8257b6b39dc --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/README.md @@ -0,0 +1,202 @@ +# 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. 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 package: io.swagger.codegen.languages.CSharpClientCodegen + + +## Frameworks supported +- .NET 4.0 or later +- Windows Phone 7.1 (Mango) + + +## Dependencies +- [RestSharp](https://www.nuget.org/packages/RestSharp) - 105.1.0 or later +- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 7.0.0 or later + +The DLLs included in the package may not be the latest version. We recommend using [NuGet] (https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: +``` +Install-Package RestSharp +Install-Package Newtonsoft.Json +``` + +NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploads to fail. See [RestSharp#742](https://github.com/restsharp/RestSharp/issues/742) + + +## Installation +Run the following command to generate the DLL +- [Mac/Linux] `/bin/sh build.sh` +- [Windows] `build.bat` + +Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces: +```csharp +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; +``` + +## Packaging + +A `.nuspec` is included with the project. You can follow the Nuget quickstart to [create](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#create-the-package) and [publish](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#publish-the-package) packages. + +This `.nuspec` uses placeholders from the `.csproj`, so build the `.csproj` directly: + +``` +nuget pack -Build -OutputDirectory out IO.Swagger.csproj +``` + +Then, publish to a [local feed](https://docs.microsoft.com/en-us/nuget/hosting-packages/local-feeds) or [other host](https://docs.microsoft.com/en-us/nuget/hosting-packages/overview) and consume the new package via Nuget as usual. + + +## Getting Started + +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class Example + { + public void main() + { + + var apiInstance = new AnotherFakeApi(); + var body = new ModelClient(); // ModelClient | client model + + try + { + // To test special tags + ModelClient result = apiInstance.TestSpecialTags(body); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling AnotherFakeApi.TestSpecialTags: " + e.Message ); + } + + } + } +} +``` + + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AnotherFakeApi* | [**TestSpecialTags**](docs/AnotherFakeApi.md#testspecialtags) | **PATCH** /another-fake/dummy | To test special tags +*FakeApi* | [**FakeOuterBooleanSerialize**](docs/FakeApi.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +*FakeApi* | [**FakeOuterCompositeSerialize**](docs/FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +*FakeApi* | [**FakeOuterNumberSerialize**](docs/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | +*FakeApi* | [**FakeOuterStringSerialize**](docs/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | +*FakeApi* | [**TestClientModel**](docs/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +*FakeApi* | [**TestEndpointParameters**](docs/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**TestEnumParameters**](docs/FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**TestInlineAdditionalProperties**](docs/FakeApi.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeApi* | [**TestJsonFormData**](docs/FakeApi.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeClassnameTags123Api* | [**TestClassname**](docs/FakeClassnameTags123Api.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case +*PetApi* | [**AddPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**DeletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**FindPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*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/{order_id} | 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/{order_id} | 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 + + - [Model.AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [Model.Animal](docs/Animal.md) + - [Model.AnimalFarm](docs/AnimalFarm.md) + - [Model.ApiResponse](docs/ApiResponse.md) + - [Model.ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [Model.ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [Model.ArrayTest](docs/ArrayTest.md) + - [Model.Capitalization](docs/Capitalization.md) + - [Model.Category](docs/Category.md) + - [Model.ClassModel](docs/ClassModel.md) + - [Model.EnumArrays](docs/EnumArrays.md) + - [Model.EnumClass](docs/EnumClass.md) + - [Model.EnumTest](docs/EnumTest.md) + - [Model.FormatTest](docs/FormatTest.md) + - [Model.HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [Model.List](docs/List.md) + - [Model.MapTest](docs/MapTest.md) + - [Model.MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model.Model200Response](docs/Model200Response.md) + - [Model.ModelClient](docs/ModelClient.md) + - [Model.ModelReturn](docs/ModelReturn.md) + - [Model.Name](docs/Name.md) + - [Model.NumberOnly](docs/NumberOnly.md) + - [Model.Order](docs/Order.md) + - [Model.OuterBoolean](docs/OuterBoolean.md) + - [Model.OuterComposite](docs/OuterComposite.md) + - [Model.OuterEnum](docs/OuterEnum.md) + - [Model.OuterNumber](docs/OuterNumber.md) + - [Model.OuterString](docs/OuterString.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) + - [Model.Cat](docs/Cat.md) + - [Model.Dog](docs/Dog.md) + + + +## Documentation for Authorization + + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +### api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + + +### http_basic_test + +- **Type**: HTTP basic authentication + + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/build.bat b/samples/client/petstore/csharp/SwaggerClientNet40/build.bat new file mode 100644 index 00000000000..3944ce79ec2 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/build.bat @@ -0,0 +1,16 @@ +:: Generated by: https://github.com/swagger-api/swagger-codegen.git +:: + +@echo off + +SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v3.5 + +if not exist ".\nuget.exe" powershell -Command "(new-object System.Net.WebClient).DownloadFile('https://dist.nuget.org/win-x86-commandline/latest/nuget.exe', '.\nuget.exe')" +.\nuget.exe install src\IO.Swagger\packages.config -o packages + +if not exist ".\bin" mkdir bin + +copy packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll +copy packages\RestSharp.105.1.0\lib\net4\RestSharp.dll bin\RestSharp.dll +%CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll;System.ComponentModel.DataAnnotations.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/SwaggerClientNet40/build.sh b/samples/client/petstore/csharp/SwaggerClientNet40/build.sh new file mode 100644 index 00000000000..838fd258d52 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/build.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# + +frameworkVersion=net40 +netfx=${frameworkVersion#net} + +echo "[INFO] Target framework: ${frameworkVersion}" + +echo "[INFO] Download nuget and packages" +wget -nc https://dist.nuget.org/win-x86-commandline/latest/nuget.exe; +mozroots --import --sync +mono nuget.exe install src/IO.Swagger/packages.config -o packages; + +echo "[INFO] Copy DLLs to the 'bin' folder" +mkdir -p bin; +cp packages/Newtonsoft.Json.4.5.11/lib/net40/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; +cp packages/RestSharp.105.1.0/lib/net4/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.ComponentModel.DataAnnotations.dll,\ +System.Runtime.Serialization.dll \ +-target:library \ +-out:bin/IO.Swagger.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/SwaggerClientNet40/docs/AdditionalPropertiesClass.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..ac4f9d10798 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/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/SwaggerClientNet40/docs/Animal.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Animal.md new file mode 100644 index 00000000000..f461176159c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Animal.md @@ -0,0 +1,10 @@ +# IO.Swagger.Model.Animal +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **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/csharp/SwaggerClientNet40/docs/AnimalFarm.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/AnimalFarm.md new file mode 100644 index 00000000000..4d1cccb0cef --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/AnimalFarm.md @@ -0,0 +1,8 @@ +# IO.Swagger.Model.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/csharp/SwaggerClientNet40/docs/AnotherFakeApi.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/AnotherFakeApi.md new file mode 100644 index 00000000000..89bc406754a --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/AnotherFakeApi.md @@ -0,0 +1,70 @@ +# IO.Swagger.Api.AnotherFakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**TestSpecialTags**](AnotherFakeApi.md#testspecialtags) | **PATCH** /another-fake/dummy | To test special tags + + + +# **TestSpecialTags** +> ModelClient TestSpecialTags (ModelClient body) + +To test special tags + +To test special tags + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class TestSpecialTagsExample + { + public void main() + { + var apiInstance = new AnotherFakeApi(); + var body = new ModelClient(); // ModelClient | client model + + try + { + // To test special tags + ModelClient result = apiInstance.TestSpecialTags(body); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling AnotherFakeApi.TestSpecialTags: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**ModelClient**](ModelClient.md)| client model | + +### Return type + +[**ModelClient**](ModelClient.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **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/csharp/SwaggerClientNet40/docs/ApiResponse.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/ApiResponse.md new file mode 100644 index 00000000000..3e4b4c5e9cb --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/ApiResponse.md @@ -0,0 +1,11 @@ +# IO.Swagger.Model.ApiResponse +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Code** | **int?** | | [optional] +**Type** | **string** | | [optional] +**Message** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..3431d89edd0 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,9 @@ +# IO.Swagger.Model.ArrayOfArrayOfNumberOnly +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayArrayNumber** | **List<List<decimal?>>** | | [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/SwaggerClientNet40/docs/ArrayOfNumberOnly.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..9dc573663d6 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/ArrayOfNumberOnly.md @@ -0,0 +1,9 @@ +# IO.Swagger.Model.ArrayOfNumberOnly +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayNumber** | **List<decimal?>** | | [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/SwaggerClientNet40/docs/ArrayTest.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/ArrayTest.md new file mode 100644 index 00000000000..37fb2788b77 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/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/SwaggerClientNet40/docs/Capitalization.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Capitalization.md new file mode 100644 index 00000000000..87d14f03e0d --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Capitalization.md @@ -0,0 +1,14 @@ +# IO.Swagger.Model.Capitalization +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**SmallCamel** | **string** | | [optional] +**CapitalCamel** | **string** | | [optional] +**SmallSnake** | **string** | | [optional] +**CapitalSnake** | **string** | | [optional] +**SCAETHFlowPoints** | **string** | | [optional] +**ATT_NAME** | **string** | Name of the pet | [optional] + +[[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/SwaggerClientNet40/docs/Cat.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Cat.md new file mode 100644 index 00000000000..a88425f4307 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Cat.md @@ -0,0 +1,11 @@ +# IO.Swagger.Model.Cat +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | +**Color** | **string** | | [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/csharp/SwaggerClientNet40/docs/Category.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Category.md new file mode 100644 index 00000000000..20b56b1728c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Category.md @@ -0,0 +1,10 @@ +# IO.Swagger.Model.Category +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long?** | | [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/csharp/SwaggerClientNet40/docs/ClassModel.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/ClassModel.md new file mode 100644 index 00000000000..760130f053c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/ClassModel.md @@ -0,0 +1,9 @@ +# IO.Swagger.Model.ClassModel +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_Class** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/docs/Dog.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Dog.md new file mode 100644 index 00000000000..c3ee6d927b4 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Dog.md @@ -0,0 +1,11 @@ +# IO.Swagger.Model.Dog +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **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/csharp/SwaggerClientNet40/docs/EnumArrays.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/EnumArrays.md new file mode 100644 index 00000000000..86fd208f8f8 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/EnumArrays.md @@ -0,0 +1,10 @@ +# IO.Swagger.Model.EnumArrays +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**JustSymbol** | **string** | | [optional] +**ArrayEnum** | **List<string>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/docs/EnumClass.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/EnumClass.md new file mode 100644 index 00000000000..d936aad6f0b --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/EnumClass.md @@ -0,0 +1,8 @@ +# IO.Swagger.Model.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/csharp/SwaggerClientNet40/docs/EnumTest.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/EnumTest.md new file mode 100644 index 00000000000..a4371a96695 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/EnumTest.md @@ -0,0 +1,12 @@ +# IO.Swagger.Model.EnumTest +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**EnumString** | **string** | | [optional] +**EnumInteger** | **int?** | | [optional] +**EnumNumber** | **double?** | | [optional] +**OuterEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/docs/FakeApi.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/FakeApi.md new file mode 100644 index 00000000000..166fc077b26 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/FakeApi.md @@ -0,0 +1,604 @@ +# IO.Swagger.Api.FakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**FakeOuterBooleanSerialize**](FakeApi.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +[**FakeOuterCompositeSerialize**](FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +[**FakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | +[**FakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | +[**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +[**TestEndpointParameters**](FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**TestEnumParameters**](FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters +[**TestInlineAdditionalProperties**](FakeApi.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**TestJsonFormData**](FakeApi.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data + + + +# **FakeOuterBooleanSerialize** +> OuterBoolean FakeOuterBooleanSerialize (OuterBoolean body = null) + + + +Test serialization of outer boolean types + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class FakeOuterBooleanSerializeExample + { + public void main() + { + var apiInstance = new FakeApi(); + var body = new OuterBoolean(); // OuterBoolean | Input boolean as post body (optional) + + try + { + OuterBoolean result = apiInstance.FakeOuterBooleanSerialize(body); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling FakeApi.FakeOuterBooleanSerialize: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**OuterBoolean**](OuterBoolean.md)| Input boolean as post body | [optional] + +### Return type + +[**OuterBoolean**](OuterBoolean.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **FakeOuterCompositeSerialize** +> OuterComposite FakeOuterCompositeSerialize (OuterComposite body = null) + + + +Test serialization of object with outer number type + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class FakeOuterCompositeSerializeExample + { + public void main() + { + var apiInstance = new FakeApi(); + var body = new OuterComposite(); // OuterComposite | Input composite as post body (optional) + + try + { + OuterComposite result = apiInstance.FakeOuterCompositeSerialize(body); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling FakeApi.FakeOuterCompositeSerialize: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] + +### Return type + +[**OuterComposite**](OuterComposite.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **FakeOuterNumberSerialize** +> OuterNumber FakeOuterNumberSerialize (OuterNumber body = null) + + + +Test serialization of outer number types + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class FakeOuterNumberSerializeExample + { + public void main() + { + var apiInstance = new FakeApi(); + var body = new OuterNumber(); // OuterNumber | Input number as post body (optional) + + try + { + OuterNumber result = apiInstance.FakeOuterNumberSerialize(body); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling FakeApi.FakeOuterNumberSerialize: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**OuterNumber**](OuterNumber.md)| Input number as post body | [optional] + +### Return type + +[**OuterNumber**](OuterNumber.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **FakeOuterStringSerialize** +> OuterString FakeOuterStringSerialize (OuterString body = null) + + + +Test serialization of outer string types + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class FakeOuterStringSerializeExample + { + public void main() + { + var apiInstance = new FakeApi(); + var body = new OuterString(); // OuterString | Input string as post body (optional) + + try + { + OuterString result = apiInstance.FakeOuterStringSerialize(body); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling FakeApi.FakeOuterStringSerialize: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**OuterString**](OuterString.md)| Input string as post body | [optional] + +### Return type + +[**OuterString**](OuterString.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **TestClientModel** +> ModelClient TestClientModel (ModelClient body) + +To test \"client\" model + +To test \"client\" model + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class TestClientModelExample + { + public void main() + { + var apiInstance = new FakeApi(); + var body = new ModelClient(); // ModelClient | client model + + try + { + // To test \"client\" model + ModelClient result = apiInstance.TestClientModel(body); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling FakeApi.TestClientModel: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**ModelClient**](ModelClient.md)| client model | + +### Return type + +[**ModelClient**](ModelClient.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **TestEndpointParameters** +> void TestEndpointParameters (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = 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() + { + // Configure HTTP basic authorization: http_basic_test + Configuration.Default.Username = "YOUR_USERNAME"; + Configuration.Default.Password = "YOUR_PASSWORD"; + + var apiInstance = new FakeApi(); + var number = 3.4; // decimal? | None + var _double = 1.2; // double? | None + var patternWithoutDelimiter = patternWithoutDelimiter_example; // string | None + var _byte = _byte_example; // 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 _string = _string_example; // string | 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) + var callback = callback_example; // string | None (optional) + + try + { + // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + apiInstance.TestEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback); + } + catch (Exception e) + { + Debug.Print("Exception when calling FakeApi.TestEndpointParameters: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **decimal?**| None | + **_double** | **double?**| None | + **patternWithoutDelimiter** | **string**| None | + **_byte** | **byte[]**| None | + **integer** | **int?**| None | [optional] + **int32** | **int?**| None | [optional] + **int64** | **long?**| None | [optional] + **_float** | **float?**| None | [optional] + **_string** | **string**| None | [optional] + **binary** | **byte[]**| None | [optional] + **date** | **DateTime?**| None | [optional] + **dateTime** | **DateTime?**| None | [optional] + **password** | **string**| None | [optional] + **callback** | **string**| None | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/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) + + +# **TestEnumParameters** +> void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null) + +To test enum parameters + +To test enum parameters + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class TestEnumParametersExample + { + public void main() + { + var apiInstance = new FakeApi(); + var enumFormStringArray = new List(); // List | Form parameter enum test (string array) (optional) + var enumFormString = enumFormString_example; // string | Form parameter enum test (string) (optional) (default to -efg) + var enumHeaderStringArray = new List(); // List | Header parameter enum test (string array) (optional) + var enumHeaderString = enumHeaderString_example; // string | Header parameter enum test (string) (optional) (default to -efg) + var enumQueryStringArray = new List(); // List | Query parameter enum test (string array) (optional) + var enumQueryString = enumQueryString_example; // string | Query parameter enum test (string) (optional) (default to -efg) + var enumQueryInteger = 56; // int? | Query parameter enum test (double) (optional) + var enumQueryDouble = 1.2; // double? | Query parameter enum test (double) (optional) + + try + { + // To test enum parameters + apiInstance.TestEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + } + catch (Exception e) + { + Debug.Print("Exception when calling FakeApi.TestEnumParameters: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumFormStringArray** | [**List<string>**](string.md)| Form parameter enum test (string array) | [optional] + **enumFormString** | **string**| Form parameter enum test (string) | [optional] [default to -efg] + **enumHeaderStringArray** | [**List<string>**](string.md)| Header parameter enum test (string array) | [optional] + **enumHeaderString** | **string**| Header parameter enum test (string) | [optional] [default to -efg] + **enumQueryStringArray** | [**List<string>**](string.md)| Query parameter enum test (string array) | [optional] + **enumQueryString** | **string**| Query parameter enum test (string) | [optional] [default to -efg] + **enumQueryInteger** | **int?**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **double?**| Query parameter enum test (double) | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: */* + - **Accept**: */* + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **TestInlineAdditionalProperties** +> void TestInlineAdditionalProperties (Object param) + +test inline additionalProperties + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class TestInlineAdditionalPropertiesExample + { + public void main() + { + var apiInstance = new FakeApi(); + var param = ; // Object | request body + + try + { + // test inline additionalProperties + apiInstance.TestInlineAdditionalProperties(param); + } + catch (Exception e) + { + Debug.Print("Exception when calling FakeApi.TestInlineAdditionalProperties: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **TestJsonFormData** +> void TestJsonFormData (string param, string param2) + +test json serialization of form data + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class TestJsonFormDataExample + { + public void main() + { + var apiInstance = new FakeApi(); + var param = param_example; // string | field1 + var param2 = param2_example; // string | field2 + + try + { + // test json serialization of form data + apiInstance.TestJsonFormData(param, param2); + } + catch (Exception e) + { + Debug.Print("Exception when calling FakeApi.TestJsonFormData: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **string**| field1 | + **param2** | **string**| field2 | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/docs/FakeClassnameTags123Api.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/FakeClassnameTags123Api.md new file mode 100644 index 00000000000..5f1d0ca776b --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/FakeClassnameTags123Api.md @@ -0,0 +1,73 @@ +# IO.Swagger.Api.FakeClassnameTags123Api + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**TestClassname**](FakeClassnameTags123Api.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case + + + +# **TestClassname** +> ModelClient TestClassname (ModelClient body) + +To test class name in snake case + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class TestClassnameExample + { + public void main() + { + // Configure API key authorization: api_key_query + Configuration.Default.AddApiKey("api_key_query", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.AddApiKeyPrefix("api_key_query", "Bearer"); + + var apiInstance = new FakeClassnameTags123Api(); + var body = new ModelClient(); // ModelClient | client model + + try + { + // To test class name in snake case + ModelClient result = apiInstance.TestClassname(body); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling FakeClassnameTags123Api.TestClassname: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**ModelClient**](ModelClient.md)| client model | + +### Return type + +[**ModelClient**](ModelClient.md) + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + + - **Content-Type**: application/json + - **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/csharp/SwaggerClientNet40/docs/FormatTest.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/FormatTest.md new file mode 100644 index 00000000000..1d366bd7cab --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/FormatTest.md @@ -0,0 +1,21 @@ +# IO.Swagger.Model.FormatTest +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Integer** | **int?** | | [optional] +**Int32** | **int?** | | [optional] +**Int64** | **long?** | | [optional] +**Number** | **decimal?** | | +**_Float** | **float?** | | [optional] +**_Double** | **double?** | | [optional] +**_String** | **string** | | [optional] +**_Byte** | **byte[]** | | +**Binary** | **byte[]** | | [optional] +**Date** | **DateTime?** | | +**DateTime** | **DateTime?** | | [optional] +**Uuid** | **Guid?** | | [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/csharp/SwaggerClientNet40/docs/HasOnlyReadOnly.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..cf0190498b9 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/HasOnlyReadOnly.md @@ -0,0 +1,10 @@ +# IO.Swagger.Model.HasOnlyReadOnly +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Bar** | **string** | | [optional] +**Foo** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/docs/List.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/List.md new file mode 100644 index 00000000000..d7555b7e7ac --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/List.md @@ -0,0 +1,9 @@ +# IO.Swagger.Model.List +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123List** | **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/SwaggerClientNet40/docs/MapTest.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/MapTest.md new file mode 100644 index 00000000000..5c202aa336a --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/MapTest.md @@ -0,0 +1,10 @@ +# IO.Swagger.Model.MapTest +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] +**MapOfEnumString** | **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/SwaggerClientNet40/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..e2c978f9ab1 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/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/SwaggerClientNet40/docs/Model200Response.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Model200Response.md new file mode 100644 index 00000000000..cfaddb67027 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Model200Response.md @@ -0,0 +1,10 @@ +# IO.Swagger.Model.Model200Response +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **int?** | | [optional] +**_Class** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/docs/ModelClient.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/ModelClient.md new file mode 100644 index 00000000000..9ecdc0e1141 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/ModelClient.md @@ -0,0 +1,9 @@ +# IO.Swagger.Model.ModelClient +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_Client** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/docs/ModelReturn.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/ModelReturn.md new file mode 100644 index 00000000000..9895ccde2b0 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/ModelReturn.md @@ -0,0 +1,9 @@ +# IO.Swagger.Model.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/csharp/SwaggerClientNet40/docs/Name.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Name.md new file mode 100644 index 00000000000..678132c8e4e --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Name.md @@ -0,0 +1,12 @@ +# IO.Swagger.Model.Name +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_Name** | **int?** | | +**SnakeCase** | **int?** | | [optional] +**Property** | **string** | | [optional] +**_123Number** | **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/csharp/SwaggerClientNet40/docs/NumberOnly.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/NumberOnly.md new file mode 100644 index 00000000000..a156dc4e2fc --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/NumberOnly.md @@ -0,0 +1,9 @@ +# IO.Swagger.Model.NumberOnly +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**JustNumber** | **decimal?** | | [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/SwaggerClientNet40/docs/Order.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Order.md new file mode 100644 index 00000000000..32aeab388e5 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Order.md @@ -0,0 +1,14 @@ +# IO.Swagger.Model.Order +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long?** | | [optional] +**PetId** | **long?** | | [optional] +**Quantity** | **int?** | | [optional] +**ShipDate** | **DateTime?** | | [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/csharp/SwaggerClientNet40/docs/OuterBoolean.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/OuterBoolean.md new file mode 100644 index 00000000000..84845b35e54 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/OuterBoolean.md @@ -0,0 +1,8 @@ +# IO.Swagger.Model.OuterBoolean +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/docs/OuterComposite.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/OuterComposite.md new file mode 100644 index 00000000000..41fae66f136 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/OuterComposite.md @@ -0,0 +1,11 @@ +# IO.Swagger.Model.OuterComposite +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MyNumber** | [**OuterNumber**](OuterNumber.md) | | [optional] +**MyString** | [**OuterString**](OuterString.md) | | [optional] +**MyBoolean** | [**OuterBoolean**](OuterBoolean.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/docs/OuterEnum.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/OuterEnum.md new file mode 100644 index 00000000000..55eb118a349 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/OuterEnum.md @@ -0,0 +1,8 @@ +# IO.Swagger.Model.OuterEnum +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/docs/OuterNumber.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/OuterNumber.md new file mode 100644 index 00000000000..7c88274d6ee --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/OuterNumber.md @@ -0,0 +1,8 @@ +# IO.Swagger.Model.OuterNumber +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/docs/OuterString.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/OuterString.md new file mode 100644 index 00000000000..524423a5dab --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/OuterString.md @@ -0,0 +1,8 @@ +# IO.Swagger.Model.OuterString +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/docs/Pet.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Pet.md new file mode 100644 index 00000000000..e83933d1c60 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Pet.md @@ -0,0 +1,14 @@ +# IO.Swagger.Model.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** | **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/csharp/SwaggerClientNet40/docs/PetApi.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/PetApi.md new file mode 100644 index 00000000000..6b6450a12ab --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/PetApi.md @@ -0,0 +1,536 @@ +# IO.Swagger.Api.PetApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**AddPet**](PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +[**DeletePet**](PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +[**FindPetsByStatus**](PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +[**FindPetsByTags**](PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +[**GetPetById**](PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +[**UpdatePet**](PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +[**UpdatePetWithForm**](PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**UploadFile**](PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **AddPet** +> void AddPet (Pet body) + +Add a new pet to the store + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class AddPetExample + { + public void main() + { + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var body = new Pet(); // Pet | Pet object that needs to be added to the store + + try + { + // Add a new pet to the store + apiInstance.AddPet(body); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.AddPet: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: 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) + + +# **DeletePet** +> void DeletePet (long? petId, string apiKey = null) + +Deletes a pet + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class DeletePetExample + { + public void main() + { + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var petId = 789; // long? | Pet id to delete + var apiKey = apiKey_example; // string | (optional) + + try + { + // Deletes a pet + apiInstance.DeletePet(petId, apiKey); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.DeletePet: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **long?**| Pet id to delete | + **apiKey** | **string**| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **FindPetsByStatus** +> List FindPetsByStatus (List status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class FindPetsByStatusExample + { + public void main() + { + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var status = new List(); // List | Status values that need to be considered for filter + + try + { + // Finds Pets by status + List<Pet> result = apiInstance.FindPetsByStatus(status); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.FindPetsByStatus: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<string>**](string.md)| Status values that need to be considered for filter | + +### Return type + +[**List**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **FindPetsByTags** +> List FindPetsByTags (List tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class FindPetsByTagsExample + { + public void main() + { + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var tags = new List(); // List | Tags to filter by + + try + { + // Finds Pets by tags + List<Pet> result = apiInstance.FindPetsByTags(tags); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.FindPetsByTags: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<string>**](string.md)| Tags to filter by | + +### Return type + +[**List**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **GetPetById** +> Pet GetPetById (long? petId) + +Find pet by ID + +Returns a single pet + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class GetPetByIdExample + { + public void main() + { + // Configure API key authorization: api_key + Configuration.Default.AddApiKey("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.AddApiKeyPrefix("api_key", "Bearer"); + + var apiInstance = new PetApi(); + var petId = 789; // long? | ID of pet to return + + try + { + // Find pet by ID + Pet result = apiInstance.GetPetById(petId); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.GetPetById: " + e.Message ); + } + } + } +} +``` + +### 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 + +[[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** +> void UpdatePet (Pet body) + +Update an existing pet + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class UpdatePetExample + { + public void main() + { + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var body = new Pet(); // Pet | Pet object that needs to be added to the store + + try + { + // Update an existing pet + apiInstance.UpdatePet(body); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.UpdatePet: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: 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) + + +# **UpdatePetWithForm** +> void UpdatePetWithForm (long? petId, string name = null, string status = null) + +Updates a pet in the store with form data + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class UpdatePetWithFormExample + { + public void main() + { + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var petId = 789; // long? | ID of pet that needs to be updated + var name = name_example; // string | Updated name of the pet (optional) + var status = status_example; // string | Updated status of the pet (optional) + + try + { + // Updates a pet in the store with form data + apiInstance.UpdatePetWithForm(petId, name, status); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.UpdatePetWithForm: " + e.Message ); + } + } + } +} +``` + +### 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 (empty response body) + +### Authorization + +[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) + + +# **UploadFile** +> ApiResponse UploadFile (long? petId, string additionalMetadata = null, System.IO.Stream file = null) + +uploads an image + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class UploadFileExample + { + public void main() + { + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var petId = 789; // long? | ID of pet to update + var additionalMetadata = additionalMetadata_example; // string | Additional data to pass to server (optional) + var file = new System.IO.Stream(); // System.IO.Stream | file to upload (optional) + + try + { + // uploads an image + ApiResponse result = apiInstance.UploadFile(petId, additionalMetadata, file); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.UploadFile: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **long?**| ID of pet to update | + **additionalMetadata** | **string**| Additional data to pass to server | [optional] + **file** | **System.IO.Stream**| file to upload | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/docs/ReadOnlyFirst.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..b5f8d484869 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/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/SwaggerClientNet40/docs/SpecialModelName.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/SpecialModelName.md new file mode 100644 index 00000000000..ee1bc316835 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/SpecialModelName.md @@ -0,0 +1,9 @@ +# IO.Swagger.Model.SpecialModelName +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**SpecialPropertyName** | **long?** | | [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/SwaggerClientNet40/docs/StoreApi.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/StoreApi.md new file mode 100644 index 00000000000..113032c257b --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/StoreApi.md @@ -0,0 +1,256 @@ +# IO.Swagger.Api.StoreApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**DeleteOrder**](StoreApi.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +[**GetInventory**](StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[**GetOrderById**](StoreApi.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +[**PlaceOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet + + + +# **DeleteOrder** +> void DeleteOrder (string 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 +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class DeleteOrderExample + { + public void main() + { + var apiInstance = new StoreApi(); + var orderId = orderId_example; // string | ID of the order that needs to be deleted + + try + { + // Delete purchase order by ID + apiInstance.DeleteOrder(orderId); + } + catch (Exception e) + { + Debug.Print("Exception when calling StoreApi.DeleteOrder: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **string**| ID of the order that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: 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) + + +# **GetInventory** +> Dictionary GetInventory () + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class GetInventoryExample + { + public void main() + { + // Configure API key authorization: api_key + Configuration.Default.AddApiKey("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.AddApiKeyPrefix("api_key", "Bearer"); + + var apiInstance = new StoreApi(); + + try + { + // Returns pet inventories by status + Dictionary<string, int?> result = apiInstance.GetInventory(); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling StoreApi.GetInventory: " + e.Message ); + } + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**Dictionary** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **GetOrderById** +> Order GetOrderById (long? orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class GetOrderByIdExample + { + public void main() + { + var apiInstance = new StoreApi(); + var orderId = 789; // long? | ID of pet that needs to be fetched + + try + { + // Find purchase order by ID + Order result = apiInstance.GetOrderById(orderId); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling StoreApi.GetOrderById: " + e.Message ); + } + } + } +} +``` + +### 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 + +[[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** +> Order PlaceOrder (Order body) + +Place an order for a pet + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class PlaceOrderExample + { + public void main() + { + var apiInstance = new StoreApi(); + var body = new Order(); // Order | order placed for purchasing the pet + + try + { + // Place an order for a pet + Order result = apiInstance.PlaceOrder(body); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling StoreApi.PlaceOrder: " + e.Message ); + } + } + } +} +``` + +### 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 + +[[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/SwaggerClientNet40/docs/Tag.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Tag.md new file mode 100644 index 00000000000..64c5e6bdc72 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/Tag.md @@ -0,0 +1,10 @@ +# IO.Swagger.Model.Tag +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long?** | | [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/csharp/SwaggerClientNet40/docs/User.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/User.md new file mode 100644 index 00000000000..fbea33c48b9 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/User.md @@ -0,0 +1,16 @@ +# IO.Swagger.Model.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** | **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/csharp/SwaggerClientNet40/docs/UserApi.md b/samples/client/petstore/csharp/SwaggerClientNet40/docs/UserApi.md new file mode 100644 index 00000000000..0ddde3f669c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/docs/UserApi.md @@ -0,0 +1,498 @@ +# IO.Swagger.Api.UserApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**CreateUser**](UserApi.md#createuser) | **POST** /user | Create user +[**CreateUsersWithArrayInput**](UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +[**CreateUsersWithListInput**](UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +[**DeleteUser**](UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +[**GetUserByName**](UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +[**LoginUser**](UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +[**LogoutUser**](UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +[**UpdateUser**](UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + + +# **CreateUser** +> void CreateUser (User body) + +Create user + +This can only be done by the logged in user. + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class CreateUserExample + { + public void main() + { + var apiInstance = new UserApi(); + var body = new User(); // User | Created user object + + try + { + // Create user + apiInstance.CreateUser(body); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.CreateUser: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### 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) + + +# **CreateUsersWithArrayInput** +> void CreateUsersWithArrayInput (List body) + +Creates list of users with given input array + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class CreateUsersWithArrayInputExample + { + public void main() + { + var apiInstance = new UserApi(); + var body = new List(); // List | List of user object + + try + { + // Creates list of users with given input array + apiInstance.CreateUsersWithArrayInput(body); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.CreateUsersWithArrayInput: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### 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) + + +# **CreateUsersWithListInput** +> void CreateUsersWithListInput (List body) + +Creates list of users with given input array + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class CreateUsersWithListInputExample + { + public void main() + { + var apiInstance = new UserApi(); + var body = new List(); // List | List of user object + + try + { + // Creates list of users with given input array + apiInstance.CreateUsersWithListInput(body); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.CreateUsersWithListInput: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### 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) + + +# **DeleteUser** +> void DeleteUser (string username) + +Delete user + +This can only be done by the logged in user. + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class DeleteUserExample + { + public void main() + { + var apiInstance = new UserApi(); + var username = username_example; // string | The name that needs to be deleted + + try + { + // Delete user + apiInstance.DeleteUser(username); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.DeleteUser: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The name that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: 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) + + +# **GetUserByName** +> User GetUserByName (string username) + +Get user by user name + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class GetUserByNameExample + { + public void main() + { + var apiInstance = new UserApi(); + var username = username_example; // string | The name that needs to be fetched. Use user1 for testing. + + try + { + // Get user by user name + User result = apiInstance.GetUserByName(username); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.GetUserByName: " + e.Message ); + } + } + } +} +``` + +### 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 + +[[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 (string username, string password) + +Logs user into the system + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class LoginUserExample + { + public void main() + { + var apiInstance = new UserApi(); + var username = username_example; // string | The user name for login + var password = password_example; // string | The password for login in clear text + + try + { + // Logs user into the system + string result = apiInstance.LoginUser(username, password); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.LoginUser: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The user name for login | + **password** | **string**| The password for login in clear text | + +### Return type + +**string** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **LogoutUser** +> void LogoutUser () + +Logs out current logged in user session + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class LogoutUserExample + { + public void main() + { + var apiInstance = new UserApi(); + + try + { + // Logs out current logged in user session + apiInstance.LogoutUser(); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.LogoutUser: " + e.Message ); + } + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: 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) + + +# **UpdateUser** +> void UpdateUser (string username, User body) + +Updated user + +This can only be done by the logged in user. + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class UpdateUserExample + { + public void main() + { + var apiInstance = new UserApi(); + var username = username_example; // string | name that need to be deleted + var body = new User(); // User | Updated user object + + try + { + // Updated user + apiInstance.UpdateUser(username, body); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.UpdateUser: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + +### 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/SwaggerClientNet40/git_push.sh b/samples/client/petstore/csharp/SwaggerClientNet40/git_push.sh new file mode 100644 index 00000000000..792320114fb --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git 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/samples/client/petstore/csharp/SwaggerClientNet40/mono_nunit_test.sh b/samples/client/petstore/csharp/SwaggerClientNet40/mono_nunit_test.sh new file mode 100644 index 00000000000..1276032d81b --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/mono_nunit_test.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# + +wget -nc https://dist.nuget.org/win-x86-commandline/latest/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://dist.nuget.org/win-x86-commandline/latest/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 2.6.4 -OutputDirectory packages + +echo "[INFO] Build the solution and run the unit test" +xbuild IO.Swagger.sln && \ + mono ./packages/NUnit.Runners.2.6.4/tools/nunit-console.exe src/IO.Swagger.Test/bin/Debug/IO.Swagger.Test.dll diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/nuget.exe b/samples/client/petstore/csharp/SwaggerClientNet40/nuget.exe new file mode 100644 index 00000000000..ec1309c7aa6 Binary files /dev/null and b/samples/client/petstore/csharp/SwaggerClientNet40/nuget.exe differ diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/AnotherFakeApiTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/AnotherFakeApiTests.cs new file mode 100644 index 00000000000..070e217a0f5 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/AnotherFakeApiTests.cs @@ -0,0 +1,81 @@ +/* + * 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 + */ + +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using RestSharp; +using NUnit.Framework; + +using IO.Swagger.Client; +using IO.Swagger.Api; +using IO.Swagger.Model; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing AnotherFakeApi + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the API endpoint. + /// + [TestFixture] + public class AnotherFakeApiTests + { + private AnotherFakeApi instance; + + /// + /// Setup before each unit test + /// + [SetUp] + public void Init() + { + instance = new AnotherFakeApi(); + } + + /// + /// Clean up after each unit test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of AnotherFakeApi + /// + [Test] + public void InstanceTest() + { + // TODO uncomment below to test 'IsInstanceOfType' AnotherFakeApi + //Assert.IsInstanceOfType(typeof(AnotherFakeApi), instance, "instance is a AnotherFakeApi"); + } + + + /// + /// Test TestSpecialTags + /// + [Test] + public void TestSpecialTagsTest() + { + // TODO uncomment below to test the method and replace null with proper value + //ModelClient body = null; + //var response = instance.TestSpecialTags(body); + //Assert.IsInstanceOf (response, "response is ModelClient"); + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/FakeApiTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/FakeApiTests.cs new file mode 100644 index 00000000000..fc21272e659 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/FakeApiTests.cs @@ -0,0 +1,198 @@ +/* + * 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 + */ + +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using RestSharp; +using NUnit.Framework; + +using IO.Swagger.Client; +using IO.Swagger.Api; +using IO.Swagger.Model; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing FakeApi + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the API endpoint. + /// + [TestFixture] + public class FakeApiTests + { + private FakeApi instance; + + /// + /// Setup before each unit test + /// + [SetUp] + public void Init() + { + instance = new FakeApi(); + } + + /// + /// Clean up after each unit test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of FakeApi + /// + [Test] + public void InstanceTest() + { + // TODO uncomment below to test 'IsInstanceOfType' FakeApi + //Assert.IsInstanceOfType(typeof(FakeApi), instance, "instance is a FakeApi"); + } + + + /// + /// Test FakeOuterBooleanSerialize + /// + [Test] + public void FakeOuterBooleanSerializeTest() + { + // TODO uncomment below to test the method and replace null with proper value + //OuterBoolean body = null; + //var response = instance.FakeOuterBooleanSerialize(body); + //Assert.IsInstanceOf (response, "response is OuterBoolean"); + } + + /// + /// Test FakeOuterCompositeSerialize + /// + [Test] + public void FakeOuterCompositeSerializeTest() + { + // TODO uncomment below to test the method and replace null with proper value + //OuterComposite body = null; + //var response = instance.FakeOuterCompositeSerialize(body); + //Assert.IsInstanceOf (response, "response is OuterComposite"); + } + + /// + /// Test FakeOuterNumberSerialize + /// + [Test] + public void FakeOuterNumberSerializeTest() + { + // TODO uncomment below to test the method and replace null with proper value + //OuterNumber body = null; + //var response = instance.FakeOuterNumberSerialize(body); + //Assert.IsInstanceOf (response, "response is OuterNumber"); + } + + /// + /// Test FakeOuterStringSerialize + /// + [Test] + public void FakeOuterStringSerializeTest() + { + // TODO uncomment below to test the method and replace null with proper value + //OuterString body = null; + //var response = instance.FakeOuterStringSerialize(body); + //Assert.IsInstanceOf (response, "response is OuterString"); + } + + /// + /// Test TestClientModel + /// + [Test] + public void TestClientModelTest() + { + // TODO uncomment below to test the method and replace null with proper value + //ModelClient body = null; + //var response = instance.TestClientModel(body); + //Assert.IsInstanceOf (response, "response is ModelClient"); + } + + /// + /// Test TestEndpointParameters + /// + [Test] + public void TestEndpointParametersTest() + { + // TODO uncomment below to test the method and replace null with proper value + //decimal? number = null; + //double? _double = null; + //string patternWithoutDelimiter = null; + //byte[] _byte = null; + //int? integer = null; + //int? int32 = null; + //long? int64 = null; + //float? _float = null; + //string _string = null; + //byte[] binary = null; + //DateTime? date = null; + //DateTime? dateTime = null; + //string password = null; + //string callback = null; + //instance.TestEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback); + + } + + /// + /// Test TestEnumParameters + /// + [Test] + public void TestEnumParametersTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List enumFormStringArray = null; + //string enumFormString = null; + //List enumHeaderStringArray = null; + //string enumHeaderString = null; + //List enumQueryStringArray = null; + //string enumQueryString = null; + //int? enumQueryInteger = null; + //double? enumQueryDouble = null; + //instance.TestEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + + } + + /// + /// Test TestInlineAdditionalProperties + /// + [Test] + public void TestInlineAdditionalPropertiesTest() + { + // TODO uncomment below to test the method and replace null with proper value + //Object param = null; + //instance.TestInlineAdditionalProperties(param); + + } + + /// + /// Test TestJsonFormData + /// + [Test] + public void TestJsonFormDataTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string param = null; + //string param2 = null; + //instance.TestJsonFormData(param, param2); + + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/FakeClassnameTags123ApiTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/FakeClassnameTags123ApiTests.cs new file mode 100644 index 00000000000..36a5acb38a9 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/FakeClassnameTags123ApiTests.cs @@ -0,0 +1,81 @@ +/* + * 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 + */ + +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using RestSharp; +using NUnit.Framework; + +using IO.Swagger.Client; +using IO.Swagger.Api; +using IO.Swagger.Model; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing FakeClassnameTags123Api + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the API endpoint. + /// + [TestFixture] + public class FakeClassnameTags123ApiTests + { + private FakeClassnameTags123Api instance; + + /// + /// Setup before each unit test + /// + [SetUp] + public void Init() + { + instance = new FakeClassnameTags123Api(); + } + + /// + /// Clean up after each unit test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of FakeClassnameTags123Api + /// + [Test] + public void InstanceTest() + { + // TODO uncomment below to test 'IsInstanceOfType' FakeClassnameTags123Api + //Assert.IsInstanceOfType(typeof(FakeClassnameTags123Api), instance, "instance is a FakeClassnameTags123Api"); + } + + + /// + /// Test TestClassname + /// + [Test] + public void TestClassnameTest() + { + // TODO uncomment below to test the method and replace null with proper value + //ModelClient body = null; + //var response = instance.TestClassname(body); + //Assert.IsInstanceOf (response, "response is ModelClient"); + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/PetApiTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/PetApiTests.cs new file mode 100644 index 00000000000..34c1fb71f44 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/PetApiTests.cs @@ -0,0 +1,170 @@ +/* + * 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 + */ + +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using RestSharp; +using NUnit.Framework; + +using IO.Swagger.Client; +using IO.Swagger.Api; +using IO.Swagger.Model; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing PetApi + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the API endpoint. + /// + [TestFixture] + public class PetApiTests + { + private PetApi instance; + + /// + /// Setup before each unit test + /// + [SetUp] + public void Init() + { + instance = new PetApi(); + } + + /// + /// Clean up after each unit test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of PetApi + /// + [Test] + public void InstanceTest() + { + // TODO uncomment below to test 'IsInstanceOfType' PetApi + //Assert.IsInstanceOfType(typeof(PetApi), instance, "instance is a PetApi"); + } + + + /// + /// Test AddPet + /// + [Test] + public void AddPetTest() + { + // TODO uncomment below to test the method and replace null with proper value + //Pet body = null; + //instance.AddPet(body); + + } + + /// + /// Test DeletePet + /// + [Test] + public void DeletePetTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long? petId = null; + //string apiKey = null; + //instance.DeletePet(petId, apiKey); + + } + + /// + /// Test FindPetsByStatus + /// + [Test] + public void FindPetsByStatusTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List status = null; + //var response = instance.FindPetsByStatus(status); + //Assert.IsInstanceOf> (response, "response is List"); + } + + /// + /// Test FindPetsByTags + /// + [Test] + public void FindPetsByTagsTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List tags = null; + //var response = instance.FindPetsByTags(tags); + //Assert.IsInstanceOf> (response, "response is List"); + } + + /// + /// Test GetPetById + /// + [Test] + public void GetPetByIdTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long? petId = null; + //var response = instance.GetPetById(petId); + //Assert.IsInstanceOf (response, "response is Pet"); + } + + /// + /// Test UpdatePet + /// + [Test] + public void UpdatePetTest() + { + // TODO uncomment below to test the method and replace null with proper value + //Pet body = null; + //instance.UpdatePet(body); + + } + + /// + /// Test UpdatePetWithForm + /// + [Test] + public void UpdatePetWithFormTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long? petId = null; + //string name = null; + //string status = null; + //instance.UpdatePetWithForm(petId, name, status); + + } + + /// + /// Test UploadFile + /// + [Test] + public void UploadFileTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long? petId = null; + //string additionalMetadata = null; + //System.IO.Stream file = null; + //var response = instance.UploadFile(petId, additionalMetadata, file); + //Assert.IsInstanceOf (response, "response is ApiResponse"); + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/StoreApiTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/StoreApiTests.cs new file mode 100644 index 00000000000..005bf9f0315 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/StoreApiTests.cs @@ -0,0 +1,116 @@ +/* + * 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 + */ + +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using RestSharp; +using NUnit.Framework; + +using IO.Swagger.Client; +using IO.Swagger.Api; +using IO.Swagger.Model; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing StoreApi + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the API endpoint. + /// + [TestFixture] + public class StoreApiTests + { + private StoreApi instance; + + /// + /// Setup before each unit test + /// + [SetUp] + public void Init() + { + instance = new StoreApi(); + } + + /// + /// Clean up after each unit test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of StoreApi + /// + [Test] + public void InstanceTest() + { + // TODO uncomment below to test 'IsInstanceOfType' StoreApi + //Assert.IsInstanceOfType(typeof(StoreApi), instance, "instance is a StoreApi"); + } + + + /// + /// Test DeleteOrder + /// + [Test] + public void DeleteOrderTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string orderId = null; + //instance.DeleteOrder(orderId); + + } + + /// + /// Test GetInventory + /// + [Test] + public void GetInventoryTest() + { + // TODO uncomment below to test the method and replace null with proper value + //var response = instance.GetInventory(); + //Assert.IsInstanceOf> (response, "response is Dictionary"); + } + + /// + /// Test GetOrderById + /// + [Test] + public void GetOrderByIdTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long? orderId = null; + //var response = instance.GetOrderById(orderId); + //Assert.IsInstanceOf (response, "response is Order"); + } + + /// + /// Test PlaceOrder + /// + [Test] + public void PlaceOrderTest() + { + // TODO uncomment below to test the method and replace null with proper value + //Order body = null; + //var response = instance.PlaceOrder(body); + //Assert.IsInstanceOf (response, "response is Order"); + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/UserApiTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/UserApiTests.cs new file mode 100644 index 00000000000..e119bb85c22 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Api/UserApiTests.cs @@ -0,0 +1,166 @@ +/* + * 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 + */ + +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using RestSharp; +using NUnit.Framework; + +using IO.Swagger.Client; +using IO.Swagger.Api; +using IO.Swagger.Model; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing UserApi + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the API endpoint. + /// + [TestFixture] + public class UserApiTests + { + private UserApi instance; + + /// + /// Setup before each unit test + /// + [SetUp] + public void Init() + { + instance = new UserApi(); + } + + /// + /// Clean up after each unit test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of UserApi + /// + [Test] + public void InstanceTest() + { + // TODO uncomment below to test 'IsInstanceOfType' UserApi + //Assert.IsInstanceOfType(typeof(UserApi), instance, "instance is a UserApi"); + } + + + /// + /// Test CreateUser + /// + [Test] + public void CreateUserTest() + { + // TODO uncomment below to test the method and replace null with proper value + //User body = null; + //instance.CreateUser(body); + + } + + /// + /// Test CreateUsersWithArrayInput + /// + [Test] + public void CreateUsersWithArrayInputTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List body = null; + //instance.CreateUsersWithArrayInput(body); + + } + + /// + /// Test CreateUsersWithListInput + /// + [Test] + public void CreateUsersWithListInputTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List body = null; + //instance.CreateUsersWithListInput(body); + + } + + /// + /// Test DeleteUser + /// + [Test] + public void DeleteUserTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string username = null; + //instance.DeleteUser(username); + + } + + /// + /// Test GetUserByName + /// + [Test] + public void GetUserByNameTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string username = null; + //var response = instance.GetUserByName(username); + //Assert.IsInstanceOf (response, "response is User"); + } + + /// + /// Test LoginUser + /// + [Test] + public void LoginUserTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string username = null; + //string password = null; + //var response = instance.LoginUser(username, password); + //Assert.IsInstanceOf (response, "response is string"); + } + + /// + /// Test LogoutUser + /// + [Test] + public void LogoutUserTest() + { + // TODO uncomment below to test the method and replace null with proper value + //instance.LogoutUser(); + + } + + /// + /// Test UpdateUser + /// + [Test] + public void UpdateUserTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string username = null; + //User body = null; + //instance.UpdateUser(username, body); + + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/IO.Swagger.Test.csproj b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/IO.Swagger.Test.csproj new file mode 100644 index 00000000000..b1aded9e1a9 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/IO.Swagger.Test.csproj @@ -0,0 +1,83 @@ + + + + + Debug + AnyCPU + {19F1DEBC-DE5E-4517-8062-F000CD499087} + Library + Properties + IO.Swagger.Test + IO.Swagger.Test + v4.0 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + $(SolutionDir)\packages\Newtonsoft.Json.10.0.3\lib\net40\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.10.0.3\lib\net40\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.10.0.3\lib\net40\Newtonsoft.Json.dll + ..\..\vendor\Newtonsoft.Json.10.0.3\lib\net40\Newtonsoft.Json.dll + + + $(SolutionDir)\packages\RestSharp.105.1.0\lib\net40\RestSharp.dll + ..\packages\RestSharp.105.1.0\lib\net40\RestSharp.dll + ..\..\packages\RestSharp.105.1.0\lib\net40\RestSharp.dll + ..\..\vendor\RestSharp.105.1.0\lib\net40\RestSharp.dll + + + $(SolutionDir)\packages\NUnit.2.6.4\lib\nunit.framework.dll + ..\packages\NUnit.2.6.4\lib\nunit.framework.dll + ..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll + ..\..\vendor\NUnit.2.6.4\lib\nunit.framework.dll + + + + + + + + + + + + {321C8C3F-0156-40C1-AE42-D59761FB9B6C} + IO.Swagger + + + + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/AdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/AdditionalPropertiesClassTests.cs new file mode 100644 index 00000000000..60b6cee9f53 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/AdditionalPropertiesClassTests.cs @@ -0,0 +1,88 @@ +/* + * 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 + */ + + +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 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 + { + // TODO uncomment below to declare an instance variable for AdditionalPropertiesClass + //private AdditionalPropertiesClass instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of AdditionalPropertiesClass + //instance = new AdditionalPropertiesClass(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of AdditionalPropertiesClass + /// + [Test] + public void AdditionalPropertiesClassInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" AdditionalPropertiesClass + //Assert.IsInstanceOfType (instance, "variable 'instance' is a AdditionalPropertiesClass"); + } + + + /// + /// Test the property 'MapProperty' + /// + [Test] + public void MapPropertyTest() + { + // TODO unit test for the property 'MapProperty' + } + /// + /// Test the property 'MapOfMapProperty' + /// + [Test] + public void MapOfMapPropertyTest() + { + // TODO unit test for the property 'MapOfMapProperty' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/AnimalFarmTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/AnimalFarmTests.cs new file mode 100644 index 00000000000..6fa7b87485a --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/AnimalFarmTests.cs @@ -0,0 +1,72 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing AnimalFarm + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class AnimalFarmTests + { + // TODO uncomment below to declare an instance variable for AnimalFarm + //private AnimalFarm instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of AnimalFarm + //instance = new AnimalFarm(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of AnimalFarm + /// + [Test] + public void AnimalFarmInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" AnimalFarm + //Assert.IsInstanceOfType (instance, "variable 'instance' is a AnimalFarm"); + } + + + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/AnimalTests.cs new file mode 100644 index 00000000000..ba3786457af --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/AnimalTests.cs @@ -0,0 +1,106 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing Animal + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class AnimalTests + { + // TODO uncomment below to declare an instance variable for Animal + //private Animal instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of Animal + //instance = new Animal(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of Animal + /// + [Test] + public void AnimalInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" Animal + //Assert.IsInstanceOfType (instance, "variable 'instance' is a Animal"); + } + + /// + /// Test deserialize a Dog from type Animal + /// + [Test] + public void DogDeserializeFromAnimalTest() + { + // TODO uncomment below to test deserialize a Dog from type Animal + //Assert.IsInstanceOf(JsonConvert.DeserializeObject(new Dog().ToJson())); + } + /// + /// Test deserialize a Cat from type Animal + /// + [Test] + public void CatDeserializeFromAnimalTest() + { + // TODO uncomment below to test deserialize a Cat from type Animal + //Assert.IsInstanceOf(JsonConvert.DeserializeObject(new Cat().ToJson())); + } + + /// + /// Test the property 'ClassName' + /// + [Test] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + /// + /// Test the property 'Color' + /// + [Test] + public void ColorTest() + { + // TODO unit test for the property 'Color' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ApiResponseTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ApiResponseTests.cs new file mode 100644 index 00000000000..8a5649b4676 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ApiResponseTests.cs @@ -0,0 +1,96 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing ApiResponse + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ApiResponseTests + { + // TODO uncomment below to declare an instance variable for ApiResponse + //private ApiResponse instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of ApiResponse + //instance = new ApiResponse(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of ApiResponse + /// + [Test] + public void ApiResponseInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" ApiResponse + //Assert.IsInstanceOfType (instance, "variable 'instance' is a ApiResponse"); + } + + + /// + /// Test the property 'Code' + /// + [Test] + public void CodeTest() + { + // TODO unit test for the property 'Code' + } + /// + /// Test the property 'Type' + /// + [Test] + public void TypeTest() + { + // TODO unit test for the property 'Type' + } + /// + /// Test the property 'Message' + /// + [Test] + public void MessageTest() + { + // TODO unit test for the property 'Message' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs new file mode 100644 index 00000000000..3f8f100a7f5 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs @@ -0,0 +1,80 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing ArrayOfArrayOfNumberOnly + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ArrayOfArrayOfNumberOnlyTests + { + // TODO uncomment below to declare an instance variable for ArrayOfArrayOfNumberOnly + //private ArrayOfArrayOfNumberOnly instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of ArrayOfArrayOfNumberOnly + //instance = new ArrayOfArrayOfNumberOnly(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of ArrayOfArrayOfNumberOnly + /// + [Test] + public void ArrayOfArrayOfNumberOnlyInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" ArrayOfArrayOfNumberOnly + //Assert.IsInstanceOfType (instance, "variable 'instance' is a ArrayOfArrayOfNumberOnly"); + } + + + /// + /// Test the property 'ArrayArrayNumber' + /// + [Test] + public void ArrayArrayNumberTest() + { + // TODO unit test for the property 'ArrayArrayNumber' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ArrayOfNumberOnlyTests.cs new file mode 100644 index 00000000000..28a540e676b --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ArrayOfNumberOnlyTests.cs @@ -0,0 +1,80 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing ArrayOfNumberOnly + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ArrayOfNumberOnlyTests + { + // TODO uncomment below to declare an instance variable for ArrayOfNumberOnly + //private ArrayOfNumberOnly instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of ArrayOfNumberOnly + //instance = new ArrayOfNumberOnly(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of ArrayOfNumberOnly + /// + [Test] + public void ArrayOfNumberOnlyInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" ArrayOfNumberOnly + //Assert.IsInstanceOfType (instance, "variable 'instance' is a ArrayOfNumberOnly"); + } + + + /// + /// Test the property 'ArrayNumber' + /// + [Test] + public void ArrayNumberTest() + { + // TODO unit test for the property 'ArrayNumber' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ArrayTestTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ArrayTestTests.cs new file mode 100644 index 00000000000..09864b81ac2 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ArrayTestTests.cs @@ -0,0 +1,96 @@ +/* + * 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 + */ + + +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 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 + { + // TODO uncomment below to declare an instance variable for ArrayTest + //private ArrayTest instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of ArrayTest + //instance = new ArrayTest(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of ArrayTest + /// + [Test] + public void ArrayTestInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" ArrayTest + //Assert.IsInstanceOfType (instance, "variable 'instance' is a ArrayTest"); + } + + + /// + /// Test the property 'ArrayOfString' + /// + [Test] + public void ArrayOfStringTest() + { + // TODO unit test for the property 'ArrayOfString' + } + /// + /// Test the property 'ArrayArrayOfInteger' + /// + [Test] + public void ArrayArrayOfIntegerTest() + { + // TODO unit test for the property 'ArrayArrayOfInteger' + } + /// + /// Test the property 'ArrayArrayOfModel' + /// + [Test] + public void ArrayArrayOfModelTest() + { + // TODO unit test for the property 'ArrayArrayOfModel' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/CapitalizationTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/CapitalizationTests.cs new file mode 100644 index 00000000000..fe7637ded78 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/CapitalizationTests.cs @@ -0,0 +1,120 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing Capitalization + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class CapitalizationTests + { + // TODO uncomment below to declare an instance variable for Capitalization + //private Capitalization instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of Capitalization + //instance = new Capitalization(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of Capitalization + /// + [Test] + public void CapitalizationInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" Capitalization + //Assert.IsInstanceOfType (instance, "variable 'instance' is a Capitalization"); + } + + + /// + /// Test the property 'SmallCamel' + /// + [Test] + public void SmallCamelTest() + { + // TODO unit test for the property 'SmallCamel' + } + /// + /// Test the property 'CapitalCamel' + /// + [Test] + public void CapitalCamelTest() + { + // TODO unit test for the property 'CapitalCamel' + } + /// + /// Test the property 'SmallSnake' + /// + [Test] + public void SmallSnakeTest() + { + // TODO unit test for the property 'SmallSnake' + } + /// + /// Test the property 'CapitalSnake' + /// + [Test] + public void CapitalSnakeTest() + { + // TODO unit test for the property 'CapitalSnake' + } + /// + /// Test the property 'SCAETHFlowPoints' + /// + [Test] + public void SCAETHFlowPointsTest() + { + // TODO unit test for the property 'SCAETHFlowPoints' + } + /// + /// Test the property 'ATT_NAME' + /// + [Test] + public void ATT_NAMETest() + { + // TODO unit test for the property 'ATT_NAME' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/CatTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/CatTests.cs new file mode 100644 index 00000000000..d79719efdbc --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/CatTests.cs @@ -0,0 +1,80 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing Cat + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class CatTests + { + // TODO uncomment below to declare an instance variable for Cat + //private Cat instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of Cat + //instance = new Cat(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of Cat + /// + [Test] + public void CatInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" Cat + //Assert.IsInstanceOfType (instance, "variable 'instance' is a Cat"); + } + + + /// + /// Test the property 'Declawed' + /// + [Test] + public void DeclawedTest() + { + // TODO unit test for the property 'Declawed' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/CategoryTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/CategoryTests.cs new file mode 100644 index 00000000000..13497ed1fd6 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/CategoryTests.cs @@ -0,0 +1,88 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing Category + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class CategoryTests + { + // TODO uncomment below to declare an instance variable for Category + //private Category instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of Category + //instance = new Category(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of Category + /// + [Test] + public void CategoryInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" Category + //Assert.IsInstanceOfType (instance, "variable 'instance' is a Category"); + } + + + /// + /// Test the property 'Id' + /// + [Test] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + /// + /// Test the property 'Name' + /// + [Test] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ClassModelTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ClassModelTests.cs new file mode 100644 index 00000000000..2589ea4ecea --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ClassModelTests.cs @@ -0,0 +1,80 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing ClassModel + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ClassModelTests + { + // TODO uncomment below to declare an instance variable for ClassModel + //private ClassModel instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of ClassModel + //instance = new ClassModel(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of ClassModel + /// + [Test] + public void ClassModelInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" ClassModel + //Assert.IsInstanceOfType (instance, "variable 'instance' is a ClassModel"); + } + + + /// + /// Test the property '_Class' + /// + [Test] + public void _ClassTest() + { + // TODO unit test for the property '_Class' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/DogTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/DogTests.cs new file mode 100644 index 00000000000..3f47e42e8c2 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/DogTests.cs @@ -0,0 +1,80 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing Dog + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class DogTests + { + // TODO uncomment below to declare an instance variable for Dog + //private Dog instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of Dog + //instance = new Dog(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of Dog + /// + [Test] + public void DogInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" Dog + //Assert.IsInstanceOfType (instance, "variable 'instance' is a Dog"); + } + + + /// + /// Test the property 'Breed' + /// + [Test] + public void BreedTest() + { + // TODO unit test for the property 'Breed' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/EnumArraysTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/EnumArraysTests.cs new file mode 100644 index 00000000000..f84821d33eb --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/EnumArraysTests.cs @@ -0,0 +1,88 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing EnumArrays + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class EnumArraysTests + { + // TODO uncomment below to declare an instance variable for EnumArrays + //private EnumArrays instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of EnumArrays + //instance = new EnumArrays(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of EnumArrays + /// + [Test] + public void EnumArraysInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" EnumArrays + //Assert.IsInstanceOfType (instance, "variable 'instance' is a EnumArrays"); + } + + + /// + /// Test the property 'JustSymbol' + /// + [Test] + public void JustSymbolTest() + { + // TODO unit test for the property 'JustSymbol' + } + /// + /// Test the property 'ArrayEnum' + /// + [Test] + public void ArrayEnumTest() + { + // TODO unit test for the property 'ArrayEnum' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/EnumClassTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/EnumClassTests.cs new file mode 100644 index 00000000000..b37648d2200 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/EnumClassTests.cs @@ -0,0 +1,72 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing EnumClass + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class EnumClassTests + { + // TODO uncomment below to declare an instance variable for EnumClass + //private EnumClass instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of EnumClass + //instance = new EnumClass(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of EnumClass + /// + [Test] + public void EnumClassInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" EnumClass + //Assert.IsInstanceOfType (instance, "variable 'instance' is a EnumClass"); + } + + + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/EnumTestTests.cs new file mode 100644 index 00000000000..66664cbd9af --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/EnumTestTests.cs @@ -0,0 +1,104 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing EnumTest + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class EnumTestTests + { + // TODO uncomment below to declare an instance variable for EnumTest + //private EnumTest instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of EnumTest + //instance = new EnumTest(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of EnumTest + /// + [Test] + public void EnumTestInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" EnumTest + //Assert.IsInstanceOfType (instance, "variable 'instance' is a EnumTest"); + } + + + /// + /// Test the property 'EnumString' + /// + [Test] + public void EnumStringTest() + { + // TODO unit test for the property 'EnumString' + } + /// + /// Test the property 'EnumInteger' + /// + [Test] + public void EnumIntegerTest() + { + // TODO unit test for the property 'EnumInteger' + } + /// + /// Test the property 'EnumNumber' + /// + [Test] + public void EnumNumberTest() + { + // TODO unit test for the property 'EnumNumber' + } + /// + /// Test the property 'OuterEnum' + /// + [Test] + public void OuterEnumTest() + { + // TODO unit test for the property 'OuterEnum' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/FormatTestTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/FormatTestTests.cs new file mode 100644 index 00000000000..3ae16b2fc6b --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/FormatTestTests.cs @@ -0,0 +1,176 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing FormatTest + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class FormatTestTests + { + // TODO uncomment below to declare an instance variable for FormatTest + //private FormatTest instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of FormatTest + //instance = new FormatTest(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of FormatTest + /// + [Test] + public void FormatTestInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" FormatTest + //Assert.IsInstanceOfType (instance, "variable 'instance' is a FormatTest"); + } + + + /// + /// Test the property 'Integer' + /// + [Test] + public void IntegerTest() + { + // TODO unit test for the property 'Integer' + } + /// + /// Test the property 'Int32' + /// + [Test] + public void Int32Test() + { + // TODO unit test for the property 'Int32' + } + /// + /// Test the property 'Int64' + /// + [Test] + public void Int64Test() + { + // TODO unit test for the property 'Int64' + } + /// + /// Test the property 'Number' + /// + [Test] + public void NumberTest() + { + // TODO unit test for the property 'Number' + } + /// + /// Test the property '_Float' + /// + [Test] + public void _FloatTest() + { + // TODO unit test for the property '_Float' + } + /// + /// Test the property '_Double' + /// + [Test] + public void _DoubleTest() + { + // TODO unit test for the property '_Double' + } + /// + /// Test the property '_String' + /// + [Test] + public void _StringTest() + { + // TODO unit test for the property '_String' + } + /// + /// Test the property '_Byte' + /// + [Test] + public void _ByteTest() + { + // TODO unit test for the property '_Byte' + } + /// + /// Test the property 'Binary' + /// + [Test] + public void BinaryTest() + { + // TODO unit test for the property 'Binary' + } + /// + /// Test the property 'Date' + /// + [Test] + public void DateTest() + { + // TODO unit test for the property 'Date' + } + /// + /// Test the property 'DateTime' + /// + [Test] + public void DateTimeTest() + { + // TODO unit test for the property 'DateTime' + } + /// + /// Test the property 'Uuid' + /// + [Test] + public void UuidTest() + { + // TODO unit test for the property 'Uuid' + } + /// + /// Test the property 'Password' + /// + [Test] + public void PasswordTest() + { + // TODO unit test for the property 'Password' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/HasOnlyReadOnlyTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/HasOnlyReadOnlyTests.cs new file mode 100644 index 00000000000..cafd23d90b2 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/HasOnlyReadOnlyTests.cs @@ -0,0 +1,88 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing HasOnlyReadOnly + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class HasOnlyReadOnlyTests + { + // TODO uncomment below to declare an instance variable for HasOnlyReadOnly + //private HasOnlyReadOnly instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of HasOnlyReadOnly + //instance = new HasOnlyReadOnly(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of HasOnlyReadOnly + /// + [Test] + public void HasOnlyReadOnlyInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" HasOnlyReadOnly + //Assert.IsInstanceOfType (instance, "variable 'instance' is a HasOnlyReadOnly"); + } + + + /// + /// Test the property 'Bar' + /// + [Test] + public void BarTest() + { + // TODO unit test for the property 'Bar' + } + /// + /// Test the property 'Foo' + /// + [Test] + public void FooTest() + { + // TODO unit test for the property 'Foo' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ListTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ListTests.cs new file mode 100644 index 00000000000..6ca026a83e0 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ListTests.cs @@ -0,0 +1,80 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing List + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ListTests + { + // TODO uncomment below to declare an instance variable for List + //private List instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of List + //instance = new List(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of List + /// + [Test] + public void ListInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" List + //Assert.IsInstanceOfType (instance, "variable 'instance' is a List"); + } + + + /// + /// Test the property '_123List' + /// + [Test] + public void _123ListTest() + { + // TODO unit test for the property '_123List' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/MapTestTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/MapTestTests.cs new file mode 100644 index 00000000000..d61693c3322 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/MapTestTests.cs @@ -0,0 +1,88 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing MapTest + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class MapTestTests + { + // TODO uncomment below to declare an instance variable for MapTest + //private MapTest instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of MapTest + //instance = new MapTest(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of MapTest + /// + [Test] + public void MapTestInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" MapTest + //Assert.IsInstanceOfType (instance, "variable 'instance' is a MapTest"); + } + + + /// + /// Test the property 'MapMapOfString' + /// + [Test] + public void MapMapOfStringTest() + { + // TODO unit test for the property 'MapMapOfString' + } + /// + /// Test the property 'MapOfEnumString' + /// + [Test] + public void MapOfEnumStringTest() + { + // TODO unit test for the property 'MapOfEnumString' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs new file mode 100644 index 00000000000..55302d27c40 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs @@ -0,0 +1,96 @@ +/* + * 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 + */ + + +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 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 + { + // TODO uncomment below to declare an instance variable for MixedPropertiesAndAdditionalPropertiesClass + //private MixedPropertiesAndAdditionalPropertiesClass instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of MixedPropertiesAndAdditionalPropertiesClass + //instance = new MixedPropertiesAndAdditionalPropertiesClass(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of MixedPropertiesAndAdditionalPropertiesClass + /// + [Test] + public void MixedPropertiesAndAdditionalPropertiesClassInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" MixedPropertiesAndAdditionalPropertiesClass + //Assert.IsInstanceOfType (instance, "variable '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' + } + /// + /// Test the property 'Map' + /// + [Test] + public void MapTest() + { + // TODO unit test for the property 'Map' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/Model200ResponseTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/Model200ResponseTests.cs new file mode 100644 index 00000000000..cdb0c1960c2 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/Model200ResponseTests.cs @@ -0,0 +1,88 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing Model200Response + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class Model200ResponseTests + { + // TODO uncomment below to declare an instance variable for Model200Response + //private Model200Response instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of Model200Response + //instance = new Model200Response(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of Model200Response + /// + [Test] + public void Model200ResponseInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" Model200Response + //Assert.IsInstanceOfType (instance, "variable 'instance' is a Model200Response"); + } + + + /// + /// Test the property 'Name' + /// + [Test] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + /// + /// Test the property '_Class' + /// + [Test] + public void _ClassTest() + { + // TODO unit test for the property '_Class' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ModelClientTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ModelClientTests.cs new file mode 100644 index 00000000000..f552ab92959 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ModelClientTests.cs @@ -0,0 +1,80 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing ModelClient + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ModelClientTests + { + // TODO uncomment below to declare an instance variable for ModelClient + //private ModelClient instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of ModelClient + //instance = new ModelClient(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of ModelClient + /// + [Test] + public void ModelClientInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" ModelClient + //Assert.IsInstanceOfType (instance, "variable 'instance' is a ModelClient"); + } + + + /// + /// Test the property '_Client' + /// + [Test] + public void _ClientTest() + { + // TODO unit test for the property '_Client' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ModelReturnTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ModelReturnTests.cs new file mode 100644 index 00000000000..7c9ca513a7d --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ModelReturnTests.cs @@ -0,0 +1,80 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing ModelReturn + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ModelReturnTests + { + // TODO uncomment below to declare an instance variable for ModelReturn + //private ModelReturn instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of ModelReturn + //instance = new ModelReturn(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of ModelReturn + /// + [Test] + public void ModelReturnInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" ModelReturn + //Assert.IsInstanceOfType (instance, "variable 'instance' is a ModelReturn"); + } + + + /// + /// Test the property '_Return' + /// + [Test] + public void _ReturnTest() + { + // TODO unit test for the property '_Return' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/NameTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/NameTests.cs new file mode 100644 index 00000000000..3802292269a --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/NameTests.cs @@ -0,0 +1,104 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing Name + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class NameTests + { + // TODO uncomment below to declare an instance variable for Name + //private Name instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of Name + //instance = new Name(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of Name + /// + [Test] + public void NameInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" Name + //Assert.IsInstanceOfType (instance, "variable 'instance' is a Name"); + } + + + /// + /// Test the property '_Name' + /// + [Test] + public void _NameTest() + { + // TODO unit test for the property '_Name' + } + /// + /// Test the property 'SnakeCase' + /// + [Test] + public void SnakeCaseTest() + { + // TODO unit test for the property 'SnakeCase' + } + /// + /// Test the property 'Property' + /// + [Test] + public void PropertyTest() + { + // TODO unit test for the property 'Property' + } + /// + /// Test the property '_123Number' + /// + [Test] + public void _123NumberTest() + { + // TODO unit test for the property '_123Number' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/NumberOnlyTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/NumberOnlyTests.cs new file mode 100644 index 00000000000..afa72bf45e4 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/NumberOnlyTests.cs @@ -0,0 +1,80 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing NumberOnly + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class NumberOnlyTests + { + // TODO uncomment below to declare an instance variable for NumberOnly + //private NumberOnly instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of NumberOnly + //instance = new NumberOnly(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of NumberOnly + /// + [Test] + public void NumberOnlyInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" NumberOnly + //Assert.IsInstanceOfType (instance, "variable 'instance' is a NumberOnly"); + } + + + /// + /// Test the property 'JustNumber' + /// + [Test] + public void JustNumberTest() + { + // TODO unit test for the property 'JustNumber' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OrderTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OrderTests.cs new file mode 100644 index 00000000000..40757e5c01c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OrderTests.cs @@ -0,0 +1,120 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing Order + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class OrderTests + { + // TODO uncomment below to declare an instance variable for Order + //private Order instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of Order + //instance = new Order(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of Order + /// + [Test] + public void OrderInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" Order + //Assert.IsInstanceOfType (instance, "variable 'instance' is a Order"); + } + + + /// + /// Test the property 'Id' + /// + [Test] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + /// + /// Test the property 'PetId' + /// + [Test] + public void PetIdTest() + { + // TODO unit test for the property 'PetId' + } + /// + /// Test the property 'Quantity' + /// + [Test] + public void QuantityTest() + { + // TODO unit test for the property 'Quantity' + } + /// + /// Test the property 'ShipDate' + /// + [Test] + public void ShipDateTest() + { + // TODO unit test for the property 'ShipDate' + } + /// + /// Test the property 'Status' + /// + [Test] + public void StatusTest() + { + // TODO unit test for the property 'Status' + } + /// + /// Test the property 'Complete' + /// + [Test] + public void CompleteTest() + { + // TODO unit test for the property 'Complete' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OuterBooleanTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OuterBooleanTests.cs new file mode 100644 index 00000000000..81a6cdf5323 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OuterBooleanTests.cs @@ -0,0 +1,72 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing OuterBoolean + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class OuterBooleanTests + { + // TODO uncomment below to declare an instance variable for OuterBoolean + //private OuterBoolean instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of OuterBoolean + //instance = new OuterBoolean(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of OuterBoolean + /// + [Test] + public void OuterBooleanInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" OuterBoolean + //Assert.IsInstanceOfType (instance, "variable 'instance' is a OuterBoolean"); + } + + + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OuterCompositeTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OuterCompositeTests.cs new file mode 100644 index 00000000000..8cae88a554a --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OuterCompositeTests.cs @@ -0,0 +1,96 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing OuterComposite + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class OuterCompositeTests + { + // TODO uncomment below to declare an instance variable for OuterComposite + //private OuterComposite instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of OuterComposite + //instance = new OuterComposite(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of OuterComposite + /// + [Test] + public void OuterCompositeInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" OuterComposite + //Assert.IsInstanceOfType (instance, "variable 'instance' is a OuterComposite"); + } + + + /// + /// Test the property 'MyNumber' + /// + [Test] + public void MyNumberTest() + { + // TODO unit test for the property 'MyNumber' + } + /// + /// Test the property 'MyString' + /// + [Test] + public void MyStringTest() + { + // TODO unit test for the property 'MyString' + } + /// + /// Test the property 'MyBoolean' + /// + [Test] + public void MyBooleanTest() + { + // TODO unit test for the property 'MyBoolean' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OuterEnumTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OuterEnumTests.cs new file mode 100644 index 00000000000..b65bc240b0d --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OuterEnumTests.cs @@ -0,0 +1,72 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing OuterEnum + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class OuterEnumTests + { + // TODO uncomment below to declare an instance variable for OuterEnum + //private OuterEnum instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of OuterEnum + //instance = new OuterEnum(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of OuterEnum + /// + [Test] + public void OuterEnumInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" OuterEnum + //Assert.IsInstanceOfType (instance, "variable 'instance' is a OuterEnum"); + } + + + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OuterNumberTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OuterNumberTests.cs new file mode 100644 index 00000000000..55ebb7da9fd --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OuterNumberTests.cs @@ -0,0 +1,72 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing OuterNumber + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class OuterNumberTests + { + // TODO uncomment below to declare an instance variable for OuterNumber + //private OuterNumber instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of OuterNumber + //instance = new OuterNumber(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of OuterNumber + /// + [Test] + public void OuterNumberInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" OuterNumber + //Assert.IsInstanceOfType (instance, "variable 'instance' is a OuterNumber"); + } + + + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OuterStringTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OuterStringTests.cs new file mode 100644 index 00000000000..76a2c2253dc --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/OuterStringTests.cs @@ -0,0 +1,72 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing OuterString + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class OuterStringTests + { + // TODO uncomment below to declare an instance variable for OuterString + //private OuterString instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of OuterString + //instance = new OuterString(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of OuterString + /// + [Test] + public void OuterStringInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" OuterString + //Assert.IsInstanceOfType (instance, "variable 'instance' is a OuterString"); + } + + + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/PetTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/PetTests.cs new file mode 100644 index 00000000000..89b221bde94 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/PetTests.cs @@ -0,0 +1,120 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing Pet + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class PetTests + { + // TODO uncomment below to declare an instance variable for Pet + //private Pet instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of Pet + //instance = new Pet(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of Pet + /// + [Test] + public void PetInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" Pet + //Assert.IsInstanceOfType (instance, "variable 'instance' is a Pet"); + } + + + /// + /// Test the property 'Id' + /// + [Test] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + /// + /// Test the property 'Category' + /// + [Test] + public void CategoryTest() + { + // TODO unit test for the property 'Category' + } + /// + /// Test the property 'Name' + /// + [Test] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + /// + /// Test the property 'PhotoUrls' + /// + [Test] + public void PhotoUrlsTest() + { + // TODO unit test for the property 'PhotoUrls' + } + /// + /// Test the property 'Tags' + /// + [Test] + public void TagsTest() + { + // TODO unit test for the property 'Tags' + } + /// + /// Test the property 'Status' + /// + [Test] + public void StatusTest() + { + // TODO unit test for the property 'Status' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ReadOnlyFirstTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ReadOnlyFirstTests.cs new file mode 100644 index 00000000000..f3836f4cabd --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/ReadOnlyFirstTests.cs @@ -0,0 +1,88 @@ +/* + * 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 + */ + + +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 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 + { + // TODO uncomment below to declare an instance variable for ReadOnlyFirst + //private ReadOnlyFirst instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of ReadOnlyFirst + //instance = new ReadOnlyFirst(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of ReadOnlyFirst + /// + [Test] + public void ReadOnlyFirstInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" ReadOnlyFirst + //Assert.IsInstanceOfType (instance, "variable '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/SwaggerClientNet40/src/IO.Swagger.Test/Model/SpecialModelNameTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/SpecialModelNameTests.cs new file mode 100644 index 00000000000..547c62fd482 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/SpecialModelNameTests.cs @@ -0,0 +1,80 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing SpecialModelName + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class SpecialModelNameTests + { + // TODO uncomment below to declare an instance variable for SpecialModelName + //private SpecialModelName instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of SpecialModelName + //instance = new SpecialModelName(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of SpecialModelName + /// + [Test] + public void SpecialModelNameInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" SpecialModelName + //Assert.IsInstanceOfType (instance, "variable 'instance' is a SpecialModelName"); + } + + + /// + /// Test the property 'SpecialPropertyName' + /// + [Test] + public void SpecialPropertyNameTest() + { + // TODO unit test for the property 'SpecialPropertyName' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/TagTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/TagTests.cs new file mode 100644 index 00000000000..adb4bf7c8be --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/TagTests.cs @@ -0,0 +1,88 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing Tag + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class TagTests + { + // TODO uncomment below to declare an instance variable for Tag + //private Tag instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of Tag + //instance = new Tag(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of Tag + /// + [Test] + public void TagInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" Tag + //Assert.IsInstanceOfType (instance, "variable 'instance' is a Tag"); + } + + + /// + /// Test the property 'Id' + /// + [Test] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + /// + /// Test the property 'Name' + /// + [Test] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/UserTests.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/UserTests.cs new file mode 100644 index 00000000000..1f64a7aa433 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/Model/UserTests.cs @@ -0,0 +1,136 @@ +/* + * 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 + */ + + +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 IO.Swagger.Test +{ + /// + /// Class for testing User + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class UserTests + { + // TODO uncomment below to declare an instance variable for User + //private User instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of User + //instance = new User(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of User + /// + [Test] + public void UserInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" User + //Assert.IsInstanceOfType (instance, "variable 'instance' is a User"); + } + + + /// + /// Test the property 'Id' + /// + [Test] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + /// + /// Test the property 'Username' + /// + [Test] + public void UsernameTest() + { + // TODO unit test for the property 'Username' + } + /// + /// Test the property 'FirstName' + /// + [Test] + public void FirstNameTest() + { + // TODO unit test for the property 'FirstName' + } + /// + /// Test the property 'LastName' + /// + [Test] + public void LastNameTest() + { + // TODO unit test for the property 'LastName' + } + /// + /// Test the property 'Email' + /// + [Test] + public void EmailTest() + { + // TODO unit test for the property 'Email' + } + /// + /// Test the property 'Password' + /// + [Test] + public void PasswordTest() + { + // TODO unit test for the property 'Password' + } + /// + /// Test the property 'Phone' + /// + [Test] + public void PhoneTest() + { + // TODO unit test for the property 'Phone' + } + /// + /// Test the property 'UserStatus' + /// + [Test] + public void UserStatusTest() + { + // TODO unit test for the property 'UserStatus' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/packages.config b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/packages.config new file mode 100644 index 00000000000..5d9b19287bc --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger.Test/packages.config @@ -0,0 +1,6 @@ + + + + + + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/AnotherFakeApi.cs new file mode 100644 index 00000000000..5c2dd82f5bd --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/AnotherFakeApi.cs @@ -0,0 +1,223 @@ +/* + * 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 + */ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using RestSharp; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace IO.Swagger.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IAnotherFakeApi : IApiAccessor + { + #region Synchronous Operations + /// + /// To test special tags + /// + /// + /// To test special tags + /// + /// Thrown when fails to make API call + /// client model + /// ModelClient + ModelClient TestSpecialTags (ModelClient body); + + /// + /// To test special tags + /// + /// + /// To test special tags + /// + /// Thrown when fails to make API call + /// client model + /// ApiResponse of ModelClient + ApiResponse TestSpecialTagsWithHttpInfo (ModelClient body); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class AnotherFakeApi : IAnotherFakeApi + { + private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public AnotherFakeApi(String basePath) + { + this.Configuration = new Configuration { BasePath = basePath }; + + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public AnotherFakeApi(Configuration configuration = null) + { + if (configuration == null) // use the default one in Configuration + this.Configuration = Configuration.Default; + else + this.Configuration = configuration; + + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// 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 'Configuration.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;} + + /// + /// 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. + /// + /// Dictionary of HTTP header + [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] + public IDictionary DefaultHeader() + { + return new ReadOnlyDictionary(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); + } + + /// + /// To test special tags To test special tags + /// + /// Thrown when fails to make API call + /// client model + /// ModelClient + public ModelClient TestSpecialTags (ModelClient body) + { + ApiResponse localVarResponse = TestSpecialTagsWithHttpInfo(body); + return localVarResponse.Data; + } + + /// + /// To test special tags To test special tags + /// + /// Thrown when fails to make API call + /// client model + /// ApiResponse of ModelClient + public ApiResponse< ModelClient > TestSpecialTagsWithHttpInfo (ModelClient body) + { + // verify the required parameter 'body' is set + if (body == null) + throw new ApiException(400, "Missing required parameter 'body' when calling AnotherFakeApi->TestSpecialTags"); + + var localVarPath = "/another-fake/dummy"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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[] { + "application/json" + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.PATCH, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("TestSpecialTags", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (ModelClient) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ModelClient))); + } + + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/FakeApi.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/FakeApi.cs new file mode 100644 index 00000000000..36f85798534 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/FakeApi.cs @@ -0,0 +1,1058 @@ +/* + * 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 + */ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using RestSharp; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace IO.Swagger.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IFakeApi : IApiAccessor + { + #region Synchronous Operations + /// + /// + /// + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// OuterBoolean + OuterBoolean FakeOuterBooleanSerialize (OuterBoolean body = null); + + /// + /// + /// + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// ApiResponse of OuterBoolean + ApiResponse FakeOuterBooleanSerializeWithHttpInfo (OuterBoolean body = null); + /// + /// + /// + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// OuterComposite + OuterComposite FakeOuterCompositeSerialize (OuterComposite body = null); + + /// + /// + /// + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// ApiResponse of OuterComposite + ApiResponse FakeOuterCompositeSerializeWithHttpInfo (OuterComposite body = null); + /// + /// + /// + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// OuterNumber + OuterNumber FakeOuterNumberSerialize (OuterNumber body = null); + + /// + /// + /// + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// ApiResponse of OuterNumber + ApiResponse FakeOuterNumberSerializeWithHttpInfo (OuterNumber body = null); + /// + /// + /// + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// OuterString + OuterString FakeOuterStringSerialize (OuterString body = null); + + /// + /// + /// + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// ApiResponse of OuterString + ApiResponse FakeOuterStringSerializeWithHttpInfo (OuterString body = null); + /// + /// To test \"client\" model + /// + /// + /// To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// ModelClient + ModelClient TestClientModel (ModelClient body); + + /// + /// To test \"client\" model + /// + /// + /// To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// ApiResponse of ModelClient + ApiResponse TestClientModelWithHttpInfo (ModelClient body); + /// + /// 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) + /// None (optional) + /// None (optional) + /// + void TestEndpointParameters (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = 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) + /// None (optional) + /// None (optional) + /// ApiResponse of Object(void) + ApiResponse TestEndpointParametersWithHttpInfo (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = null); + /// + /// To test enum parameters + /// + /// + /// To test enum parameters + /// + /// Thrown when fails to make API call + /// Form parameter enum test (string array) (optional) + /// Form parameter enum test (string) (optional, default to -efg) + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// + void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null); + + /// + /// To test enum parameters + /// + /// + /// To test enum parameters + /// + /// Thrown when fails to make API call + /// Form parameter enum test (string array) (optional) + /// Form parameter enum test (string) (optional, default to -efg) + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// ApiResponse of Object(void) + ApiResponse TestEnumParametersWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null); + /// + /// test inline additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// + void TestInlineAdditionalProperties (Object param); + + /// + /// test inline additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// ApiResponse of Object(void) + ApiResponse TestInlineAdditionalPropertiesWithHttpInfo (Object param); + /// + /// test json serialization of form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// + void TestJsonFormData (string param, string param2); + + /// + /// test json serialization of form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// ApiResponse of Object(void) + ApiResponse TestJsonFormDataWithHttpInfo (string param, string param2); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class FakeApi : IFakeApi + { + private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public FakeApi(String basePath) + { + this.Configuration = new Configuration { BasePath = basePath }; + + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// 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; + + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// 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 'Configuration.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;} + + /// + /// 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. + /// + /// Dictionary of HTTP header + [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] + public IDictionary DefaultHeader() + { + return new ReadOnlyDictionary(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); + } + + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// OuterBoolean + public OuterBoolean FakeOuterBooleanSerialize (OuterBoolean body = null) + { + ApiResponse localVarResponse = FakeOuterBooleanSerializeWithHttpInfo(body); + return localVarResponse.Data; + } + + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// ApiResponse of OuterBoolean + public ApiResponse< OuterBoolean > FakeOuterBooleanSerializeWithHttpInfo (OuterBoolean body = null) + { + + var localVarPath = "/fake/outer/boolean"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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[] { + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + + // 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 (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("FakeOuterBooleanSerialize", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (OuterBoolean) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OuterBoolean))); + } + + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// OuterComposite + public OuterComposite FakeOuterCompositeSerialize (OuterComposite body = null) + { + ApiResponse localVarResponse = FakeOuterCompositeSerializeWithHttpInfo(body); + return localVarResponse.Data; + } + + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// ApiResponse of OuterComposite + public ApiResponse< OuterComposite > FakeOuterCompositeSerializeWithHttpInfo (OuterComposite body = null) + { + + var localVarPath = "/fake/outer/composite"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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[] { + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + + // 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 (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("FakeOuterCompositeSerialize", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (OuterComposite) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OuterComposite))); + } + + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// OuterNumber + public OuterNumber FakeOuterNumberSerialize (OuterNumber body = null) + { + ApiResponse localVarResponse = FakeOuterNumberSerializeWithHttpInfo(body); + return localVarResponse.Data; + } + + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// ApiResponse of OuterNumber + public ApiResponse< OuterNumber > FakeOuterNumberSerializeWithHttpInfo (OuterNumber body = null) + { + + var localVarPath = "/fake/outer/number"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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[] { + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + + // 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 (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("FakeOuterNumberSerialize", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (OuterNumber) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OuterNumber))); + } + + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// OuterString + public OuterString FakeOuterStringSerialize (OuterString body = null) + { + ApiResponse localVarResponse = FakeOuterStringSerializeWithHttpInfo(body); + return localVarResponse.Data; + } + + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// ApiResponse of OuterString + public ApiResponse< OuterString > FakeOuterStringSerializeWithHttpInfo (OuterString body = null) + { + + var localVarPath = "/fake/outer/string"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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[] { + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + + // 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 (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("FakeOuterStringSerialize", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (OuterString) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OuterString))); + } + + /// + /// To test \"client\" model To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// ModelClient + public ModelClient TestClientModel (ModelClient body) + { + ApiResponse localVarResponse = TestClientModelWithHttpInfo(body); + return localVarResponse.Data; + } + + /// + /// To test \"client\" model To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// ApiResponse of ModelClient + public ApiResponse< ModelClient > TestClientModelWithHttpInfo (ModelClient body) + { + // verify the required parameter 'body' is set + if (body == null) + throw new ApiException(400, "Missing required parameter 'body' when calling FakeApi->TestClientModel"); + + var localVarPath = "/fake"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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[] { + "application/json" + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.PATCH, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("TestClientModel", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (ModelClient) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ModelClient))); + } + + /// + /// 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) + /// None (optional) + /// None (optional) + /// + public void TestEndpointParameters (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = null) + { + TestEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback); + } + + /// + /// 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) + /// None (optional) + /// None (optional) + /// ApiResponse of Object(void) + public ApiResponse TestEndpointParametersWithHttpInfo (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = 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 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) + throw new ApiException(400, "Missing required parameter 'patternWithoutDelimiter' 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 List>(); + 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[] { + "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; charset=utf-8", + "application/json; charset=utf-8" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + 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 (patternWithoutDelimiter != null) localVarFormParams.Add("pattern_without_delimiter", Configuration.ApiClient.ParameterToString(patternWithoutDelimiter)); // 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 + if (callback != null) localVarFormParams.Add("callback", Configuration.ApiClient.ParameterToString(callback)); // form parameter + + // authentication (http_basic_test) required + // http basic authentication required + if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) + { + localVarHeaderParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password); + } + + // 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 (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("TestEndpointParameters", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// To test enum parameters To test enum parameters + /// + /// Thrown when fails to make API call + /// Form parameter enum test (string array) (optional) + /// Form parameter enum test (string) (optional, default to -efg) + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// + public void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null) + { + TestEnumParametersWithHttpInfo(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + } + + /// + /// To test enum parameters To test enum parameters + /// + /// Thrown when fails to make API call + /// Form parameter enum test (string array) (optional) + /// Form parameter enum test (string) (optional, default to -efg) + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// ApiResponse of Object(void) + public ApiResponse TestEnumParametersWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null) + { + + var localVarPath = "/fake"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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[] { + "*/*" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (enumQueryStringArray != null) localVarQueryParams.AddRange(Configuration.ApiClient.ParameterToKeyValuePairs("csv", "enum_query_string_array", enumQueryStringArray)); // query parameter + if (enumQueryString != null) localVarQueryParams.AddRange(Configuration.ApiClient.ParameterToKeyValuePairs("", "enum_query_string", enumQueryString)); // query parameter + if (enumQueryInteger != null) localVarQueryParams.AddRange(Configuration.ApiClient.ParameterToKeyValuePairs("", "enum_query_integer", enumQueryInteger)); // query parameter + if (enumHeaderStringArray != null) localVarHeaderParams.Add("enum_header_string_array", Configuration.ApiClient.ParameterToString(enumHeaderStringArray)); // header parameter + if (enumHeaderString != null) localVarHeaderParams.Add("enum_header_string", Configuration.ApiClient.ParameterToString(enumHeaderString)); // header parameter + if (enumFormStringArray != null) localVarFormParams.Add("enum_form_string_array", Configuration.ApiClient.ParameterToString(enumFormStringArray)); // form parameter + if (enumFormString != null) localVarFormParams.Add("enum_form_string", Configuration.ApiClient.ParameterToString(enumFormString)); // form parameter + if (enumQueryDouble != null) localVarFormParams.Add("enum_query_double", Configuration.ApiClient.ParameterToString(enumQueryDouble)); // form parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("TestEnumParameters", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// test inline additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// + public void TestInlineAdditionalProperties (Object param) + { + TestInlineAdditionalPropertiesWithHttpInfo(param); + } + + /// + /// test inline additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// ApiResponse of Object(void) + public ApiResponse TestInlineAdditionalPropertiesWithHttpInfo (Object param) + { + // verify the required parameter 'param' is set + if (param == null) + throw new ApiException(400, "Missing required parameter 'param' when calling FakeApi->TestInlineAdditionalProperties"); + + var localVarPath = "/fake/inline-additionalProperties"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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[] { + "application/json" + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (param != null && param.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(param); // http body (model) parameter + } + else + { + localVarPostBody = param; // byte array + } + + + // 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 (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("TestInlineAdditionalProperties", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// test json serialization of form data + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// + public void TestJsonFormData (string param, string param2) + { + TestJsonFormDataWithHttpInfo(param, param2); + } + + /// + /// test json serialization of form data + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// ApiResponse of Object(void) + public ApiResponse TestJsonFormDataWithHttpInfo (string param, string param2) + { + // verify the required parameter 'param' is set + if (param == null) + throw new ApiException(400, "Missing required parameter 'param' when calling FakeApi->TestJsonFormData"); + // verify the required parameter 'param2' is set + if (param2 == null) + throw new ApiException(400, "Missing required parameter 'param2' when calling FakeApi->TestJsonFormData"); + + var localVarPath = "/fake/jsonFormData"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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[] { + "application/json" + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (param != null) localVarFormParams.Add("param", Configuration.ApiClient.ParameterToString(param)); // form parameter + if (param2 != null) localVarFormParams.Add("param2", Configuration.ApiClient.ParameterToString(param2)); // form parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("TestJsonFormData", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/FakeClassnameTags123Api.cs new file mode 100644 index 00000000000..9ca1ed03b7b --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/FakeClassnameTags123Api.cs @@ -0,0 +1,228 @@ +/* + * 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 + */ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using RestSharp; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace IO.Swagger.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IFakeClassnameTags123Api : IApiAccessor + { + #region Synchronous Operations + /// + /// To test class name in snake case + /// + /// + /// + /// + /// Thrown when fails to make API call + /// client model + /// ModelClient + ModelClient TestClassname (ModelClient body); + + /// + /// To test class name in snake case + /// + /// + /// + /// + /// Thrown when fails to make API call + /// client model + /// ApiResponse of ModelClient + ApiResponse TestClassnameWithHttpInfo (ModelClient body); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class FakeClassnameTags123Api : IFakeClassnameTags123Api + { + private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public FakeClassnameTags123Api(String basePath) + { + this.Configuration = new Configuration { BasePath = basePath }; + + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public FakeClassnameTags123Api(Configuration configuration = null) + { + if (configuration == null) // use the default one in Configuration + this.Configuration = Configuration.Default; + else + this.Configuration = configuration; + + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// 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 'Configuration.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;} + + /// + /// 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. + /// + /// Dictionary of HTTP header + [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] + public IDictionary DefaultHeader() + { + return new ReadOnlyDictionary(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); + } + + /// + /// To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// ModelClient + public ModelClient TestClassname (ModelClient body) + { + ApiResponse localVarResponse = TestClassnameWithHttpInfo(body); + return localVarResponse.Data; + } + + /// + /// To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// ApiResponse of ModelClient + public ApiResponse< ModelClient > TestClassnameWithHttpInfo (ModelClient body) + { + // verify the required parameter 'body' is set + if (body == null) + throw new ApiException(400, "Missing required parameter 'body' when calling FakeClassnameTags123Api->TestClassname"); + + var localVarPath = "/fake_classname_test"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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[] { + "application/json" + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + // authentication (api_key_query) required + if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarQueryParams.AddRange(Configuration.ApiClient.ParameterToKeyValuePairs("", "api_key_query", Configuration.GetApiKeyWithPrefix("api_key_query"))); + } + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.PATCH, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("TestClassname", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (ModelClient) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ModelClient))); + } + + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/PetApi.cs new file mode 100644 index 00000000000..40e495d110d --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/PetApi.cs @@ -0,0 +1,919 @@ +/* + * 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 + */ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using RestSharp; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace IO.Swagger.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IPetApi : IApiAccessor + { + #region Synchronous Operations + /// + /// Add a new pet to the store + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// + void AddPet (Pet body); + + /// + /// Add a new pet to the store + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// ApiResponse of Object(void) + ApiResponse AddPetWithHttpInfo (Pet body); + /// + /// Deletes a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// + void DeletePet (long? petId, string apiKey = null); + + /// + /// Deletes a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// ApiResponse of Object(void) + ApiResponse DeletePetWithHttpInfo (long? petId, string apiKey = null); + /// + /// Finds Pets by status + /// + /// + /// Multiple status values can be provided with comma separated strings + /// + /// Thrown when fails to make API call + /// Status values that need to be considered for filter + /// List<Pet> + List FindPetsByStatus (List status); + + /// + /// Finds Pets by status + /// + /// + /// Multiple status values can be provided with comma separated strings + /// + /// Thrown when fails to make API call + /// Status values that need to be considered for filter + /// ApiResponse of List<Pet> + ApiResponse> FindPetsByStatusWithHttpInfo (List status); + /// + /// Finds Pets by tags + /// + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// List<Pet> + List FindPetsByTags (List tags); + + /// + /// Finds Pets by tags + /// + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// ApiResponse of List<Pet> + ApiResponse> FindPetsByTagsWithHttpInfo (List tags); + /// + /// Find pet by ID + /// + /// + /// Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Pet + Pet GetPetById (long? petId); + + /// + /// Find pet by ID + /// + /// + /// Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// ApiResponse of Pet + ApiResponse GetPetByIdWithHttpInfo (long? petId); + /// + /// Update an existing pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// + void UpdatePet (Pet body); + + /// + /// Update an existing pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// ApiResponse of Object(void) + ApiResponse UpdatePetWithHttpInfo (Pet body); + /// + /// Updates a pet in the store with form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// + void UpdatePetWithForm (long? petId, string name = null, string status = null); + + /// + /// Updates a pet in the store with form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// ApiResponse of Object(void) + ApiResponse UpdatePetWithFormWithHttpInfo (long? petId, string name = null, string status = null); + /// + /// uploads an image + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// ApiResponse + ApiResponse UploadFile (long? petId, string additionalMetadata = null, System.IO.Stream file = null); + + /// + /// uploads an image + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// ApiResponse of ApiResponse + ApiResponse UploadFileWithHttpInfo (long? petId, string additionalMetadata = null, System.IO.Stream file = null); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class PetApi : IPetApi + { + private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public PetApi(String basePath) + { + this.Configuration = new Configuration { BasePath = basePath }; + + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public PetApi(Configuration configuration = null) + { + if (configuration == null) // use the default one in Configuration + this.Configuration = Configuration.Default; + else + this.Configuration = configuration; + + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// 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 'Configuration.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;} + + /// + /// 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. + /// + /// Dictionary of HTTP header + [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] + public IDictionary DefaultHeader() + { + return new ReadOnlyDictionary(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); + } + + /// + /// Add a new pet to the store + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// + public void AddPet (Pet body) + { + AddPetWithHttpInfo(body); + } + + /// + /// Add a new pet to the store + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// ApiResponse of Object(void) + public ApiResponse AddPetWithHttpInfo (Pet body) + { + // verify the required parameter 'body' is set + if (body == null) + throw new ApiException(400, "Missing required parameter 'body' when calling PetApi->AddPet"); + + var localVarPath = "/pet"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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[] { + "application/json", + "application/xml" + }; + 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); + + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + // authentication (petstore_auth) required + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + // 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 (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("AddPet", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// Deletes a pet + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// + public void DeletePet (long? petId, string apiKey = null) + { + DeletePetWithHttpInfo(petId, apiKey); + } + + /// + /// Deletes a pet + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// ApiResponse of Object(void) + public ApiResponse DeletePetWithHttpInfo (long? petId, string apiKey = null) + { + // verify the required parameter 'petId' is set + if (petId == null) + throw new ApiException(400, "Missing required parameter 'petId' when calling PetApi->DeletePet"); + + var localVarPath = "/pet/{petId}"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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); + + if (petId != null) localVarPathParams.Add("petId", Configuration.ApiClient.ParameterToString(petId)); // path parameter + if (apiKey != null) localVarHeaderParams.Add("api_key", Configuration.ApiClient.ParameterToString(apiKey)); // header parameter + + // authentication (petstore_auth) required + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DeletePet", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// Finds Pets by status Multiple status values can be provided with comma separated strings + /// + /// Thrown when fails to make API call + /// Status values that need to be considered for filter + /// List<Pet> + public List FindPetsByStatus (List status) + { + ApiResponse> localVarResponse = FindPetsByStatusWithHttpInfo(status); + return localVarResponse.Data; + } + + /// + /// Finds Pets by status Multiple status values can be provided with comma separated strings + /// + /// Thrown when fails to make API call + /// Status values that need to be considered for filter + /// ApiResponse of List<Pet> + public ApiResponse< List > FindPetsByStatusWithHttpInfo (List status) + { + // verify the required parameter 'status' is set + if (status == null) + throw new ApiException(400, "Missing required parameter 'status' when calling PetApi->FindPetsByStatus"); + + var localVarPath = "/pet/findByStatus"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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); + + if (status != null) localVarQueryParams.AddRange(Configuration.ApiClient.ParameterToKeyValuePairs("csv", "status", status)); // query parameter + + // authentication (petstore_auth) required + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + 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()), + (List) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List))); + } + + /// + /// Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// List<Pet> + public List FindPetsByTags (List tags) + { + ApiResponse> localVarResponse = FindPetsByTagsWithHttpInfo(tags); + return localVarResponse.Data; + } + + /// + /// Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// ApiResponse of List<Pet> + public ApiResponse< List > FindPetsByTagsWithHttpInfo (List tags) + { + // verify the required parameter 'tags' is set + if (tags == null) + throw new ApiException(400, "Missing required parameter 'tags' when calling PetApi->FindPetsByTags"); + + var localVarPath = "/pet/findByTags"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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); + + if (tags != null) localVarQueryParams.AddRange(Configuration.ApiClient.ParameterToKeyValuePairs("csv", "tags", tags)); // query parameter + + // authentication (petstore_auth) required + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + 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()), + (List) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List))); + } + + /// + /// Find pet by ID Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Pet + public Pet GetPetById (long? petId) + { + ApiResponse localVarResponse = GetPetByIdWithHttpInfo(petId); + return localVarResponse.Data; + } + + /// + /// Find pet by ID Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// ApiResponse of Pet + public ApiResponse< Pet > GetPetByIdWithHttpInfo (long? petId) + { + // verify the required parameter 'petId' is set + if (petId == null) + throw new ApiException(400, "Missing required parameter 'petId' when calling PetApi->GetPetById"); + + var localVarPath = "/pet/{petId}"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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); + + if (petId != null) localVarPathParams.Add("petId", Configuration.ApiClient.ParameterToString(petId)); // path parameter + + // authentication (api_key) required + if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("api_key"))) + { + localVarHeaderParams["api_key"] = Configuration.GetApiKeyWithPrefix("api_key"); + } + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + 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()), + (Pet) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Pet))); + } + + /// + /// Update an existing pet + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// + public void UpdatePet (Pet body) + { + UpdatePetWithHttpInfo(body); + } + + /// + /// Update an existing pet + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// ApiResponse of Object(void) + public ApiResponse UpdatePetWithHttpInfo (Pet body) + { + // verify the required parameter 'body' is set + if (body == null) + throw new ApiException(400, "Missing required parameter 'body' when calling PetApi->UpdatePet"); + + var localVarPath = "/pet"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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[] { + "application/json", + "application/xml" + }; + 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); + + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + // authentication (petstore_auth) required + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UpdatePet", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// Updates a pet in the store with form data + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// + public void UpdatePetWithForm (long? petId, string name = null, string status = null) + { + UpdatePetWithFormWithHttpInfo(petId, name, status); + } + + /// + /// Updates a pet in the store with form data + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// ApiResponse of Object(void) + public ApiResponse UpdatePetWithFormWithHttpInfo (long? petId, string name = null, string status = null) + { + // verify the required parameter 'petId' is set + if (petId == null) + throw new ApiException(400, "Missing required parameter 'petId' when calling PetApi->UpdatePetWithForm"); + + var localVarPath = "/pet/{petId}"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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[] { + "application/x-www-form-urlencoded" + }; + 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); + + if (petId != null) localVarPathParams.Add("petId", Configuration.ApiClient.ParameterToString(petId)); // path parameter + if (name != null) localVarFormParams.Add("name", Configuration.ApiClient.ParameterToString(name)); // form parameter + if (status != null) localVarFormParams.Add("status", Configuration.ApiClient.ParameterToString(status)); // form parameter + + // authentication (petstore_auth) required + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + // 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 (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UpdatePetWithForm", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// uploads an image + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// ApiResponse + public ApiResponse UploadFile (long? petId, string additionalMetadata = null, System.IO.Stream file = null) + { + ApiResponse localVarResponse = UploadFileWithHttpInfo(petId, additionalMetadata, file); + return localVarResponse.Data; + } + + /// + /// uploads an image + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// ApiResponse of ApiResponse + public ApiResponse< ApiResponse > UploadFileWithHttpInfo (long? petId, string additionalMetadata = null, System.IO.Stream file = null) + { + // verify the required parameter 'petId' is set + if (petId == null) + throw new ApiException(400, "Missing required parameter 'petId' when calling PetApi->UploadFile"); + + var localVarPath = "/pet/{petId}/uploadImage"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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[] { + "multipart/form-data" + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (petId != null) localVarPathParams.Add("petId", Configuration.ApiClient.ParameterToString(petId)); // path parameter + if (additionalMetadata != null) localVarFormParams.Add("additionalMetadata", Configuration.ApiClient.ParameterToString(additionalMetadata)); // form parameter + if (file != null) localVarFileParams.Add("file", Configuration.ApiClient.ParameterToFile("file", file)); + + // authentication (petstore_auth) required + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + // 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 (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()), + (ApiResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ApiResponse))); + } + + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/StoreApi.cs new file mode 100644 index 00000000000..8829f14e96c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/StoreApi.cs @@ -0,0 +1,482 @@ +/* + * 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 + */ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using RestSharp; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace IO.Swagger.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IStoreApi : IApiAccessor + { + #region Synchronous Operations + /// + /// Delete purchase order by ID + /// + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// + void DeleteOrder (string orderId); + + /// + /// Delete purchase order by ID + /// + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// ApiResponse of Object(void) + ApiResponse DeleteOrderWithHttpInfo (string orderId); + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Dictionary<string, int?> + Dictionary GetInventory (); + + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// ApiResponse of Dictionary<string, int?> + ApiResponse> GetInventoryWithHttpInfo (); + /// + /// Find purchase order by ID + /// + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Order + Order GetOrderById (long? orderId); + + /// + /// Find purchase order by ID + /// + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// ApiResponse of Order + ApiResponse GetOrderByIdWithHttpInfo (long? orderId); + /// + /// Place an order for a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Order + Order PlaceOrder (Order body); + + /// + /// Place an order for a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// ApiResponse of Order + ApiResponse PlaceOrderWithHttpInfo (Order body); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class StoreApi : IStoreApi + { + private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public StoreApi(String basePath) + { + this.Configuration = new Configuration { BasePath = basePath }; + + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public StoreApi(Configuration configuration = null) + { + if (configuration == null) // use the default one in Configuration + this.Configuration = Configuration.Default; + else + this.Configuration = configuration; + + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// 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 'Configuration.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;} + + /// + /// 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. + /// + /// Dictionary of HTTP header + [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] + public IDictionary DefaultHeader() + { + return new ReadOnlyDictionary(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); + } + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// + public void DeleteOrder (string orderId) + { + 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 + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// ApiResponse of Object(void) + public ApiResponse DeleteOrderWithHttpInfo (string orderId) + { + // verify the required parameter 'orderId' is set + if (orderId == null) + throw new ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); + + var localVarPath = "/store/order/{order_id}"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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); + + if (orderId != null) localVarPathParams.Add("order_id", Configuration.ApiClient.ParameterToString(orderId)); // path parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DeleteOrder", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Dictionary<string, int?> + public Dictionary GetInventory () + { + ApiResponse> localVarResponse = GetInventoryWithHttpInfo(); + return localVarResponse.Data; + } + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// ApiResponse of Dictionary<string, int?> + public ApiResponse< Dictionary > GetInventoryWithHttpInfo () + { + + var localVarPath = "/store/inventory"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + + // authentication (api_key) required + if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("api_key"))) + { + localVarHeaderParams["api_key"] = Configuration.GetApiKeyWithPrefix("api_key"); + } + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + 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()), + (Dictionary) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Dictionary))); + } + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Order + public Order GetOrderById (long? orderId) + { + ApiResponse localVarResponse = GetOrderByIdWithHttpInfo(orderId); + return localVarResponse.Data; + } + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// ApiResponse of Order + public ApiResponse< Order > GetOrderByIdWithHttpInfo (long? orderId) + { + // verify the required parameter 'orderId' is set + if (orderId == null) + throw new ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->GetOrderById"); + + var localVarPath = "/store/order/{order_id}"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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); + + if (orderId != null) localVarPathParams.Add("order_id", Configuration.ApiClient.ParameterToString(orderId)); // path parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + 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()), + (Order) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Order))); + } + + /// + /// Place an order for a pet + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Order + public Order PlaceOrder (Order body) + { + ApiResponse localVarResponse = PlaceOrderWithHttpInfo(body); + return localVarResponse.Data; + } + + /// + /// Place an order for a pet + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// ApiResponse of Order + public ApiResponse< Order > PlaceOrderWithHttpInfo (Order body) + { + // verify the required parameter 'body' is set + if (body == null) + throw new ApiException(400, "Missing required parameter 'body' when calling StoreApi->PlaceOrder"); + + var localVarPath = "/store/order"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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); + + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + + // 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 (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()), + (Order) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Order))); + } + + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/UserApi.cs new file mode 100644 index 00000000000..5d8c4507bb6 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Api/UserApi.cs @@ -0,0 +1,862 @@ +/* + * 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 + */ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using RestSharp; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace IO.Swagger.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IUserApi : IApiAccessor + { + #region Synchronous Operations + /// + /// Create user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// + void CreateUser (User body); + + /// + /// Create user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// ApiResponse of Object(void) + ApiResponse CreateUserWithHttpInfo (User body); + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// + void CreateUsersWithArrayInput (List body); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// ApiResponse of Object(void) + ApiResponse CreateUsersWithArrayInputWithHttpInfo (List body); + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// + void CreateUsersWithListInput (List body); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// ApiResponse of Object(void) + ApiResponse CreateUsersWithListInputWithHttpInfo (List body); + /// + /// Delete user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// + void DeleteUser (string username); + + /// + /// Delete user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// ApiResponse of Object(void) + ApiResponse DeleteUserWithHttpInfo (string username); + /// + /// Get user by user name + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// User + User GetUserByName (string username); + + /// + /// Get user by user name + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// ApiResponse of User + ApiResponse GetUserByNameWithHttpInfo (string username); + /// + /// Logs user into the system + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// string + string LoginUser (string username, string password); + + /// + /// Logs user into the system + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// ApiResponse of string + ApiResponse LoginUserWithHttpInfo (string username, string password); + /// + /// Logs out current logged in user session + /// + /// + /// + /// + /// Thrown when fails to make API call + /// + void LogoutUser (); + + /// + /// Logs out current logged in user session + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ApiResponse of Object(void) + ApiResponse LogoutUserWithHttpInfo (); + /// + /// Updated user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// + void UpdateUser (string username, User body); + + /// + /// Updated user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// ApiResponse of Object(void) + ApiResponse UpdateUserWithHttpInfo (string username, User body); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class UserApi : IUserApi + { + private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public UserApi(String basePath) + { + this.Configuration = new Configuration { BasePath = basePath }; + + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public UserApi(Configuration configuration = null) + { + if (configuration == null) // use the default one in Configuration + this.Configuration = Configuration.Default; + else + this.Configuration = configuration; + + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// 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 'Configuration.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;} + + /// + /// 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. + /// + /// Dictionary of HTTP header + [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] + public IDictionary DefaultHeader() + { + return new ReadOnlyDictionary(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); + } + + /// + /// Create user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// + public void CreateUser (User body) + { + CreateUserWithHttpInfo(body); + } + + /// + /// Create user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// ApiResponse of Object(void) + public ApiResponse CreateUserWithHttpInfo (User body) + { + // verify the required parameter 'body' is set + if (body == null) + throw new ApiException(400, "Missing required parameter 'body' when calling UserApi->CreateUser"); + + var localVarPath = "/user"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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); + + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + + // 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 (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("CreateUser", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// + public void CreateUsersWithArrayInput (List body) + { + CreateUsersWithArrayInputWithHttpInfo(body); + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// ApiResponse of Object(void) + public ApiResponse CreateUsersWithArrayInputWithHttpInfo (List body) + { + // verify the required parameter 'body' is set + if (body == null) + throw new ApiException(400, "Missing required parameter 'body' when calling UserApi->CreateUsersWithArrayInput"); + + var localVarPath = "/user/createWithArray"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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); + + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + + // 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 (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// + public void CreateUsersWithListInput (List body) + { + CreateUsersWithListInputWithHttpInfo(body); + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// ApiResponse of Object(void) + public ApiResponse CreateUsersWithListInputWithHttpInfo (List body) + { + // verify the required parameter 'body' is set + if (body == null) + throw new ApiException(400, "Missing required parameter 'body' when calling UserApi->CreateUsersWithListInput"); + + var localVarPath = "/user/createWithList"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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); + + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + + // 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 (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("CreateUsersWithListInput", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// Delete user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// + public void DeleteUser (string username) + { + DeleteUserWithHttpInfo(username); + } + + /// + /// Delete user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// ApiResponse of Object(void) + public ApiResponse DeleteUserWithHttpInfo (string username) + { + // verify the required parameter 'username' is set + if (username == null) + throw new ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); + + var localVarPath = "/user/{username}"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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); + + if (username != null) localVarPathParams.Add("username", Configuration.ApiClient.ParameterToString(username)); // path parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DeleteUser", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// Get user by user name + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// User + public User GetUserByName (string username) + { + ApiResponse localVarResponse = GetUserByNameWithHttpInfo(username); + return localVarResponse.Data; + } + + /// + /// Get user by user name + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// ApiResponse of User + public ApiResponse< User > GetUserByNameWithHttpInfo (string username) + { + // verify the required parameter 'username' is set + if (username == null) + throw new ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); + + var localVarPath = "/user/{username}"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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); + + if (username != null) localVarPathParams.Add("username", Configuration.ApiClient.ParameterToString(username)); // path parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + 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()), + (User) Configuration.ApiClient.Deserialize(localVarResponse, typeof(User))); + } + + /// + /// Logs user into the system + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// string + public string LoginUser (string username, string password) + { + ApiResponse localVarResponse = LoginUserWithHttpInfo(username, password); + return localVarResponse.Data; + } + + /// + /// Logs user into the system + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// ApiResponse of string + public ApiResponse< string > LoginUserWithHttpInfo (string username, string password) + { + // verify the required parameter 'username' is set + if (username == null) + throw new ApiException(400, "Missing required parameter 'username' when calling UserApi->LoginUser"); + // verify the required parameter 'password' is set + if (password == null) + throw new ApiException(400, "Missing required parameter 'password' when calling UserApi->LoginUser"); + + var localVarPath = "/user/login"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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); + + if (username != null) localVarQueryParams.AddRange(Configuration.ApiClient.ParameterToKeyValuePairs("", "username", username)); // query parameter + if (password != null) localVarQueryParams.AddRange(Configuration.ApiClient.ParameterToKeyValuePairs("", "password", password)); // query parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + 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()), + (string) Configuration.ApiClient.Deserialize(localVarResponse, typeof(string))); + } + + /// + /// Logs out current logged in user session + /// + /// Thrown when fails to make API call + /// + public void LogoutUser () + { + LogoutUserWithHttpInfo(); + } + + /// + /// Logs out current logged in user session + /// + /// Thrown when fails to make API call + /// ApiResponse of Object(void) + public ApiResponse LogoutUserWithHttpInfo () + { + + var localVarPath = "/user/logout"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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); + + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("LogoutUser", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// Updated user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// + public void UpdateUser (string username, User body) + { + UpdateUserWithHttpInfo(username, body); + } + + /// + /// Updated user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// ApiResponse of Object(void) + public ApiResponse UpdateUserWithHttpInfo (string username, User body) + { + // verify the required parameter 'username' is set + if (username == null) + throw new ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); + // verify the required parameter 'body' is set + if (body == null) + throw new ApiException(400, "Missing required parameter 'body' when calling UserApi->UpdateUser"); + + var localVarPath = "/user/{username}"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + 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); + + if (username != null) localVarPathParams.Add("username", Configuration.ApiClient.ParameterToString(username)); // path parameter + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UpdateUser", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/ApiClient.cs new file mode 100644 index 00000000000..db66a078c13 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/ApiClient.cs @@ -0,0 +1,504 @@ +/* + * 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 + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; +using System.IO; +using System.Web; +using System.Linq; +using System.Net; +using System.Text; +using Newtonsoft.Json; +using RestSharp; + +namespace IO.Swagger.Client +{ + /// + /// API client is mainly responsible for making the HTTP call to the API backend. + /// + 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. + /// + public ApiClient() + { + Configuration = IO.Swagger.Client.Configuration.Default; + RestClient = new RestClient("http://petstore.swagger.io:80/v2"); + } + + /// + /// Initializes a new instance of the class + /// with default base path (http://petstore.swagger.io:80/v2). + /// + /// An instance of Configuration. + public ApiClient(Configuration config) + { + Configuration = config ?? IO.Swagger.Client.Configuration.Default; + + RestClient = new RestClient(Configuration.BasePath); + } + + /// + /// Initializes a new instance of the class + /// with default configuration. + /// + /// The base path. + public ApiClient(String basePath = "http://petstore.swagger.io:80/v2") + { + if (String.IsNullOrEmpty(basePath)) + throw new ArgumentException("basePath cannot be empty"); + + RestClient = new RestClient(basePath); + Configuration = Client.Configuration.Default; + } + + /// + /// Gets or sets the default API client for making HTTP calls. + /// + /// The default API client. + [Obsolete("ApiClient.Default is deprecated, please use 'Configuration.Default.ApiClient' instead.")] + public static ApiClient Default; + + /// + /// Gets or sets an instance of the IReadableConfiguration. + /// + /// An instance of the IReadableConfiguration. + /// + /// helps us to avoid modifying possibly global + /// configuration values from within a given client. It does not gaurantee thread-safety + /// of the instance in any way. + /// + public IReadableConfiguration Configuration { get; set; } + + /// + /// Gets or sets the RestClient. + /// + /// An instance of the RestClient + public RestClient RestClient { get; set; } + + // Creates and sets up a RestRequest prior to a call. + private RestRequest PrepareRequest( + String path, RestSharp.Method method, List> queryParams, Object postBody, + Dictionary headerParams, Dictionary formParams, + Dictionary fileParams, Dictionary pathParams, + String contentType) + { + var request = new RestRequest(path, method); + + // add path parameter, if any + foreach(var param in pathParams) + request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment); + + // add header parameter, if any + foreach(var param in headerParams) + request.AddHeader(param.Key, param.Value); + + // add query parameter, if any + foreach(var param in queryParams) + request.AddQueryParameter(param.Key, param.Value); + + // add form parameter, if any + foreach(var param in formParams) + request.AddParameter(param.Key, param.Value); + + // add file parameter, if any + foreach(var param in fileParams) + { + request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType); + } + + if (postBody != null) // http body (model or byte[]) parameter + { + request.AddParameter(contentType, postBody, ParameterType.RequestBody); + } + + return request; + } + + /// + /// Makes the HTTP request (Sync). + /// + /// URL path. + /// HTTP method. + /// Query parameters. + /// HTTP body (POST request). + /// Header parameters. + /// Form parameters. + /// File parameters. + /// Path parameters. + /// Content Type of the request + /// Object + public Object CallApi( + String path, RestSharp.Method method, List> queryParams, Object postBody, + Dictionary headerParams, Dictionary formParams, + Dictionary fileParams, Dictionary pathParams, + String contentType) + { + var request = PrepareRequest( + path, method, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, contentType); + + // set timeout + + RestClient.Timeout = Configuration.Timeout; + // set user agent + RestClient.UserAgent = Configuration.UserAgent; + + InterceptRequest(request); + var response = RestClient.Execute(request); + InterceptResponse(request, response); + + return (Object) response; + } + + + /// + /// Escape string (url-encoded). + /// + /// String to be escaped. + /// Escaped string. + public string EscapeString(string str) + { + return UrlEncode(str); + } + + /// + /// Create FileParameter based on Stream. + /// + /// Parameter name. + /// Input stream. + /// FileParameter. + public FileParameter ParameterToFile(string name, Stream stream) + { + if (stream is FileStream) + return FileParameter.Create(name, ReadAsBytes(stream), Path.GetFileName(((FileStream)stream).Name)); + else + return FileParameter.Create(name, ReadAsBytes(stream), "no_file_name_provided"); + } + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// Formatted string. + public string ParameterToString(object obj) + { + if (obj is DateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return ((DateTime)obj).ToString (Configuration.DateTimeFormat); + else if (obj is DateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat); + else if (obj is IList) + { + var flattenedString = new StringBuilder(); + foreach (var param in (IList)obj) + { + if (flattenedString.Length > 0) + flattenedString.Append(","); + flattenedString.Append(param); + } + return flattenedString.ToString(); + } + else + return Convert.ToString (obj); + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// The HTTP response. + /// Object type. + /// Object representation of the JSON string. + public object Deserialize(IRestResponse response, Type type) + { + IList headers = response.Headers; + if (type == typeof(byte[])) // return byte array + { + return response.RawBytes; + } + + // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) + if (type == typeof(Stream)) + { + if (headers != null) + { + var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath) + ? Path.GetTempPath() + : Configuration.TempFolderPath; + var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); + foreach (var header in headers) + { + var match = regex.Match(header.ToString()); + if (match.Success) + { + string fileName = filePath + SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); + File.WriteAllBytes(fileName, response.RawBytes); + return new FileStream(fileName, FileMode.Open); + } + } + } + var stream = new MemoryStream(response.RawBytes); + return stream; + } + + if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object + { + return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + } + + if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type + { + return ConvertType(response.Content, type); + } + + // at this point, it must be a model (json) + try + { + return JsonConvert.DeserializeObject(response.Content, type, serializerSettings); + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + /// + /// Serialize an input (model) into JSON string + /// + /// Object. + /// JSON string. + public String Serialize(object obj) + { + try + { + return obj != null ? JsonConvert.SerializeObject(obj) : null; + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + /// + ///Check if the given MIME is a JSON MIME. + ///JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public bool IsJsonMime(String mime) + { + var jsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"); + return mime != null && (jsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json")); + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public String SelectHeaderContentType(String[] contentTypes) + { + if (contentTypes.Length == 0) + return "application/json"; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType.ToLower())) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// 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) + /// + /// The accepts array to select from. + /// The Accept header to use. + public String SelectHeaderAccept(String[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return String.Join(",", accepts); + } + + /// + /// Encode string in base64 format. + /// + /// String to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Dynamically cast the object into target type. + /// + /// Object to be casted + /// Target type + /// Casted object + public static object ConvertType(T fromObject, Type toObject) where T : class + { + return Convert.ChangeType(fromObject, toObject); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + byte[] buf = new byte[16*1024]; + using (MemoryStream ms = new MemoryStream()) + { + int count; + while ((count = inputStream.Read(buf, 0, buf.Length)) > 0) + { + ms.Write(buf, 0, count); + } + return ms.ToArray(); + } + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// String to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Sanitize filename by removing the path + /// + /// Filename + /// Filename + public static string SanitizeFilename(string filename) + { + Match match = Regex.Match(filename, @".*[/\\](.*)$"); + + if (match.Success) + { + return match.Groups[1].Value; + } + else + { + return filename; + } + } + + /// + /// Convert params to key/value pairs. + /// Use collectionFormat to properly format lists and collections. + /// + /// Key name. + /// Value object. + /// A list of KeyValuePairs + public IEnumerable> ParameterToKeyValuePairs(string collectionFormat, string name, object value) + { + var parameters = new List>(); + + if (IsCollection(value) && collectionFormat == "multi") + { + var valueCollection = value as IEnumerable; + parameters.AddRange(from object item in valueCollection select new KeyValuePair(name, ParameterToString(item))); + } + else + { + parameters.Add(new KeyValuePair(name, ParameterToString(value))); + } + + return parameters; + } + + /// + /// Check if generic object is a collection. + /// + /// + /// True if object is a collection type + private static bool IsCollection(object value) + { + return value is IList || value is ICollection; + } + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/ApiException.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/ApiException.cs new file mode 100644 index 00000000000..8f0fc5a05d5 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/ApiException.cs @@ -0,0 +1,60 @@ +/* + * 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 + */ + +using System; + +namespace IO.Swagger.Client +{ + /// + /// API Exception + /// + public class ApiException : Exception + { + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). + public int ErrorCode { get; set; } + + /// + /// Gets or sets the error content (body json object) + /// + /// The error content (Http response body). + public object ErrorContent { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public ApiException() {} + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + public ApiException(int errorCode, string message) : base(message) + { + this.ErrorCode = errorCode; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Error content. + public ApiException(int errorCode, string message, object errorContent = null) : base(message) + { + this.ErrorCode = errorCode; + this.ErrorContent = errorContent; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/ApiResponse.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/ApiResponse.cs new file mode 100644 index 00000000000..b21347aa408 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/ApiResponse.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 + */ + +using System; +using System.Collections.Generic; + +namespace IO.Swagger.Client +{ + /// + /// API Response + /// + public class ApiResponse + { + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + public int StatusCode { get; private set; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public IDictionary Headers { get; private set; } + + /// + /// Gets or sets the data (parsed HTTP body) + /// + /// The data. + public T Data { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + public ApiResponse(int statusCode, IDictionary headers, T data) + { + this.StatusCode= statusCode; + this.Headers = headers; + this.Data = data; + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/Configuration.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/Configuration.cs new file mode 100644 index 00000000000..531d240482a --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/Configuration.cs @@ -0,0 +1,453 @@ +/* + * 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 + */ + +using System; +using System.Reflection; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace IO.Swagger.Client +{ + /// + /// Represents a set of configuration settings + /// + public class Configuration : IReadableConfiguration + { + #region Constants + + /// + /// Version of the package. + /// + /// Version of the package. + public const string Version = "1.0.0"; + + /// + /// Identifier for ISO 8601 DateTime Format + /// + /// See https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 for more information. + // ReSharper disable once InconsistentNaming + public const string ISO8601_DATETIME_FORMAT = "o"; + + #endregion Constants + + #region Static Members + + private static readonly object GlobalConfigSync = new { }; + private static Configuration _globalConfiguration; + + /// + /// Default creation of exceptions for a given method name and response object + /// + public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => + { + var 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 default Configuration. + /// + /// Configuration. + public static Configuration Default + { + get { return _globalConfiguration; } + set + { + lock (GlobalConfigSync) + { + _globalConfiguration = value; + } + } + } + + #endregion Static Members + + #region Private Members + + /// + /// Gets or sets the API key based on the authentication name. + /// + /// The API key. + private IDictionary _apiKey = null; + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// The prefix of the API key. + private IDictionary _apiKeyPrefix = null; + + private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; + private string _tempFolderPath = Path.GetTempPath(); + + #endregion Private Members + + #region Constructors + + static Configuration() + { + _globalConfiguration = new GlobalConfiguration(); + } + + /// + /// Initializes a new instance of the class + /// + public Configuration() + { + UserAgent = "Swagger-Codegen/1.0.0/csharp"; + BasePath = "http://petstore.swagger.io:80/v2"; + DefaultHeader = new ConcurrentDictionary(); + ApiKey = new ConcurrentDictionary(); + ApiKeyPrefix = new ConcurrentDictionary(); + + // Setting Timeout has side effects (forces ApiClient creation). + Timeout = 100000; + } + + /// + /// Initializes a new instance of the class + /// + public Configuration( + IDictionary defaultHeader, + IDictionary apiKey, + IDictionary apiKeyPrefix, + string basePath = "http://petstore.swagger.io:80/v2") : this() + { + if (string.IsNullOrWhiteSpace(basePath)) + throw new ArgumentException("The provided basePath is invalid.", "basePath"); + if (defaultHeader == null) + throw new ArgumentNullException("defaultHeader"); + if (apiKey == null) + throw new ArgumentNullException("apiKey"); + if (apiKeyPrefix == null) + throw new ArgumentNullException("apiKeyPrefix"); + + BasePath = basePath; + + foreach (var keyValuePair in defaultHeader) + { + DefaultHeader.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKey) + { + ApiKey.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKeyPrefix) + { + ApiKeyPrefix.Add(keyValuePair); + } + } + + /// + /// Initializes a new instance of the class with different settings + /// + /// Api client + /// Dictionary of default HTTP header + /// Username + /// Password + /// accessToken + /// Dictionary of API key + /// Dictionary of API key prefix + /// Temp folder path + /// DateTime format string + /// HTTP connection timeout (in milliseconds) + /// HTTP user agent + [Obsolete("Use explicit object construction and setting of properties.", true)] + public Configuration( + // ReSharper disable UnusedParameter.Local + ApiClient apiClient = null, + IDictionary defaultHeader = null, + string username = null, + string password = null, + string accessToken = null, + IDictionary apiKey = null, + IDictionary apiKeyPrefix = null, + string tempFolderPath = null, + string dateTimeFormat = null, + int timeout = 100000, + string userAgent = "Swagger-Codegen/1.0.0/csharp" + // ReSharper restore UnusedParameter.Local + ) + { + + } + + /// + /// Initializes a new instance of the Configuration class. + /// + /// Api client. + [Obsolete("This constructor caused unexpected sharing of static data. It is no longer supported.", true)] + // ReSharper disable once UnusedParameter.Local + public Configuration(ApiClient apiClient) + { + + } + + #endregion Constructors + + + #region Properties + + private ApiClient _apiClient = null; + /// + /// Gets an instance of an ApiClient for this configuration + /// + public virtual ApiClient ApiClient + { + get + { + if (_apiClient == null) _apiClient = CreateApiClient(); + return _apiClient; + } + } + + private String _basePath = null; + /// + /// Gets or sets the base path for API access. + /// + public virtual string BasePath { + get { return _basePath; } + set { + _basePath = value; + // pass-through to ApiClient if it's set. + if(_apiClient != null) { + _apiClient.RestClient.BaseUrl = new Uri(_basePath); + } + } + } + + /// + /// Gets or sets the default header. + /// + public virtual IDictionary DefaultHeader { get; set; } + + /// + /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. + /// + public virtual int Timeout + { + + get { return ApiClient.RestClient.Timeout; } + set { ApiClient.RestClient.Timeout = value; } + } + + /// + /// Gets or sets the HTTP user agent. + /// + /// Http user agent. + public virtual string UserAgent { get; set; } + + /// + /// Gets or sets the username (HTTP basic authentication). + /// + /// The username. + public virtual string Username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication). + /// + /// The password. + public virtual string Password { get; set; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + public string GetApiKeyWithPrefix(string apiKeyIdentifier) + { + var apiKeyValue = ""; + ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue); + var apiKeyPrefix = ""; + if (ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) + return apiKeyPrefix + " " + apiKeyValue; + else + return apiKeyValue; + } + + /// + /// Gets or sets the access token for OAuth2 authentication. + /// + /// The access token. + public virtual string AccessToken { get; set; } + + /// + /// Gets or sets the temporary folder path to store the files downloaded from the server. + /// + /// Folder path. + public virtual string TempFolderPath + { + get { return _tempFolderPath; } + + set + { + if (string.IsNullOrEmpty(value)) + { + // Possible breaking change since swagger-codegen 2.2.1, enforce a valid temporary path on set. + _tempFolderPath = Path.GetTempPath(); + return; + } + + // create the directory if it does not exist + if (!Directory.Exists(value)) + { + Directory.CreateDirectory(value); + } + + // check if the path contains directory separator at the end + if (value[value.Length - 1] == Path.DirectorySeparatorChar) + { + _tempFolderPath = value; + } + else + { + _tempFolderPath = value + Path.DirectorySeparatorChar; + } + } + } + + /// + /// Gets or sets the the date time format used when serializing in the ApiClient + /// By default, it's set to ISO 8601 - "o", for others see: + /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx + /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx + /// No validation is done to ensure that the string you're providing is valid + /// + /// The DateTimeFormat string + public virtual string DateTimeFormat + { + get { return _dateTimeFormat; } + set + { + if (string.IsNullOrEmpty(value)) + { + // Never allow a blank or null string, go back to the default + _dateTimeFormat = ISO8601_DATETIME_FORMAT; + return; + } + + // Caution, no validation when you choose date time format other than ISO 8601 + // Take a look at the above links + _dateTimeFormat = value; + } + } + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// The prefix of the API key. + public virtual IDictionary ApiKeyPrefix + { + get { return _apiKeyPrefix; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKeyPrefix collection may not be null."); + } + _apiKeyPrefix = value; + } + } + + /// + /// Gets or sets the API key based on the authentication name. + /// + /// The API key. + public virtual IDictionary ApiKey + { + get { return _apiKey; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKey collection may not be null."); + } + _apiKey = value; + } + } + + #endregion Properties + + #region Methods + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + public void AddDefaultHeader(string key, string value) + { + DefaultHeader[key] = value; + } + + /// + /// Creates a new based on this instance. + /// + /// + public ApiClient CreateApiClient() + { + return new ApiClient(BasePath) { Configuration = this }; + } + + + /// + /// Returns a string with essential information for debugging. + /// + public static String ToDebugReport() + { + String report = "C# SDK (IO.Swagger) Debug Report:\n"; + report += " OS: " + System.Environment.OSVersion + "\n"; + report += " .NET Framework Version: " + System.Environment.Version + "\n"; + report += " Version of the API: 1.0.0\n"; + report += " SDK Package Version: 1.0.0\n"; + + return report; + } + + /// + /// Add Api Key Header. + /// + /// Api Key name. + /// Api Key value. + /// + public void AddApiKey(string key, string value) + { + ApiKey[key] = value; + } + + /// + /// Sets the API key prefix. + /// + /// Api Key name. + /// Api Key value. + public void AddApiKeyPrefix(string key, string value) + { + ApiKeyPrefix[key] = value; + } + + #endregion Methods + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/ExceptionFactory.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/ExceptionFactory.cs new file mode 100644 index 00000000000..0f16ee365e5 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/ExceptionFactory.cs @@ -0,0 +1,24 @@ +/* + * 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 + */ + + +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/SwaggerClientNet40/src/IO.Swagger/Client/GlobalConfiguration.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/GlobalConfiguration.cs new file mode 100644 index 00000000000..d8b196fc3e8 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/GlobalConfiguration.cs @@ -0,0 +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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + + +using System; +using System.Reflection; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; + +namespace IO.Swagger.Client +{ + /// + /// provides a compile-time extension point for globally configuring + /// API Clients. + /// + /// + /// A customized implementation via partial class may reside in another file and may + /// be excluded from automatic generation via a .swagger-codegen-ignore file. + /// + public partial class GlobalConfiguration : Configuration + { + + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/IApiAccessor.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/IApiAccessor.cs new file mode 100644 index 00000000000..20f9722af2a --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/IApiAccessor.cs @@ -0,0 +1,42 @@ +/* + * 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 + */ + + +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/SwaggerClientNet40/src/IO.Swagger/Client/IReadableConfiguration.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/IReadableConfiguration.cs new file mode 100644 index 00000000000..32e87d6bd9a --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/IReadableConfiguration.cs @@ -0,0 +1,94 @@ +/* + * 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 + */ + + +using System.Collections.Generic; + +namespace IO.Swagger.Client +{ + /// + /// Represents a readable-only configuration contract. + /// + public interface IReadableConfiguration + { + /// + /// Gets the access token. + /// + /// Access token. + string AccessToken { get; } + + /// + /// Gets the API key. + /// + /// API key. + IDictionary ApiKey { get; } + + /// + /// Gets the API key prefix. + /// + /// API key prefix. + IDictionary ApiKeyPrefix { get; } + + /// + /// Gets the base path. + /// + /// Base path. + string BasePath { get; } + + /// + /// Gets the date time format. + /// + /// Date time foramt. + string DateTimeFormat { get; } + + /// + /// Gets the default header. + /// + /// Default header. + IDictionary DefaultHeader { get; } + + /// + /// Gets the temp folder path. + /// + /// Temp folder path. + string TempFolderPath { get; } + + /// + /// Gets the HTTP connection timeout (in milliseconds) + /// + /// HTTP connection timeout. + int Timeout { get; } + + /// + /// Gets the user agent. + /// + /// User agent. + string UserAgent { get; } + + /// + /// Gets the username. + /// + /// Username. + string Username { get; } + + /// + /// Gets the password. + /// + /// Password. + string Password { get; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + string GetApiKeyWithPrefix(string apiKeyIdentifier); + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/JsonSubTypes.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/JsonSubTypes.cs new file mode 100644 index 00000000000..3a6da091b78 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/JsonSubTypes.cs @@ -0,0 +1,272 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace JsonSubTypes +{ + // Copied from project https://github.com/manuc66/JsonSubTypes + // https://raw.githubusercontent.com/manuc66/JsonSubTypes/07403192ea3f4959f6d42f5966ac56ceb0d6095b/JsonSubTypes/JsonSubtypes.cs + + public class JsonSubtypes : JsonConverter + { + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true)] + public class KnownSubTypeAttribute : Attribute + { + public Type SubType { get; private set; } + public object AssociatedValue { get; private set; } + + public KnownSubTypeAttribute(Type subType, object associatedValue) + { + SubType = subType; + AssociatedValue = associatedValue; + } + } + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true)] + public class KnownSubTypeWithPropertyAttribute : Attribute + { + public Type SubType { get; private set; } + public string PropertyName { get; private set; } + + public KnownSubTypeWithPropertyAttribute(Type subType, string propertyName) + { + SubType = subType; + PropertyName = propertyName; + } + } + + private readonly string _typeMappingPropertyName; + + private bool _isInsideRead; + private JsonReader _reader; + + public override bool CanRead + { + get + { + if (!_isInsideRead) + return true; + + return !string.IsNullOrEmpty(_reader.Path); + } + } + + public sealed override bool CanWrite + { + get { return false; } + } + + public JsonSubtypes() + { + } + + public JsonSubtypes(string typeMappingPropertyName) + { + _typeMappingPropertyName = typeMappingPropertyName; + } + + public override bool CanConvert(Type objectType) + { + return _typeMappingPropertyName != null; + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + throw new NotImplementedException(); + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.Comment) + reader.Read(); + + switch (reader.TokenType) + { + case JsonToken.Null: + return null; + case JsonToken.StartArray: + return ReadArray(reader, objectType, serializer); + case JsonToken.StartObject: + return ReadObject(reader, objectType, serializer); + default: + throw new Exception("Array: Unrecognized token: " + reader.TokenType); + } + } + + private IList ReadArray(JsonReader reader, Type targetType, JsonSerializer serializer) + { + var elementType = GetElementType(targetType); + + var list = CreateCompatibleList(targetType, elementType); + + while (reader.TokenType != JsonToken.EndArray && reader.Read()) + { + switch (reader.TokenType) + { + case JsonToken.Null: + list.Add(reader.Value); + break; + case JsonToken.Comment: + break; + case JsonToken.StartObject: + list.Add(ReadObject(reader, elementType, serializer)); + break; + case JsonToken.EndArray: + break; + default: + throw new Exception("Array: Unrecognized token: " + reader.TokenType); + } + } + if (targetType.IsArray) + { + var array = Array.CreateInstance(targetType.GetElementType(), list.Count); + list.CopyTo(array, 0); + list = array; + } + return list; + } + + private static IList CreateCompatibleList(Type targetContainerType, Type elementType) + { + IList list; + if (targetContainerType.IsArray || targetContainerType.GetTypeInfo().IsAbstract) + { + list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(elementType)); + } + else + { + list = (IList)Activator.CreateInstance(targetContainerType); + } + return list; + } + + private static Type GetElementType(Type arrayOrGenericContainer) + { + Type elementType; + if (arrayOrGenericContainer.IsArray) + { + elementType = arrayOrGenericContainer.GetElementType(); + } + else + { + elementType = arrayOrGenericContainer.GenericTypeArguments[0]; + } + return elementType; + } + + private object ReadObject(JsonReader reader, Type objectType, JsonSerializer serializer) + { + var jObject = JObject.Load(reader); + + var targetType = GetType(jObject, objectType) ?? objectType; + + return _ReadJson(CreateAnotherReader(jObject, reader), targetType, null, serializer); + } + + private static JsonReader CreateAnotherReader(JObject jObject, JsonReader reader) + { + var jObjectReader = jObject.CreateReader(); + jObjectReader.Culture = reader.Culture; + jObjectReader.CloseInput = reader.CloseInput; + jObjectReader.SupportMultipleContent = reader.SupportMultipleContent; + jObjectReader.DateTimeZoneHandling = reader.DateTimeZoneHandling; + jObjectReader.FloatParseHandling = reader.FloatParseHandling; + jObjectReader.DateFormatString = reader.DateFormatString; + jObjectReader.DateParseHandling = reader.DateParseHandling; + return jObjectReader; + } + + public Type GetType(JObject jObject, Type parentType) + { + if (_typeMappingPropertyName == null) + { + return GetTypeByPropertyPresence(jObject, parentType); + } + return GetTypeFromDiscriminatorValue(jObject, parentType); + } + + private static Type GetTypeByPropertyPresence(JObject jObject, Type parentType) + { + foreach (var type in parentType.GetTypeInfo().GetCustomAttributes()) + { + JToken ignore; + if (jObject.TryGetValue(type.PropertyName, out ignore)) + { + return type.SubType; + } + } + return null; + } + + private Type GetTypeFromDiscriminatorValue(JObject jObject, Type parentType) + { + JToken jToken; + if (!jObject.TryGetValue(_typeMappingPropertyName, out jToken)) return null; + + var discriminatorValue = jToken.ToObject(); + if (discriminatorValue == null) return null; + + var typeMapping = GetSubTypeMapping(parentType); + if (typeMapping.Any()) + { + return GetTypeFromMapping(typeMapping, discriminatorValue); + } + return GetTypeByName(discriminatorValue as string, parentType); + } + + private static Type GetTypeByName(string typeName, Type parentType) + { + if (typeName == null) + return null; + + var insideAssembly = parentType.GetTypeInfo().Assembly; + + var typeByName = insideAssembly.GetType(typeName); + if (typeByName == null) + { + var searchLocation = parentType.FullName.Substring(0, parentType.FullName.Length - parentType.Name.Length); + typeByName = insideAssembly.GetType(searchLocation + typeName, false, true); + } + return typeByName; + } + + private static Type GetTypeFromMapping(IReadOnlyDictionary typeMapping, object discriminatorValue) + { + var targetlookupValueType = typeMapping.First().Key.GetType(); + var lookupValue = ConvertJsonValueToType(discriminatorValue, targetlookupValueType); + + Type targetType; + return typeMapping.TryGetValue(lookupValue, out targetType) ? targetType : null; + } + + private static Dictionary GetSubTypeMapping(Type type) + { + return type.GetTypeInfo().GetCustomAttributes().ToDictionary(x => x.AssociatedValue, x => x.SubType); + } + + private static object ConvertJsonValueToType(object objectType, Type targetlookupValueType) + { + if (targetlookupValueType.GetTypeInfo().IsEnum) + return Enum.ToObject(targetlookupValueType, objectType); + + return Convert.ChangeType(objectType, targetlookupValueType); + } + + protected object _ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + _reader = reader; + _isInsideRead = true; + try + { + return serializer.Deserialize(reader, objectType); + } + finally + { + _isInsideRead = false; + } + } + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/SwaggerDateConverter.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/SwaggerDateConverter.cs new file mode 100644 index 00000000000..82b825423dc --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/SwaggerDateConverter.cs @@ -0,0 +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 + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +using Newtonsoft.Json.Converters; + +namespace IO.Swagger.Client +{ + /// + /// Formatter for 'date' swagger formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types + /// + public class SwaggerDateConverter : IsoDateTimeConverter + { + /// + /// Initializes a new instance of the class. + /// + public SwaggerDateConverter() + { + // full-date = date-fullyear "-" date-month "-" date-mday + DateTimeFormat = "yyyy-MM-dd"; + } + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/IO.Swagger.csproj new file mode 100644 index 00000000000..fe43f0d9e52 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/IO.Swagger.csproj @@ -0,0 +1,72 @@ + + + + + + Debug + AnyCPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C} + Library + Properties + IO.Swagger + IO.Swagger + v4.0 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + $(SolutionDir)\packages\Newtonsoft.Json.10.0.3\lib\net40\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.10.0.3\lib\net40\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.10.0.3\lib\net40\Newtonsoft.Json.dll + ..\..\vendor\Newtonsoft.Json.10.0.3\lib\net40\Newtonsoft.Json.dll + + + $(SolutionDir)\packages\RestSharp.105.1.0\lib\net40\RestSharp.dll + ..\packages\RestSharp.105.1.0\lib\net40\RestSharp.dll + ..\..\packages\RestSharp.105.1.0\lib\net40\RestSharp.dll + ..\..\vendor\RestSharp.105.1.0\lib\net40\RestSharp.dll + + + + + + + + + + + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/IO.Swagger.nuspec b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/IO.Swagger.nuspec new file mode 100644 index 00000000000..1035d5d81e4 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/IO.Swagger.nuspec @@ -0,0 +1,41 @@ + + + + + $id$ + Swagger Library + + + $version$ + + + $author$ + + + $author$ + false + false + + + A library generated from a Swagger doc + http://swagger.io/terms/ + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/AdditionalPropertiesClass.cs new file mode 100644 index 00000000000..ad54e625864 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/AdditionalPropertiesClass.cs @@ -0,0 +1,140 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// AdditionalPropertiesClass + /// + [DataContract] + public partial class AdditionalPropertiesClass : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// MapProperty. + /// MapOfMapProperty. + public AdditionalPropertiesClass(Dictionary MapProperty = default(Dictionary), Dictionary> MapOfMapProperty = default(Dictionary>)) + { + 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 input) + { + return this.Equals(input as AdditionalPropertiesClass); + } + + /// + /// Returns true if AdditionalPropertiesClass instances are equal + /// + /// Instance of AdditionalPropertiesClass to be compared + /// Boolean + public bool Equals(AdditionalPropertiesClass input) + { + if (input == null) + return false; + + return + ( + this.MapProperty == input.MapProperty || + this.MapProperty != null && + this.MapProperty.SequenceEqual(input.MapProperty) + ) && + ( + this.MapOfMapProperty == input.MapOfMapProperty || + this.MapOfMapProperty != null && + this.MapOfMapProperty.SequenceEqual(input.MapOfMapProperty) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.MapProperty != null) + hashCode = hashCode * 59 + this.MapProperty.GetHashCode(); + if (this.MapOfMapProperty != null) + hashCode = hashCode * 59 + this.MapOfMapProperty.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Animal.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Animal.cs new file mode 100644 index 00000000000..9b44060fb85 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Animal.cs @@ -0,0 +1,175 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// Animal + /// + [DataContract] + [JsonConverter(typeof(JsonSubtypes), "className")] + [JsonSubtypes.KnownSubType(typeof(Dog), "Dog")] + [JsonSubtypes.KnownSubType(typeof(Cat), "Cat")] + public partial class Animal : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Animal() { } + /// + /// Initializes a new instance of the class. + /// + /// ClassName (required). + /// Color (default to "red"). + public Animal(string ClassName = default(string), string Color = "red") + { + // to ensure "ClassName" is required (not null) + if (ClassName == null) + { + throw new InvalidDataException("ClassName is a required property for Animal and cannot be null"); + } + else + { + this.ClassName = ClassName; + } + // use default value if no "Color" provided + if (Color == null) + { + this.Color = "red"; + } + else + { + this.Color = Color; + } + } + + /// + /// Gets or Sets ClassName + /// + [DataMember(Name="className", EmitDefaultValue=false)] + public string ClassName { get; set; } + + /// + /// Gets or Sets Color + /// + [DataMember(Name="color", EmitDefaultValue=false)] + public string Color { 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 Animal {\n"); + sb.Append(" ClassName: ").Append(ClassName).Append("\n"); + sb.Append(" Color: ").Append(Color).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as Animal); + } + + /// + /// Returns true if Animal instances are equal + /// + /// Instance of Animal to be compared + /// Boolean + public bool Equals(Animal input) + { + if (input == null) + return false; + + return + ( + this.ClassName == input.ClassName || + (this.ClassName != null && + this.ClassName.Equals(input.ClassName)) + ) && + ( + this.Color == input.Color || + (this.Color != null && + this.Color.Equals(input.Color)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ClassName != null) + hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + if (this.Color != null) + hashCode = hashCode * 59 + this.Color.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/AnimalFarm.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/AnimalFarm.cs new file mode 100644 index 00000000000..50767b53ec2 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/AnimalFarm.cs @@ -0,0 +1,110 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// AnimalFarm + /// + [DataContract] + public partial class AnimalFarm : List, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + public AnimalFarm() : base() + { + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class AnimalFarm {\n"); + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).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 input) + { + return this.Equals(input as AnimalFarm); + } + + /// + /// Returns true if AnimalFarm instances are equal + /// + /// Instance of AnimalFarm to be compared + /// Boolean + public bool Equals(AnimalFarm input) + { + if (input == null) + return false; + + return base.Equals(input); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = base.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ApiResponse.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ApiResponse.cs new file mode 100644 index 00000000000..fc654b07f27 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ApiResponse.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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// ApiResponse + /// + [DataContract] + public partial class ApiResponse : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Code. + /// Type. + /// Message. + public ApiResponse(int? Code = default(int?), string Type = default(string), string Message = default(string)) + { + this.Code = Code; + this.Type = Type; + this.Message = Message; + } + + /// + /// Gets or Sets Code + /// + [DataMember(Name="code", EmitDefaultValue=false)] + public int? Code { get; set; } + + /// + /// Gets or Sets Type + /// + [DataMember(Name="type", EmitDefaultValue=false)] + public string Type { get; set; } + + /// + /// Gets or Sets Message + /// + [DataMember(Name="message", EmitDefaultValue=false)] + public string Message { 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 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("}\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 input) + { + return this.Equals(input as ApiResponse); + } + + /// + /// Returns true if ApiResponse instances are equal + /// + /// Instance of ApiResponse to be compared + /// Boolean + public bool Equals(ApiResponse input) + { + if (input == null) + return false; + + return + ( + this.Code == input.Code || + (this.Code != null && + this.Code.Equals(input.Code)) + ) && + ( + this.Type == input.Type || + (this.Type != null && + this.Type.Equals(input.Type)) + ) && + ( + this.Message == input.Message || + (this.Message != null && + this.Message.Equals(input.Message)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Code != null) + hashCode = hashCode * 59 + this.Code.GetHashCode(); + if (this.Type != null) + hashCode = hashCode * 59 + this.Type.GetHashCode(); + if (this.Message != null) + hashCode = hashCode * 59 + this.Message.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs new file mode 100644 index 00000000000..048483cdf48 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs @@ -0,0 +1,124 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// ArrayOfArrayOfNumberOnly + /// + [DataContract] + public partial class ArrayOfArrayOfNumberOnly : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// ArrayArrayNumber. + public ArrayOfArrayOfNumberOnly(List> ArrayArrayNumber = default(List>)) + { + this.ArrayArrayNumber = ArrayArrayNumber; + } + + /// + /// Gets or Sets ArrayArrayNumber + /// + [DataMember(Name="ArrayArrayNumber", EmitDefaultValue=false)] + public List> ArrayArrayNumber { 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 ArrayOfArrayOfNumberOnly {\n"); + sb.Append(" ArrayArrayNumber: ").Append(ArrayArrayNumber).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 input) + { + return this.Equals(input as ArrayOfArrayOfNumberOnly); + } + + /// + /// Returns true if ArrayOfArrayOfNumberOnly instances are equal + /// + /// Instance of ArrayOfArrayOfNumberOnly to be compared + /// Boolean + public bool Equals(ArrayOfArrayOfNumberOnly input) + { + if (input == null) + return false; + + return + ( + this.ArrayArrayNumber == input.ArrayArrayNumber || + this.ArrayArrayNumber != null && + this.ArrayArrayNumber.SequenceEqual(input.ArrayArrayNumber) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ArrayArrayNumber != null) + hashCode = hashCode * 59 + this.ArrayArrayNumber.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ArrayOfNumberOnly.cs new file mode 100644 index 00000000000..ccff9ee3f0e --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ArrayOfNumberOnly.cs @@ -0,0 +1,124 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// ArrayOfNumberOnly + /// + [DataContract] + public partial class ArrayOfNumberOnly : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// ArrayNumber. + public ArrayOfNumberOnly(List ArrayNumber = default(List)) + { + this.ArrayNumber = ArrayNumber; + } + + /// + /// Gets or Sets ArrayNumber + /// + [DataMember(Name="ArrayNumber", EmitDefaultValue=false)] + public List ArrayNumber { 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 ArrayOfNumberOnly {\n"); + sb.Append(" ArrayNumber: ").Append(ArrayNumber).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 input) + { + return this.Equals(input as ArrayOfNumberOnly); + } + + /// + /// Returns true if ArrayOfNumberOnly instances are equal + /// + /// Instance of ArrayOfNumberOnly to be compared + /// Boolean + public bool Equals(ArrayOfNumberOnly input) + { + if (input == null) + return false; + + return + ( + this.ArrayNumber == input.ArrayNumber || + this.ArrayNumber != null && + this.ArrayNumber.SequenceEqual(input.ArrayNumber) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ArrayNumber != null) + hashCode = hashCode * 59 + this.ArrayNumber.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ArrayTest.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ArrayTest.cs new file mode 100644 index 00000000000..66cca739d5e --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// ArrayTest + /// + [DataContract] + public partial class ArrayTest : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// ArrayOfString. + /// ArrayArrayOfInteger. + /// ArrayArrayOfModel. + public ArrayTest(List ArrayOfString = default(List), List> ArrayArrayOfInteger = default(List>), List> ArrayArrayOfModel = default(List>)) + { + 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 input) + { + return this.Equals(input as ArrayTest); + } + + /// + /// Returns true if ArrayTest instances are equal + /// + /// Instance of ArrayTest to be compared + /// Boolean + public bool Equals(ArrayTest input) + { + if (input == null) + return false; + + return + ( + this.ArrayOfString == input.ArrayOfString || + this.ArrayOfString != null && + this.ArrayOfString.SequenceEqual(input.ArrayOfString) + ) && + ( + this.ArrayArrayOfInteger == input.ArrayArrayOfInteger || + this.ArrayArrayOfInteger != null && + this.ArrayArrayOfInteger.SequenceEqual(input.ArrayArrayOfInteger) + ) && + ( + this.ArrayArrayOfModel == input.ArrayArrayOfModel || + this.ArrayArrayOfModel != null && + this.ArrayArrayOfModel.SequenceEqual(input.ArrayArrayOfModel) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ArrayOfString != null) + hashCode = hashCode * 59 + this.ArrayOfString.GetHashCode(); + if (this.ArrayArrayOfInteger != null) + hashCode = hashCode * 59 + this.ArrayArrayOfInteger.GetHashCode(); + if (this.ArrayArrayOfModel != null) + hashCode = hashCode * 59 + this.ArrayArrayOfModel.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Capitalization.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Capitalization.cs new file mode 100644 index 00000000000..b306023afd0 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Capitalization.cs @@ -0,0 +1,205 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// Capitalization + /// + [DataContract] + public partial class Capitalization : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// SmallCamel. + /// CapitalCamel. + /// SmallSnake. + /// CapitalSnake. + /// SCAETHFlowPoints. + /// Name of the pet . + public Capitalization(string SmallCamel = default(string), string CapitalCamel = default(string), string SmallSnake = default(string), string CapitalSnake = default(string), string SCAETHFlowPoints = default(string), string ATT_NAME = default(string)) + { + this.SmallCamel = SmallCamel; + this.CapitalCamel = CapitalCamel; + this.SmallSnake = SmallSnake; + this.CapitalSnake = CapitalSnake; + this.SCAETHFlowPoints = SCAETHFlowPoints; + this.ATT_NAME = ATT_NAME; + } + + /// + /// Gets or Sets SmallCamel + /// + [DataMember(Name="smallCamel", EmitDefaultValue=false)] + public string SmallCamel { get; set; } + + /// + /// Gets or Sets CapitalCamel + /// + [DataMember(Name="CapitalCamel", EmitDefaultValue=false)] + public string CapitalCamel { get; set; } + + /// + /// Gets or Sets SmallSnake + /// + [DataMember(Name="small_Snake", EmitDefaultValue=false)] + public string SmallSnake { get; set; } + + /// + /// Gets or Sets CapitalSnake + /// + [DataMember(Name="Capital_Snake", EmitDefaultValue=false)] + public string CapitalSnake { get; set; } + + /// + /// Gets or Sets SCAETHFlowPoints + /// + [DataMember(Name="SCA_ETH_Flow_Points", EmitDefaultValue=false)] + public string SCAETHFlowPoints { get; set; } + + /// + /// Name of the pet + /// + /// Name of the pet + [DataMember(Name="ATT_NAME", EmitDefaultValue=false)] + public string ATT_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 Capitalization {\n"); + sb.Append(" SmallCamel: ").Append(SmallCamel).Append("\n"); + sb.Append(" CapitalCamel: ").Append(CapitalCamel).Append("\n"); + sb.Append(" SmallSnake: ").Append(SmallSnake).Append("\n"); + sb.Append(" CapitalSnake: ").Append(CapitalSnake).Append("\n"); + sb.Append(" SCAETHFlowPoints: ").Append(SCAETHFlowPoints).Append("\n"); + sb.Append(" ATT_NAME: ").Append(ATT_NAME).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 input) + { + return this.Equals(input as Capitalization); + } + + /// + /// Returns true if Capitalization instances are equal + /// + /// Instance of Capitalization to be compared + /// Boolean + public bool Equals(Capitalization input) + { + if (input == null) + return false; + + return + ( + this.SmallCamel == input.SmallCamel || + (this.SmallCamel != null && + this.SmallCamel.Equals(input.SmallCamel)) + ) && + ( + this.CapitalCamel == input.CapitalCamel || + (this.CapitalCamel != null && + this.CapitalCamel.Equals(input.CapitalCamel)) + ) && + ( + this.SmallSnake == input.SmallSnake || + (this.SmallSnake != null && + this.SmallSnake.Equals(input.SmallSnake)) + ) && + ( + this.CapitalSnake == input.CapitalSnake || + (this.CapitalSnake != null && + this.CapitalSnake.Equals(input.CapitalSnake)) + ) && + ( + this.SCAETHFlowPoints == input.SCAETHFlowPoints || + (this.SCAETHFlowPoints != null && + this.SCAETHFlowPoints.Equals(input.SCAETHFlowPoints)) + ) && + ( + this.ATT_NAME == input.ATT_NAME || + (this.ATT_NAME != null && + this.ATT_NAME.Equals(input.ATT_NAME)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.SmallCamel != null) + hashCode = hashCode * 59 + this.SmallCamel.GetHashCode(); + if (this.CapitalCamel != null) + hashCode = hashCode * 59 + this.CapitalCamel.GetHashCode(); + if (this.SmallSnake != null) + hashCode = hashCode * 59 + this.SmallSnake.GetHashCode(); + if (this.CapitalSnake != null) + hashCode = hashCode * 59 + this.CapitalSnake.GetHashCode(); + if (this.SCAETHFlowPoints != null) + hashCode = hashCode * 59 + this.SCAETHFlowPoints.GetHashCode(); + if (this.ATT_NAME != null) + hashCode = hashCode * 59 + this.ATT_NAME.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Cat.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Cat.cs new file mode 100644 index 00000000000..b012af5de70 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Cat.cs @@ -0,0 +1,131 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// Cat + /// + [DataContract] + public partial class Cat : Animal, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Cat() { } + /// + /// Initializes a new instance of the class. + /// + /// Declawed. + public Cat(bool? Declawed = default(bool?), string ClassName = "Cat", string Color = "red") : base(ClassName, Color) + { + this.Declawed = Declawed; + } + + /// + /// Gets or Sets Declawed + /// + [DataMember(Name="declawed", EmitDefaultValue=false)] + public bool? Declawed { 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 Cat {\n"); + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); + sb.Append(" Declawed: ").Append(Declawed).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as Cat); + } + + /// + /// Returns true if Cat instances are equal + /// + /// Instance of Cat to be compared + /// Boolean + public bool Equals(Cat input) + { + if (input == null) + return false; + + return base.Equals(input) && + ( + this.Declawed == input.Declawed || + (this.Declawed != null && + this.Declawed.Equals(input.Declawed)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = base.GetHashCode(); + if (this.Declawed != null) + hashCode = hashCode * 59 + this.Declawed.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + foreach(var x in BaseValidate(validationContext)) yield return x; + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Category.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Category.cs new file mode 100644 index 00000000000..c2a3462cf99 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Category.cs @@ -0,0 +1,140 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// Category + /// + [DataContract] + public partial class Category : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Id. + /// Name. + public Category(long? Id = default(long?), string Name = default(string)) + { + this.Id = Id; + this.Name = Name; + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name="id", EmitDefaultValue=false)] + public long? Id { 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 Category {\n"); + sb.Append(" Id: ").Append(Id).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 string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as Category); + } + + /// + /// Returns true if Category instances are equal + /// + /// Instance of Category to be compared + /// Boolean + public bool Equals(Category input) + { + if (input == null) + return false; + + return + ( + this.Id == input.Id || + (this.Id != null && + this.Id.Equals(input.Id)) + ) && + ( + this.Name == input.Name || + (this.Name != null && + this.Name.Equals(input.Name)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Id != null) + hashCode = hashCode * 59 + this.Id.GetHashCode(); + if (this.Name != null) + hashCode = hashCode * 59 + this.Name.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ClassModel.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ClassModel.cs new file mode 100644 index 00000000000..4d00dbef97b --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ClassModel.cs @@ -0,0 +1,124 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// Model for testing model with \"_class\" property + /// + [DataContract] + public partial class ClassModel : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _Class. + public ClassModel(string _Class = default(string)) + { + this._Class = _Class; + } + + /// + /// Gets or Sets _Class + /// + [DataMember(Name="_class", EmitDefaultValue=false)] + public string _Class { 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 ClassModel {\n"); + sb.Append(" _Class: ").Append(_Class).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 input) + { + return this.Equals(input as ClassModel); + } + + /// + /// Returns true if ClassModel instances are equal + /// + /// Instance of ClassModel to be compared + /// Boolean + public bool Equals(ClassModel input) + { + if (input == null) + return false; + + return + ( + this._Class == input._Class || + (this._Class != null && + this._Class.Equals(input._Class)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this._Class != null) + hashCode = hashCode * 59 + this._Class.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Dog.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Dog.cs new file mode 100644 index 00000000000..f92b01a5bfb --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Dog.cs @@ -0,0 +1,131 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// Dog + /// + [DataContract] + public partial class Dog : Animal, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Dog() { } + /// + /// Initializes a new instance of the class. + /// + /// Breed. + public Dog(string Breed = default(string), string ClassName = "Dog", string Color = "red") : base(ClassName, Color) + { + this.Breed = Breed; + } + + /// + /// Gets or Sets Breed + /// + [DataMember(Name="breed", EmitDefaultValue=false)] + public string Breed { 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 Dog {\n"); + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); + sb.Append(" Breed: ").Append(Breed).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as Dog); + } + + /// + /// Returns true if Dog instances are equal + /// + /// Instance of Dog to be compared + /// Boolean + public bool Equals(Dog input) + { + if (input == null) + return false; + + return base.Equals(input) && + ( + this.Breed == input.Breed || + (this.Breed != null && + this.Breed.Equals(input.Breed)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = base.GetHashCode(); + if (this.Breed != null) + hashCode = hashCode * 59 + this.Breed.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + foreach(var x in BaseValidate(validationContext)) yield return x; + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/EnumArrays.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/EnumArrays.cs new file mode 100644 index 00000000000..64f705748f2 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/EnumArrays.cs @@ -0,0 +1,181 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// EnumArrays + /// + [DataContract] + public partial class EnumArrays : IEquatable, IValidatableObject + { + /// + /// Gets or Sets JustSymbol + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum JustSymbolEnum + { + + /// + /// Enum GreaterThanOrEqualTo for ">=" + /// + [EnumMember(Value = ">=")] + GreaterThanOrEqualTo, + + /// + /// Enum Dollar for "$" + /// + [EnumMember(Value = "$")] + Dollar + } + + + /// + /// Gets or Sets ArrayEnum + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum ArrayEnumEnum + { + + /// + /// Enum Fish for "fish" + /// + [EnumMember(Value = "fish")] + Fish, + + /// + /// Enum Crab for "crab" + /// + [EnumMember(Value = "crab")] + Crab + } + + /// + /// Gets or Sets JustSymbol + /// + [DataMember(Name="just_symbol", EmitDefaultValue=false)] + public JustSymbolEnum? JustSymbol { get; set; } + /// + /// Gets or Sets ArrayEnum + /// + [DataMember(Name="array_enum", EmitDefaultValue=false)] + public List ArrayEnum { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// JustSymbol. + /// ArrayEnum. + public EnumArrays(JustSymbolEnum? JustSymbol = default(JustSymbolEnum?), List ArrayEnum = default(List)) + { + this.JustSymbol = JustSymbol; + this.ArrayEnum = ArrayEnum; + } + + + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class EnumArrays {\n"); + sb.Append(" JustSymbol: ").Append(JustSymbol).Append("\n"); + sb.Append(" ArrayEnum: ").Append(ArrayEnum).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 input) + { + return this.Equals(input as EnumArrays); + } + + /// + /// Returns true if EnumArrays instances are equal + /// + /// Instance of EnumArrays to be compared + /// Boolean + public bool Equals(EnumArrays input) + { + if (input == null) + return false; + + return + ( + this.JustSymbol == input.JustSymbol || + (this.JustSymbol != null && + this.JustSymbol.Equals(input.JustSymbol)) + ) && + ( + this.ArrayEnum == input.ArrayEnum || + this.ArrayEnum != null && + this.ArrayEnum.SequenceEqual(input.ArrayEnum) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.JustSymbol != null) + hashCode = hashCode * 59 + this.JustSymbol.GetHashCode(); + if (this.ArrayEnum != null) + hashCode = hashCode * 59 + this.ArrayEnum.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/EnumClass.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/EnumClass.cs new file mode 100644 index 00000000000..77fc0a8e299 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/EnumClass.cs @@ -0,0 +1,53 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// Defines 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/SwaggerClientNet40/src/IO.Swagger/Model/EnumTest.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/EnumTest.cs new file mode 100644 index 00000000000..ebcfe3b0e46 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/EnumTest.cs @@ -0,0 +1,238 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// EnumTest + /// + [DataContract] + public partial class EnumTest : IEquatable, IValidatableObject + { + /// + /// 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, + + /// + /// Enum Empty for "" + /// + [EnumMember(Value = "")] + Empty + } + + /// + /// 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. + /// OuterEnum. + public EnumTest(EnumStringEnum? EnumString = default(EnumStringEnum?), EnumIntegerEnum? EnumInteger = default(EnumIntegerEnum?), EnumNumberEnum? EnumNumber = default(EnumNumberEnum?), OuterEnum OuterEnum = default(OuterEnum)) + { + this.EnumString = EnumString; + this.EnumInteger = EnumInteger; + this.EnumNumber = EnumNumber; + this.OuterEnum = OuterEnum; + } + + + + + /// + /// Gets or Sets OuterEnum + /// + [DataMember(Name="outerEnum", EmitDefaultValue=false)] + public OuterEnum OuterEnum { 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 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(" OuterEnum: ").Append(OuterEnum).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 input) + { + return this.Equals(input as EnumTest); + } + + /// + /// Returns true if EnumTest instances are equal + /// + /// Instance of EnumTest to be compared + /// Boolean + public bool Equals(EnumTest input) + { + if (input == null) + return false; + + return + ( + this.EnumString == input.EnumString || + (this.EnumString != null && + this.EnumString.Equals(input.EnumString)) + ) && + ( + this.EnumInteger == input.EnumInteger || + (this.EnumInteger != null && + this.EnumInteger.Equals(input.EnumInteger)) + ) && + ( + this.EnumNumber == input.EnumNumber || + (this.EnumNumber != null && + this.EnumNumber.Equals(input.EnumNumber)) + ) && + ( + this.OuterEnum == input.OuterEnum || + (this.OuterEnum != null && + this.OuterEnum.Equals(input.OuterEnum)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.EnumString != null) + hashCode = hashCode * 59 + this.EnumString.GetHashCode(); + if (this.EnumInteger != null) + hashCode = hashCode * 59 + this.EnumInteger.GetHashCode(); + if (this.EnumNumber != null) + hashCode = hashCode * 59 + this.EnumNumber.GetHashCode(); + if (this.OuterEnum != null) + hashCode = hashCode * 59 + this.OuterEnum.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/FormatTest.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/FormatTest.cs new file mode 100644 index 00000000000..f651fbf5d5e --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/FormatTest.cs @@ -0,0 +1,433 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// FormatTest + /// + [DataContract] + public partial class FormatTest : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected FormatTest() { } + /// + /// Initializes a new instance of the class. + /// + /// Integer. + /// Int32. + /// Int64. + /// Number (required). + /// _Float. + /// _Double. + /// _String. + /// _Byte (required). + /// Binary. + /// Date (required). + /// DateTime. + /// Uuid. + /// Password (required). + public FormatTest(int? Integer = default(int?), int? Int32 = default(int?), long? Int64 = default(long?), decimal? Number = default(decimal?), float? _Float = default(float?), double? _Double = default(double?), string _String = default(string), byte[] _Byte = default(byte[]), byte[] Binary = default(byte[]), DateTime? Date = default(DateTime?), DateTime? DateTime = default(DateTime?), Guid? Uuid = default(Guid?), string Password = default(string)) + { + // to ensure "Number" is required (not null) + if (Number == null) + { + throw new InvalidDataException("Number is a required property for FormatTest and cannot be null"); + } + else + { + this.Number = Number; + } + // to ensure "_Byte" is required (not null) + if (_Byte == null) + { + throw new InvalidDataException("_Byte is a required property for FormatTest and cannot be null"); + } + else + { + this._Byte = _Byte; + } + // to ensure "Date" is required (not null) + if (Date == null) + { + throw new InvalidDataException("Date is a required property for FormatTest and cannot be null"); + } + else + { + this.Date = Date; + } + // to ensure "Password" is required (not null) + if (Password == null) + { + throw new InvalidDataException("Password is a required property for FormatTest and cannot be null"); + } + else + { + 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; + } + + /// + /// Gets or Sets Integer + /// + [DataMember(Name="integer", EmitDefaultValue=false)] + public int? Integer { get; set; } + + /// + /// Gets or Sets Int32 + /// + [DataMember(Name="int32", EmitDefaultValue=false)] + public int? Int32 { get; set; } + + /// + /// Gets or Sets Int64 + /// + [DataMember(Name="int64", EmitDefaultValue=false)] + public long? Int64 { get; set; } + + /// + /// Gets or Sets Number + /// + [DataMember(Name="number", EmitDefaultValue=false)] + public decimal? Number { get; set; } + + /// + /// Gets or Sets _Float + /// + [DataMember(Name="float", EmitDefaultValue=false)] + public float? _Float { get; set; } + + /// + /// Gets or Sets _Double + /// + [DataMember(Name="double", EmitDefaultValue=false)] + public double? _Double { get; set; } + + /// + /// Gets or Sets _String + /// + [DataMember(Name="string", EmitDefaultValue=false)] + public string _String { get; set; } + + /// + /// Gets or Sets _Byte + /// + [DataMember(Name="byte", EmitDefaultValue=false)] + public byte[] _Byte { get; set; } + + /// + /// Gets or Sets Binary + /// + [DataMember(Name="binary", EmitDefaultValue=false)] + public byte[] Binary { get; set; } + + /// + /// Gets or Sets Date + /// + [DataMember(Name="date", EmitDefaultValue=false)] + [JsonConverter(typeof(SwaggerDateConverter))] + public DateTime? Date { get; set; } + + /// + /// Gets or Sets DateTime + /// + [DataMember(Name="dateTime", EmitDefaultValue=false)] + public DateTime? DateTime { get; set; } + + /// + /// Gets or Sets Uuid + /// + [DataMember(Name="uuid", EmitDefaultValue=false)] + public Guid? Uuid { get; set; } + + /// + /// Gets or Sets Password + /// + [DataMember(Name="password", EmitDefaultValue=false)] + public string Password { 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 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("}\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 input) + { + return this.Equals(input as FormatTest); + } + + /// + /// Returns true if FormatTest instances are equal + /// + /// Instance of FormatTest to be compared + /// Boolean + public bool Equals(FormatTest input) + { + if (input == null) + return false; + + return + ( + this.Integer == input.Integer || + (this.Integer != null && + this.Integer.Equals(input.Integer)) + ) && + ( + this.Int32 == input.Int32 || + (this.Int32 != null && + this.Int32.Equals(input.Int32)) + ) && + ( + this.Int64 == input.Int64 || + (this.Int64 != null && + this.Int64.Equals(input.Int64)) + ) && + ( + this.Number == input.Number || + (this.Number != null && + this.Number.Equals(input.Number)) + ) && + ( + this._Float == input._Float || + (this._Float != null && + this._Float.Equals(input._Float)) + ) && + ( + this._Double == input._Double || + (this._Double != null && + this._Double.Equals(input._Double)) + ) && + ( + this._String == input._String || + (this._String != null && + this._String.Equals(input._String)) + ) && + ( + this._Byte == input._Byte || + (this._Byte != null && + this._Byte.Equals(input._Byte)) + ) && + ( + this.Binary == input.Binary || + (this.Binary != null && + this.Binary.Equals(input.Binary)) + ) && + ( + this.Date == input.Date || + (this.Date != null && + this.Date.Equals(input.Date)) + ) && + ( + this.DateTime == input.DateTime || + (this.DateTime != null && + this.DateTime.Equals(input.DateTime)) + ) && + ( + this.Uuid == input.Uuid || + (this.Uuid != null && + this.Uuid.Equals(input.Uuid)) + ) && + ( + this.Password == input.Password || + (this.Password != null && + this.Password.Equals(input.Password)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Integer != null) + hashCode = hashCode * 59 + this.Integer.GetHashCode(); + if (this.Int32 != null) + hashCode = hashCode * 59 + this.Int32.GetHashCode(); + if (this.Int64 != null) + hashCode = hashCode * 59 + this.Int64.GetHashCode(); + if (this.Number != null) + hashCode = hashCode * 59 + this.Number.GetHashCode(); + if (this._Float != null) + hashCode = hashCode * 59 + this._Float.GetHashCode(); + if (this._Double != null) + hashCode = hashCode * 59 + this._Double.GetHashCode(); + if (this._String != null) + hashCode = hashCode * 59 + this._String.GetHashCode(); + if (this._Byte != null) + hashCode = hashCode * 59 + this._Byte.GetHashCode(); + if (this.Binary != null) + hashCode = hashCode * 59 + this.Binary.GetHashCode(); + if (this.Date != null) + hashCode = hashCode * 59 + this.Date.GetHashCode(); + if (this.DateTime != null) + hashCode = hashCode * 59 + this.DateTime.GetHashCode(); + if (this.Uuid != null) + hashCode = hashCode * 59 + this.Uuid.GetHashCode(); + if (this.Password != null) + hashCode = hashCode * 59 + this.Password.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Integer (int?) maximum + if(this.Integer > (int?)100) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); + } + + // Integer (int?) minimum + if(this.Integer < (int?)10) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); + } + + // Int32 (int?) maximum + if(this.Int32 > (int?)200) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); + } + + // Int32 (int?) minimum + if(this.Int32 < (int?)20) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); + } + + // Number (decimal?) maximum + if(this.Number > (decimal?)543.2) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); + } + + // Number (decimal?) minimum + if(this.Number < (decimal?)32.1) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); + } + + // _Float (float?) maximum + if(this._Float > (float?)987.6) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for _Float, must be a value less than or equal to 987.6.", new [] { "_Float" }); + } + + // _Float (float?) minimum + if(this._Float < (float?)54.3) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for _Float, must be a value greater than or equal to 54.3.", new [] { "_Float" }); + } + + // _Double (double?) maximum + if(this._Double > (double?)123.4) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for _Double, must be a value less than or equal to 123.4.", new [] { "_Double" }); + } + + // _Double (double?) minimum + if(this._Double < (double?)67.8) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for _Double, must be a value greater than or equal to 67.8.", new [] { "_Double" }); + } + + // _String (string) pattern + Regex regex_String = new Regex(@"[a-z]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + if (false == regex_String.Match(this._String).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for _String, must match a pattern of " + regex_String, new [] { "_String" }); + } + + // Password (string) maxLength + if(this.Password != null && this.Password.Length > 64) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); + } + + // Password (string) minLength + if(this.Password != null && this.Password.Length < 10) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); + } + + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/HasOnlyReadOnly.cs new file mode 100644 index 00000000000..8c15b451b1f --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/HasOnlyReadOnly.cs @@ -0,0 +1,137 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// HasOnlyReadOnly + /// + [DataContract] + public partial class HasOnlyReadOnly : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + public HasOnlyReadOnly() + { + } + + /// + /// Gets or Sets Bar + /// + [DataMember(Name="bar", EmitDefaultValue=false)] + public string Bar { get; private set; } + + /// + /// Gets or Sets Foo + /// + [DataMember(Name="foo", EmitDefaultValue=false)] + public string Foo { get; private set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class HasOnlyReadOnly {\n"); + sb.Append(" Bar: ").Append(Bar).Append("\n"); + sb.Append(" Foo: ").Append(Foo).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 input) + { + return this.Equals(input as HasOnlyReadOnly); + } + + /// + /// Returns true if HasOnlyReadOnly instances are equal + /// + /// Instance of HasOnlyReadOnly to be compared + /// Boolean + public bool Equals(HasOnlyReadOnly input) + { + if (input == null) + return false; + + return + ( + this.Bar == input.Bar || + (this.Bar != null && + this.Bar.Equals(input.Bar)) + ) && + ( + this.Foo == input.Foo || + (this.Foo != null && + this.Foo.Equals(input.Foo)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Bar != null) + hashCode = hashCode * 59 + this.Bar.GetHashCode(); + if (this.Foo != null) + hashCode = hashCode * 59 + this.Foo.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/List.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/List.cs new file mode 100644 index 00000000000..52a234d8cd5 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/List.cs @@ -0,0 +1,124 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// List + /// + [DataContract] + public partial class List : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _123List. + public List(string _123List = default(string)) + { + this._123List = _123List; + } + + /// + /// Gets or Sets _123List + /// + [DataMember(Name="123-list", EmitDefaultValue=false)] + public string _123List { 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 List {\n"); + sb.Append(" _123List: ").Append(_123List).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 input) + { + return this.Equals(input as List); + } + + /// + /// Returns true if List instances are equal + /// + /// Instance of List to be compared + /// Boolean + public bool Equals(List input) + { + if (input == null) + return false; + + return + ( + this._123List == input._123List || + (this._123List != null && + this._123List.Equals(input._123List)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this._123List != null) + hashCode = hashCode * 59 + this._123List.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/MapTest.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/MapTest.cs new file mode 100644 index 00000000000..d5fe36c4151 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/MapTest.cs @@ -0,0 +1,161 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// MapTest + /// + [DataContract] + public partial class MapTest : IEquatable, IValidatableObject + { + + /// + /// Gets or Sets Inner + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum InnerEnum + { + + /// + /// Enum UPPER for "UPPER" + /// + [EnumMember(Value = "UPPER")] + UPPER, + + /// + /// Enum Lower for "lower" + /// + [EnumMember(Value = "lower")] + Lower + } + + /// + /// Gets or Sets MapOfEnumString + /// + [DataMember(Name="map_of_enum_string", EmitDefaultValue=false)] + public Dictionary MapOfEnumString { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// MapMapOfString. + /// MapOfEnumString. + public MapTest(Dictionary> MapMapOfString = default(Dictionary>), Dictionary MapOfEnumString = default(Dictionary)) + { + this.MapMapOfString = MapMapOfString; + this.MapOfEnumString = MapOfEnumString; + } + + /// + /// Gets or Sets MapMapOfString + /// + [DataMember(Name="map_map_of_string", EmitDefaultValue=false)] + public Dictionary> MapMapOfString { 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 MapTest {\n"); + sb.Append(" MapMapOfString: ").Append(MapMapOfString).Append("\n"); + sb.Append(" MapOfEnumString: ").Append(MapOfEnumString).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 input) + { + return this.Equals(input as MapTest); + } + + /// + /// Returns true if MapTest instances are equal + /// + /// Instance of MapTest to be compared + /// Boolean + public bool Equals(MapTest input) + { + if (input == null) + return false; + + return + ( + this.MapMapOfString == input.MapMapOfString || + this.MapMapOfString != null && + this.MapMapOfString.SequenceEqual(input.MapMapOfString) + ) && + ( + this.MapOfEnumString == input.MapOfEnumString || + this.MapOfEnumString != null && + this.MapOfEnumString.SequenceEqual(input.MapOfEnumString) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.MapMapOfString != null) + hashCode = hashCode * 59 + this.MapMapOfString.GetHashCode(); + if (this.MapOfEnumString != null) + hashCode = hashCode * 59 + this.MapOfEnumString.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs new file mode 100644 index 00000000000..fb0a3998053 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// MixedPropertiesAndAdditionalPropertiesClass + /// + [DataContract] + public partial class MixedPropertiesAndAdditionalPropertiesClass : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Uuid. + /// DateTime. + /// Map. + public MixedPropertiesAndAdditionalPropertiesClass(Guid? Uuid = default(Guid?), DateTime? DateTime = default(DateTime?), Dictionary Map = default(Dictionary)) + { + 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 input) + { + return this.Equals(input as MixedPropertiesAndAdditionalPropertiesClass); + } + + /// + /// Returns true if MixedPropertiesAndAdditionalPropertiesClass instances are equal + /// + /// Instance of MixedPropertiesAndAdditionalPropertiesClass to be compared + /// Boolean + public bool Equals(MixedPropertiesAndAdditionalPropertiesClass input) + { + if (input == null) + return false; + + return + ( + this.Uuid == input.Uuid || + (this.Uuid != null && + this.Uuid.Equals(input.Uuid)) + ) && + ( + this.DateTime == input.DateTime || + (this.DateTime != null && + this.DateTime.Equals(input.DateTime)) + ) && + ( + this.Map == input.Map || + this.Map != null && + this.Map.SequenceEqual(input.Map) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Uuid != null) + hashCode = hashCode * 59 + this.Uuid.GetHashCode(); + if (this.DateTime != null) + hashCode = hashCode * 59 + this.DateTime.GetHashCode(); + if (this.Map != null) + hashCode = hashCode * 59 + this.Map.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Model200Response.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Model200Response.cs new file mode 100644 index 00000000000..3d11d1188eb --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Model200Response.cs @@ -0,0 +1,140 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// Model for testing model name starting with number + /// + [DataContract] + public partial class Model200Response : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Name. + /// _Class. + public Model200Response(int? Name = default(int?), string _Class = default(string)) + { + this.Name = Name; + this._Class = _Class; + } + + /// + /// Gets or Sets Name + /// + [DataMember(Name="name", EmitDefaultValue=false)] + public int? Name { get; set; } + + /// + /// Gets or Sets _Class + /// + [DataMember(Name="class", EmitDefaultValue=false)] + public string _Class { 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 Model200Response {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" _Class: ").Append(_Class).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 input) + { + return this.Equals(input as Model200Response); + } + + /// + /// Returns true if Model200Response instances are equal + /// + /// Instance of Model200Response to be compared + /// Boolean + public bool Equals(Model200Response input) + { + if (input == null) + return false; + + return + ( + this.Name == input.Name || + (this.Name != null && + this.Name.Equals(input.Name)) + ) && + ( + this._Class == input._Class || + (this._Class != null && + this._Class.Equals(input._Class)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Name != null) + hashCode = hashCode * 59 + this.Name.GetHashCode(); + if (this._Class != null) + hashCode = hashCode * 59 + this._Class.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ModelClient.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ModelClient.cs new file mode 100644 index 00000000000..5184c5c33d2 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ModelClient.cs @@ -0,0 +1,124 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// ModelClient + /// + [DataContract] + public partial class ModelClient : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _Client. + public ModelClient(string _Client = default(string)) + { + this._Client = _Client; + } + + /// + /// Gets or Sets _Client + /// + [DataMember(Name="client", EmitDefaultValue=false)] + public string _Client { 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 ModelClient {\n"); + sb.Append(" _Client: ").Append(_Client).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 input) + { + return this.Equals(input as ModelClient); + } + + /// + /// Returns true if ModelClient instances are equal + /// + /// Instance of ModelClient to be compared + /// Boolean + public bool Equals(ModelClient input) + { + if (input == null) + return false; + + return + ( + this._Client == input._Client || + (this._Client != null && + this._Client.Equals(input._Client)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this._Client != null) + hashCode = hashCode * 59 + this._Client.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ModelReturn.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ModelReturn.cs new file mode 100644 index 00000000000..9d885bdff8a --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ModelReturn.cs @@ -0,0 +1,124 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// Model for testing reserved words + /// + [DataContract] + public partial class ModelReturn : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _Return. + public ModelReturn(int? _Return = default(int?)) + { + this._Return = _Return; + } + + /// + /// Gets or Sets _Return + /// + [DataMember(Name="return", EmitDefaultValue=false)] + public int? _Return { 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 ModelReturn {\n"); + sb.Append(" _Return: ").Append(_Return).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 input) + { + return this.Equals(input as ModelReturn); + } + + /// + /// Returns true if ModelReturn instances are equal + /// + /// Instance of ModelReturn to be compared + /// Boolean + public bool Equals(ModelReturn input) + { + if (input == null) + return false; + + return + ( + this._Return == input._Return || + (this._Return != null && + this._Return.Equals(input._Return)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this._Return != null) + hashCode = hashCode * 59 + this._Return.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Name.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Name.cs new file mode 100644 index 00000000000..d4c149c0fad --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Name.cs @@ -0,0 +1,181 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// Model for testing model name same as property name + /// + [DataContract] + public partial class Name : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Name() { } + /// + /// Initializes a new instance of the class. + /// + /// _Name (required). + /// Property. + public Name(int? _Name = default(int?), string Property = default(string)) + { + // to ensure "_Name" is required (not null) + if (_Name == null) + { + throw new InvalidDataException("_Name is a required property for Name and cannot be null"); + } + else + { + this._Name = _Name; + } + this.Property = Property; + } + + /// + /// Gets or Sets _Name + /// + [DataMember(Name="name", EmitDefaultValue=false)] + public int? _Name { get; set; } + + /// + /// Gets or Sets SnakeCase + /// + [DataMember(Name="snake_case", EmitDefaultValue=false)] + public int? SnakeCase { get; private set; } + + /// + /// Gets or Sets Property + /// + [DataMember(Name="property", EmitDefaultValue=false)] + public string Property { get; set; } + + /// + /// Gets or Sets _123Number + /// + [DataMember(Name="123Number", EmitDefaultValue=false)] + public int? _123Number { get; private set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + 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("}\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 input) + { + return this.Equals(input as Name); + } + + /// + /// Returns true if Name instances are equal + /// + /// Instance of Name to be compared + /// Boolean + public bool Equals(Name input) + { + if (input == null) + return false; + + return + ( + this._Name == input._Name || + (this._Name != null && + this._Name.Equals(input._Name)) + ) && + ( + this.SnakeCase == input.SnakeCase || + (this.SnakeCase != null && + this.SnakeCase.Equals(input.SnakeCase)) + ) && + ( + this.Property == input.Property || + (this.Property != null && + this.Property.Equals(input.Property)) + ) && + ( + this._123Number == input._123Number || + (this._123Number != null && + this._123Number.Equals(input._123Number)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this._Name != null) + hashCode = hashCode * 59 + this._Name.GetHashCode(); + if (this.SnakeCase != null) + hashCode = hashCode * 59 + this.SnakeCase.GetHashCode(); + if (this.Property != null) + hashCode = hashCode * 59 + this.Property.GetHashCode(); + if (this._123Number != null) + hashCode = hashCode * 59 + this._123Number.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/NumberOnly.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/NumberOnly.cs new file mode 100644 index 00000000000..61c9be60c1d --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/NumberOnly.cs @@ -0,0 +1,124 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// NumberOnly + /// + [DataContract] + public partial class NumberOnly : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// JustNumber. + public NumberOnly(decimal? JustNumber = default(decimal?)) + { + this.JustNumber = JustNumber; + } + + /// + /// Gets or Sets JustNumber + /// + [DataMember(Name="JustNumber", EmitDefaultValue=false)] + public decimal? JustNumber { 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 NumberOnly {\n"); + sb.Append(" JustNumber: ").Append(JustNumber).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 input) + { + return this.Equals(input as NumberOnly); + } + + /// + /// Returns true if NumberOnly instances are equal + /// + /// Instance of NumberOnly to be compared + /// Boolean + public bool Equals(NumberOnly input) + { + if (input == null) + return false; + + return + ( + this.JustNumber == input.JustNumber || + (this.JustNumber != null && + this.JustNumber.Equals(input.JustNumber)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.JustNumber != null) + hashCode = hashCode * 59 + this.JustNumber.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Order.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Order.cs new file mode 100644 index 00000000000..e92a21c36c2 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Order.cs @@ -0,0 +1,240 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// Order + /// + [DataContract] + public partial class Order : IEquatable, IValidatableObject + { + /// + /// Order Status + /// + /// Order Status + [JsonConverter(typeof(StringEnumConverter))] + public enum StatusEnum + { + + /// + /// Enum Placed for "placed" + /// + [EnumMember(Value = "placed")] + Placed, + + /// + /// Enum Approved for "approved" + /// + [EnumMember(Value = "approved")] + Approved, + + /// + /// Enum Delivered for "delivered" + /// + [EnumMember(Value = "delivered")] + Delivered + } + + /// + /// Order Status + /// + /// Order Status + [DataMember(Name="status", EmitDefaultValue=false)] + public StatusEnum? Status { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// Id. + /// PetId. + /// Quantity. + /// ShipDate. + /// Order Status. + /// Complete (default to false). + public Order(long? Id = default(long?), long? PetId = default(long?), int? Quantity = default(int?), DateTime? ShipDate = default(DateTime?), StatusEnum? Status = default(StatusEnum?), bool? Complete = false) + { + 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) + { + this.Complete = false; + } + else + { + this.Complete = Complete; + } + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name="id", EmitDefaultValue=false)] + public long? Id { get; set; } + + /// + /// Gets or Sets PetId + /// + [DataMember(Name="petId", EmitDefaultValue=false)] + public long? PetId { get; set; } + + /// + /// Gets or Sets Quantity + /// + [DataMember(Name="quantity", EmitDefaultValue=false)] + public int? Quantity { get; set; } + + /// + /// Gets or Sets ShipDate + /// + [DataMember(Name="shipDate", EmitDefaultValue=false)] + public DateTime? ShipDate { get; set; } + + + /// + /// Gets or Sets Complete + /// + [DataMember(Name="complete", EmitDefaultValue=false)] + public bool? Complete { 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 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(); + } + + /// + /// 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 input) + { + return this.Equals(input as Order); + } + + /// + /// Returns true if Order instances are equal + /// + /// Instance of Order to be compared + /// Boolean + public bool Equals(Order input) + { + if (input == null) + return false; + + return + ( + this.Id == input.Id || + (this.Id != null && + this.Id.Equals(input.Id)) + ) && + ( + this.PetId == input.PetId || + (this.PetId != null && + this.PetId.Equals(input.PetId)) + ) && + ( + this.Quantity == input.Quantity || + (this.Quantity != null && + this.Quantity.Equals(input.Quantity)) + ) && + ( + this.ShipDate == input.ShipDate || + (this.ShipDate != null && + this.ShipDate.Equals(input.ShipDate)) + ) && + ( + this.Status == input.Status || + (this.Status != null && + this.Status.Equals(input.Status)) + ) && + ( + this.Complete == input.Complete || + (this.Complete != null && + this.Complete.Equals(input.Complete)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Id != null) + hashCode = hashCode * 59 + this.Id.GetHashCode(); + if (this.PetId != null) + hashCode = hashCode * 59 + this.PetId.GetHashCode(); + if (this.Quantity != null) + hashCode = hashCode * 59 + this.Quantity.GetHashCode(); + if (this.ShipDate != null) + hashCode = hashCode * 59 + this.ShipDate.GetHashCode(); + if (this.Status != null) + hashCode = hashCode * 59 + this.Status.GetHashCode(); + if (this.Complete != null) + hashCode = hashCode * 59 + this.Complete.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/OuterBoolean.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/OuterBoolean.cs new file mode 100644 index 00000000000..45a3382919f --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/OuterBoolean.cs @@ -0,0 +1,109 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// OuterBoolean + /// + [DataContract] + public partial class OuterBoolean : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + public OuterBoolean() + { + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class OuterBoolean {\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 input) + { + return this.Equals(input as OuterBoolean); + } + + /// + /// Returns true if OuterBoolean instances are equal + /// + /// Instance of OuterBoolean to be compared + /// Boolean + public bool Equals(OuterBoolean input) + { + if (input == null) + return false; + + return false; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/OuterComposite.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/OuterComposite.cs new file mode 100644 index 00000000000..4c12290c2ee --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/OuterComposite.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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// OuterComposite + /// + [DataContract] + public partial class OuterComposite : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// MyNumber. + /// MyString. + /// MyBoolean. + public OuterComposite(OuterNumber MyNumber = default(OuterNumber), OuterString MyString = default(OuterString), OuterBoolean MyBoolean = default(OuterBoolean)) + { + this.MyNumber = MyNumber; + this.MyString = MyString; + this.MyBoolean = MyBoolean; + } + + /// + /// Gets or Sets MyNumber + /// + [DataMember(Name="my_number", EmitDefaultValue=false)] + public OuterNumber MyNumber { get; set; } + + /// + /// Gets or Sets MyString + /// + [DataMember(Name="my_string", EmitDefaultValue=false)] + public OuterString MyString { get; set; } + + /// + /// Gets or Sets MyBoolean + /// + [DataMember(Name="my_boolean", EmitDefaultValue=false)] + public OuterBoolean MyBoolean { 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 OuterComposite {\n"); + sb.Append(" MyNumber: ").Append(MyNumber).Append("\n"); + sb.Append(" MyString: ").Append(MyString).Append("\n"); + sb.Append(" MyBoolean: ").Append(MyBoolean).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 input) + { + return this.Equals(input as OuterComposite); + } + + /// + /// Returns true if OuterComposite instances are equal + /// + /// Instance of OuterComposite to be compared + /// Boolean + public bool Equals(OuterComposite input) + { + if (input == null) + return false; + + return + ( + this.MyNumber == input.MyNumber || + (this.MyNumber != null && + this.MyNumber.Equals(input.MyNumber)) + ) && + ( + this.MyString == input.MyString || + (this.MyString != null && + this.MyString.Equals(input.MyString)) + ) && + ( + this.MyBoolean == input.MyBoolean || + (this.MyBoolean != null && + this.MyBoolean.Equals(input.MyBoolean)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.MyNumber != null) + hashCode = hashCode * 59 + this.MyNumber.GetHashCode(); + if (this.MyString != null) + hashCode = hashCode * 59 + this.MyString.GetHashCode(); + if (this.MyBoolean != null) + hashCode = hashCode * 59 + this.MyBoolean.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/OuterEnum.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/OuterEnum.cs new file mode 100644 index 00000000000..16135a6a052 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/OuterEnum.cs @@ -0,0 +1,53 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// Defines OuterEnum + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum OuterEnum + { + + /// + /// Enum Placed for "placed" + /// + [EnumMember(Value = "placed")] + Placed, + + /// + /// Enum Approved for "approved" + /// + [EnumMember(Value = "approved")] + Approved, + + /// + /// Enum Delivered for "delivered" + /// + [EnumMember(Value = "delivered")] + Delivered + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/OuterNumber.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/OuterNumber.cs new file mode 100644 index 00000000000..395239a27c1 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/OuterNumber.cs @@ -0,0 +1,109 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// OuterNumber + /// + [DataContract] + public partial class OuterNumber : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + public OuterNumber() + { + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class OuterNumber {\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 input) + { + return this.Equals(input as OuterNumber); + } + + /// + /// Returns true if OuterNumber instances are equal + /// + /// Instance of OuterNumber to be compared + /// Boolean + public bool Equals(OuterNumber input) + { + if (input == null) + return false; + + return false; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/OuterString.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/OuterString.cs new file mode 100644 index 00000000000..4a08ab3f7f7 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/OuterString.cs @@ -0,0 +1,109 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// OuterString + /// + [DataContract] + public partial class OuterString : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + public OuterString() + { + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class OuterString {\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 input) + { + return this.Equals(input as OuterString); + } + + /// + /// Returns true if OuterString instances are equal + /// + /// Instance of OuterString to be compared + /// Boolean + public bool Equals(OuterString input) + { + if (input == null) + return false; + + return false; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Pet.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Pet.cs new file mode 100644 index 00000000000..fa39a5da19c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Pet.cs @@ -0,0 +1,253 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// Pet + /// + [DataContract] + public partial class Pet : IEquatable, IValidatableObject + { + /// + /// pet status in the store + /// + /// pet status in the store + [JsonConverter(typeof(StringEnumConverter))] + public enum StatusEnum + { + + /// + /// Enum Available for "available" + /// + [EnumMember(Value = "available")] + Available, + + /// + /// Enum Pending for "pending" + /// + [EnumMember(Value = "pending")] + Pending, + + /// + /// Enum Sold for "sold" + /// + [EnumMember(Value = "sold")] + Sold + } + + /// + /// pet status in the store + /// + /// pet status in the store + [DataMember(Name="status", EmitDefaultValue=false)] + public StatusEnum? Status { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Pet() { } + /// + /// Initializes a new instance of the class. + /// + /// Id. + /// Category. + /// Name (required). + /// PhotoUrls (required). + /// Tags. + /// pet status in the store. + public Pet(long? Id = default(long?), Category Category = default(Category), string Name = default(string), List PhotoUrls = default(List), List Tags = default(List), StatusEnum? Status = default(StatusEnum?)) + { + // to ensure "Name" is required (not null) + if (Name == null) + { + throw new InvalidDataException("Name is a required property for Pet and cannot be null"); + } + else + { + this.Name = Name; + } + // to ensure "PhotoUrls" is required (not null) + if (PhotoUrls == null) + { + throw new InvalidDataException("PhotoUrls is a required property for Pet and cannot be null"); + } + else + { + this.PhotoUrls = PhotoUrls; + } + this.Id = Id; + this.Category = Category; + this.Tags = Tags; + this.Status = Status; + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name="id", EmitDefaultValue=false)] + public long? Id { get; set; } + + /// + /// Gets or Sets Category + /// + [DataMember(Name="category", EmitDefaultValue=false)] + public Category Category { get; set; } + + /// + /// Gets or Sets Name + /// + [DataMember(Name="name", EmitDefaultValue=false)] + public string Name { get; set; } + + /// + /// Gets or Sets PhotoUrls + /// + [DataMember(Name="photoUrls", EmitDefaultValue=false)] + public List PhotoUrls { get; set; } + + /// + /// Gets or Sets Tags + /// + [DataMember(Name="tags", EmitDefaultValue=false)] + public List Tags { 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 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(); + } + + /// + /// 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 input) + { + return this.Equals(input as Pet); + } + + /// + /// Returns true if Pet instances are equal + /// + /// Instance of Pet to be compared + /// Boolean + public bool Equals(Pet input) + { + if (input == null) + return false; + + return + ( + this.Id == input.Id || + (this.Id != null && + this.Id.Equals(input.Id)) + ) && + ( + this.Category == input.Category || + (this.Category != null && + this.Category.Equals(input.Category)) + ) && + ( + this.Name == input.Name || + (this.Name != null && + this.Name.Equals(input.Name)) + ) && + ( + this.PhotoUrls == input.PhotoUrls || + this.PhotoUrls != null && + this.PhotoUrls.SequenceEqual(input.PhotoUrls) + ) && + ( + this.Tags == input.Tags || + this.Tags != null && + this.Tags.SequenceEqual(input.Tags) + ) && + ( + this.Status == input.Status || + (this.Status != null && + this.Status.Equals(input.Status)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Id != null) + hashCode = hashCode * 59 + this.Id.GetHashCode(); + if (this.Category != null) + hashCode = hashCode * 59 + this.Category.GetHashCode(); + if (this.Name != null) + hashCode = hashCode * 59 + this.Name.GetHashCode(); + if (this.PhotoUrls != null) + hashCode = hashCode * 59 + this.PhotoUrls.GetHashCode(); + if (this.Tags != null) + hashCode = hashCode * 59 + this.Tags.GetHashCode(); + if (this.Status != null) + hashCode = hashCode * 59 + this.Status.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ReadOnlyFirst.cs new file mode 100644 index 00000000000..fa281fdecf7 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/ReadOnlyFirst.cs @@ -0,0 +1,138 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// ReadOnlyFirst + /// + [DataContract] + public partial class ReadOnlyFirst : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Baz. + public ReadOnlyFirst(string Baz = default(string)) + { + 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 input) + { + return this.Equals(input as ReadOnlyFirst); + } + + /// + /// Returns true if ReadOnlyFirst instances are equal + /// + /// Instance of ReadOnlyFirst to be compared + /// Boolean + public bool Equals(ReadOnlyFirst input) + { + if (input == null) + return false; + + return + ( + this.Bar == input.Bar || + (this.Bar != null && + this.Bar.Equals(input.Bar)) + ) && + ( + this.Baz == input.Baz || + (this.Baz != null && + this.Baz.Equals(input.Baz)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Bar != null) + hashCode = hashCode * 59 + this.Bar.GetHashCode(); + if (this.Baz != null) + hashCode = hashCode * 59 + this.Baz.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/SpecialModelName.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/SpecialModelName.cs new file mode 100644 index 00000000000..198a04fee71 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/SpecialModelName.cs @@ -0,0 +1,124 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// SpecialModelName + /// + [DataContract] + public partial class SpecialModelName : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// SpecialPropertyName. + public SpecialModelName(long? SpecialPropertyName = default(long?)) + { + this.SpecialPropertyName = SpecialPropertyName; + } + + /// + /// Gets or Sets SpecialPropertyName + /// + [DataMember(Name="$special[property.name]", EmitDefaultValue=false)] + public long? SpecialPropertyName { 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 SpecialModelName {\n"); + sb.Append(" SpecialPropertyName: ").Append(SpecialPropertyName).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 input) + { + return this.Equals(input as SpecialModelName); + } + + /// + /// Returns true if SpecialModelName instances are equal + /// + /// Instance of SpecialModelName to be compared + /// Boolean + public bool Equals(SpecialModelName input) + { + if (input == null) + return false; + + return + ( + this.SpecialPropertyName == input.SpecialPropertyName || + (this.SpecialPropertyName != null && + this.SpecialPropertyName.Equals(input.SpecialPropertyName)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.SpecialPropertyName != null) + hashCode = hashCode * 59 + this.SpecialPropertyName.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Tag.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Tag.cs new file mode 100644 index 00000000000..a4ae373b979 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/Tag.cs @@ -0,0 +1,140 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// Tag + /// + [DataContract] + public partial class Tag : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Id. + /// Name. + public Tag(long? Id = default(long?), string Name = default(string)) + { + this.Id = Id; + this.Name = Name; + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name="id", EmitDefaultValue=false)] + public long? Id { 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 Tag {\n"); + sb.Append(" Id: ").Append(Id).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 string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as Tag); + } + + /// + /// Returns true if Tag instances are equal + /// + /// Instance of Tag to be compared + /// Boolean + public bool Equals(Tag input) + { + if (input == null) + return false; + + return + ( + this.Id == input.Id || + (this.Id != null && + this.Id.Equals(input.Id)) + ) && + ( + this.Name == input.Name || + (this.Name != null && + this.Name.Equals(input.Name)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Id != null) + hashCode = hashCode * 59 + this.Id.GetHashCode(); + if (this.Name != null) + hashCode = hashCode * 59 + this.Name.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/User.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/User.cs new file mode 100644 index 00000000000..ada8d682356 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Model/User.cs @@ -0,0 +1,237 @@ +/* + * 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 + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// User + /// + [DataContract] + public partial class User : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Id. + /// Username. + /// FirstName. + /// LastName. + /// Email. + /// Password. + /// Phone. + /// User Status. + public User(long? Id = default(long?), string Username = default(string), string FirstName = default(string), string LastName = default(string), string Email = default(string), string Password = default(string), string Phone = default(string), int? UserStatus = default(int?)) + { + this.Id = Id; + this.Username = Username; + this.FirstName = FirstName; + this.LastName = LastName; + this.Email = Email; + this.Password = Password; + this.Phone = Phone; + this.UserStatus = UserStatus; + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name="id", EmitDefaultValue=false)] + public long? Id { get; set; } + + /// + /// Gets or Sets Username + /// + [DataMember(Name="username", EmitDefaultValue=false)] + public string Username { get; set; } + + /// + /// Gets or Sets FirstName + /// + [DataMember(Name="firstName", EmitDefaultValue=false)] + public string FirstName { get; set; } + + /// + /// Gets or Sets LastName + /// + [DataMember(Name="lastName", EmitDefaultValue=false)] + public string LastName { get; set; } + + /// + /// Gets or Sets Email + /// + [DataMember(Name="email", EmitDefaultValue=false)] + public string Email { get; set; } + + /// + /// Gets or Sets Password + /// + [DataMember(Name="password", EmitDefaultValue=false)] + public string Password { get; set; } + + /// + /// Gets or Sets Phone + /// + [DataMember(Name="phone", EmitDefaultValue=false)] + public string Phone { get; set; } + + /// + /// User Status + /// + /// User Status + [DataMember(Name="userStatus", EmitDefaultValue=false)] + public int? UserStatus { 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 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(); + } + + /// + /// 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 input) + { + return this.Equals(input as User); + } + + /// + /// Returns true if User instances are equal + /// + /// Instance of User to be compared + /// Boolean + public bool Equals(User input) + { + if (input == null) + return false; + + return + ( + this.Id == input.Id || + (this.Id != null && + this.Id.Equals(input.Id)) + ) && + ( + this.Username == input.Username || + (this.Username != null && + this.Username.Equals(input.Username)) + ) && + ( + this.FirstName == input.FirstName || + (this.FirstName != null && + this.FirstName.Equals(input.FirstName)) + ) && + ( + this.LastName == input.LastName || + (this.LastName != null && + this.LastName.Equals(input.LastName)) + ) && + ( + this.Email == input.Email || + (this.Email != null && + this.Email.Equals(input.Email)) + ) && + ( + this.Password == input.Password || + (this.Password != null && + this.Password.Equals(input.Password)) + ) && + ( + this.Phone == input.Phone || + (this.Phone != null && + this.Phone.Equals(input.Phone)) + ) && + ( + this.UserStatus == input.UserStatus || + (this.UserStatus != null && + this.UserStatus.Equals(input.UserStatus)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Id != null) + hashCode = hashCode * 59 + this.Id.GetHashCode(); + if (this.Username != null) + hashCode = hashCode * 59 + this.Username.GetHashCode(); + if (this.FirstName != null) + hashCode = hashCode * 59 + this.FirstName.GetHashCode(); + if (this.LastName != null) + hashCode = hashCode * 59 + this.LastName.GetHashCode(); + if (this.Email != null) + hashCode = hashCode * 59 + this.Email.GetHashCode(); + if (this.Password != null) + hashCode = hashCode * 59 + this.Password.GetHashCode(); + if (this.Phone != null) + hashCode = hashCode * 59 + this.Phone.GetHashCode(); + if (this.UserStatus != null) + hashCode = hashCode * 59 + this.UserStatus.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Properties/AssemblyInfo.cs b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..f3b9f7d1d14 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Properties/AssemblyInfo.cs @@ -0,0 +1,32 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Swagger Library")] +[assembly: AssemblyDescription("A library generated from a Swagger doc")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Swagger")] +[assembly: AssemblyProduct("SwaggerLibrary")] +[assembly: AssemblyCopyright("No Copyright")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0")] +[assembly: AssemblyFileVersion("1.0.0")] diff --git a/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/packages.config b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/packages.config new file mode 100644 index 00000000000..b464072993f --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/packages.config @@ -0,0 +1,5 @@ + + + + + diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/api/fake.ex b/samples/client/petstore/elixir/lib/swagger_petstore/api/fake.ex index e25a05c4fb0..8dce861d196 100644 --- a/samples/client/petstore/elixir/lib/swagger_petstore/api/fake.ex +++ b/samples/client/petstore/elixir/lib/swagger_petstore/api/fake.ex @@ -247,6 +247,32 @@ defmodule SwaggerPetstore.Api.Fake do |> decode(false) end + @doc """ + test inline additionalProperties + + + ## Parameters + + - connection (SwaggerPetstore.Connection): Connection to server + - param (Object): request body + - opts (KeywordList): [optional] Optional parameters + + ## Returns + + {:ok, %{}} on success + {:error, info} on failure + """ + @spec test_inline_additional_properties(Tesla.Env.client, SwaggerPetstore.Model.Object.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} + def test_inline_additional_properties(connection, param, _opts \\ []) do + %{} + |> method(:post) + |> url("/fake/inline-additionalProperties") + |> add_param(:body, :"param", param) + |> Enum.into([]) + |> (&Connection.request(connection, &1)).() + |> decode(false) + end + @doc """ test json serialization of form data diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/request_builder.ex b/samples/client/petstore/elixir/lib/swagger_petstore/request_builder.ex index 01512b7e278..a1aca31bd6c 100644 --- a/samples/client/petstore/elixir/lib/swagger_petstore/request_builder.ex +++ b/samples/client/petstore/elixir/lib/swagger_petstore/request_builder.ex @@ -13,13 +13,13 @@ defmodule SwaggerPetstore.RequestBuilder do ## Parameters - request (Map) - Collected request options - - m (String) - Request method + - m (atom) - Request method ## Returns Map """ - @spec method(map(), String.t) :: map() + @spec method(map(), atom) :: map() def method(request, m) do Map.put_new(request, :method, m) end @@ -54,7 +54,7 @@ defmodule SwaggerPetstore.RequestBuilder do Map """ - @spec add_optional_params(map(), %{optional(:atom) => :atom}, keyword()) :: map() + @spec add_optional_params(map(), %{optional(atom) => atom}, keyword()) :: map() def add_optional_params(request, _, []), do: request def add_optional_params(request, definitions, [{key, value} | tail]) do case definitions do @@ -81,7 +81,7 @@ defmodule SwaggerPetstore.RequestBuilder do Map """ - @spec add_param(map(), :atom, :atom, any()) :: map() + @spec add_param(map(), atom, atom, any()) :: map() def add_param(request, :body, :body, value), do: Map.put(request, :body, value) def add_param(request, :body, key, value) do request @@ -106,25 +106,20 @@ defmodule SwaggerPetstore.RequestBuilder do ## Parameters - - env (Tesla.Env) - The response object - - struct - The shape of the struct to deserialize into + - arg1 (Tesla.Env.t | term) - The response object + - arg2 (:false | struct | [struct]) - The shape of the struct to deserialize into ## Returns {:ok, struct} on success - {:error, info} on failure + {:error, term} on failure """ - @spec decode(Tesla.Env.t) :: {:ok, struct()} | {:error, Tesla.Env.t} + @spec decode(Tesla.Env.t | term()) :: {:ok, struct()} | {:error, Tesla.Env.t} | {:error, term()} def decode(%Tesla.Env{status: 200, body: body}), do: Poison.decode(body) - def decode(response) do - {:error, response} - end - @spec decode(Tesla.Env.t, struct()) :: {:ok, struct()} | {:error, Tesla.Env.t} + def decode(response), do: {:error, response} + + @spec decode(Tesla.Env.t | term(), :false | struct() | [struct()]) :: {:ok, struct()} | {:error, Tesla.Env.t} | {:error, term()} def decode(%Tesla.Env{status: 200} = env, false), do: {:ok, env} - def decode(%Tesla.Env{status: 200, body: body}, struct) do - Poison.decode(body, as: struct) - end - def decode(response, _struct) do - {:error, response} - end + def decode(%Tesla.Env{status: 200, body: body}, struct), do: Poison.decode(body, as: struct) + def decode(response, _struct), do: {:error, response} end diff --git a/samples/client/petstore/erlang-client/.swagger-codegen-ignore b/samples/client/petstore/erlang-client/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/erlang-client/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/erlang-client/.swagger-codegen/VERSION b/samples/client/petstore/erlang-client/.swagger-codegen/VERSION new file mode 100644 index 00000000000..f9f7450d135 --- /dev/null +++ b/samples/client/petstore/erlang-client/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/erlang-client/README.md b/samples/client/petstore/erlang-client/README.md new file mode 100644 index 00000000000..f3eab0b5528 --- /dev/null +++ b/samples/client/petstore/erlang-client/README.md @@ -0,0 +1,5 @@ +# Swagger client server library for Erlang + +## Overview + +An Erlang client stub generated by [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) given an OpenAPI/Swagger spec. diff --git a/samples/client/petstore/erlang-client/rebar.config b/samples/client/petstore/erlang-client/rebar.config new file mode 100644 index 00000000000..abe84a1a9f3 --- /dev/null +++ b/samples/client/petstore/erlang-client/rebar.config @@ -0,0 +1,3 @@ +{erl_opts, [debug_info, warnings_as_errors, warn_untyped_record]}. + +{deps, [jsx, hackney]}. diff --git a/samples/client/petstore/erlang-client/src/swagger.app.src b/samples/client/petstore/erlang-client/src/swagger.app.src new file mode 100644 index 00000000000..7f4d814ca3e --- /dev/null +++ b/samples/client/petstore/erlang-client/src/swagger.app.src @@ -0,0 +1,17 @@ +{application, swagger, + [{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."}, + {vsn, ""}, + {registered, []}, + {applications, + [kernel, + stdlib, + ssl, + hackney + ]}, + {env, []}, + {modules, []}, + + {maintainers, []}, + {licenses, ["Apache-2.0"]}, + {links, []} +]}. diff --git a/samples/client/petstore/erlang-client/src/swagger_api_response.erl b/samples/client/petstore/erlang-client/src/swagger_api_response.erl new file mode 100644 index 00000000000..33826528dc4 --- /dev/null +++ b/samples/client/petstore/erlang-client/src/swagger_api_response.erl @@ -0,0 +1,20 @@ +-module(swagger_api_response). + +-export_type([swagger_api_response/0, + encode/1, + decode/1]). + +-type swagger_api_response() :: + #{ 'code' => integer(), + 'type' => binary(), + 'message' => binary() + }. + +encode(#{ 'code' := Code, + 'type' := Type, + 'message' := Message + }) -> + #{ 'code' => Code, + 'type' => Type, + 'message' => Message + } diff --git a/samples/client/petstore/erlang-client/src/swagger_category.erl b/samples/client/petstore/erlang-client/src/swagger_category.erl new file mode 100644 index 00000000000..0bd89b55087 --- /dev/null +++ b/samples/client/petstore/erlang-client/src/swagger_category.erl @@ -0,0 +1,17 @@ +-module(swagger_category). + +-export_type([swagger_category/0, + encode/1, + decode/1]). + +-type swagger_category() :: + #{ 'id' => integer(), + 'name' => binary() + }. + +encode(#{ 'id' := Id, + 'name' := Name + }) -> + #{ 'id' => Id, + 'name' => Name + } diff --git a/samples/client/petstore/erlang-client/src/swagger_order.erl b/samples/client/petstore/erlang-client/src/swagger_order.erl new file mode 100644 index 00000000000..06a9a1a270a --- /dev/null +++ b/samples/client/petstore/erlang-client/src/swagger_order.erl @@ -0,0 +1,29 @@ +-module(swagger_order). + +-export_type([swagger_order/0, + encode/1, + decode/1]). + +-type swagger_order() :: + #{ 'id' => integer(), + 'petId' => integer(), + 'quantity' => integer(), + 'shipDate' => swagger_date_time:swagger_date_time(), + 'status' => binary(), + 'complete' => boolean() + }. + +encode(#{ 'id' := Id, + 'petId' := PetId, + 'quantity' := Quantity, + 'shipDate' := ShipDate, + 'status' := Status, + 'complete' := Complete + }) -> + #{ 'id' => Id, + 'petId' => PetId, + 'quantity' => Quantity, + 'shipDate' => ShipDate, + 'status' => Status, + 'complete' => Complete + } diff --git a/samples/client/petstore/erlang-client/src/swagger_pet.erl b/samples/client/petstore/erlang-client/src/swagger_pet.erl new file mode 100644 index 00000000000..c9484fa0fea --- /dev/null +++ b/samples/client/petstore/erlang-client/src/swagger_pet.erl @@ -0,0 +1,29 @@ +-module(swagger_pet). + +-export_type([swagger_pet/0, + encode/1, + decode/1]). + +-type swagger_pet() :: + #{ 'id' => integer(), + 'category' => swagger_category:swagger_category(), + 'name' := binary(), + 'photoUrls' := list(), + 'tags' => list(), + 'status' => binary() + }. + +encode(#{ 'id' := Id, + 'category' := Category, + 'name' := Name, + 'photoUrls' := PhotoUrls, + 'tags' := Tags, + 'status' := Status + }) -> + #{ 'id' => Id, + 'category' => Category, + 'name' => Name, + 'photoUrls' => PhotoUrls, + 'tags' => Tags, + 'status' => Status + } diff --git a/samples/client/petstore/erlang-client/src/swagger_pet_api.erl b/samples/client/petstore/erlang-client/src/swagger_pet_api.erl new file mode 100644 index 00000000000..7eaef8fed81 --- /dev/null +++ b/samples/client/petstore/erlang-client/src/swagger_pet_api.erl @@ -0,0 +1,165 @@ +-module(swagger_pet_api). + +-export([add_pet/1, + delete_pet/2, + find_pets_by_status/1, + find_pets_by_tags/1, + get_pet_by_id/1, + update_pet/1, + update_pet_with_form/3, + upload_file/3]). + +-define(BASE_URL, <<"http://petstore.swagger.io/v2">>). + +%% @doc Add a new pet to the store +-spec add_pet(swagger_pet:swagger_pet()) -> ok | {error, integer()}. +add_pet(Body) -> + Method = post, + Path = ["/pet"], + QS = [], + Headers = [], + Body1 = Body, + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, _RespHeaders, _ClientRef} -> + ok; + {ok, Status, _RespHeaders, _ClientRef} -> + {error, Status} + end. + +%% @doc Deletes a pet +-spec delete_pet(integer(), binary()) -> ok | {error, integer()}. +delete_pet(PetId, ApiKey) -> + Method = delete, + Path = ["/pet/", PetId, ""], + QS = [], + Headers = [{<<"api_key">>, ApiKey}], + Body1 = [], + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, _RespHeaders, _ClientRef} -> + ok; + {ok, Status, _RespHeaders, _ClientRef} -> + {error, Status} + end. + +%% @doc Finds Pets by status +%% Multiple status values can be provided with comma separated strings +-spec find_pets_by_status(list()) -> {ok, list(), [swagger_pet:swagger_pet()]} | {error, string()}. +find_pets_by_status(Status) -> + Method = get, + Path = ["/pet/findByStatus"], + QS = lists:flatten([[{<<"status">>, X} || X <- Status]]), + Headers = [], + Body1 = [], + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, RespHeaders, ClientRef} -> + {ok, Body} = hackney:body(ClientRef), + {ok, RespHeaders, jsx:decode(Body, [returns_maps, {labels, attempt_atom}])}; + {ok, 400, _RespHeaders, _ClientRef} -> + {error, "Invalid status value"} + end. + +%% @doc Finds Pets by tags +%% Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. +-spec find_pets_by_tags(list()) -> {ok, list(), [swagger_pet:swagger_pet()]} | {error, string()}. +find_pets_by_tags(Tags) -> + Method = get, + Path = ["/pet/findByTags"], + QS = lists:flatten([[{<<"tags">>, X} || X <- Tags]]), + Headers = [], + Body1 = [], + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, RespHeaders, ClientRef} -> + {ok, Body} = hackney:body(ClientRef), + {ok, RespHeaders, jsx:decode(Body, [returns_maps, {labels, attempt_atom}])}; + {ok, 400, _RespHeaders, _ClientRef} -> + {error, "Invalid tag value"} + end. + +%% @doc Find pet by ID +%% Returns a single pet +-spec get_pet_by_id(integer()) -> {ok, list(), swagger_pet:swagger_pet()} | {error, string()}. +get_pet_by_id(PetId) -> + Method = get, + Path = ["/pet/", PetId, ""], + QS = [], + Headers = [], + Body1 = [], + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, RespHeaders, ClientRef} -> + {ok, Body} = hackney:body(ClientRef), + {ok, RespHeaders, jsx:decode(Body, [returns_maps, {labels, attempt_atom}])}; + {ok, 400, _RespHeaders, _ClientRef} -> + {error, "Invalid ID supplied"}; + {ok, 404, _RespHeaders, _ClientRef} -> + {error, "Pet not found"} + end. + +%% @doc Update an existing pet +-spec update_pet(swagger_pet:swagger_pet()) -> ok | {error, integer()}. +update_pet(Body) -> + Method = put, + Path = ["/pet"], + QS = [], + Headers = [], + Body1 = Body, + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, _RespHeaders, _ClientRef} -> + ok; + {ok, Status, _RespHeaders, _ClientRef} -> + {error, Status} + end. + +%% @doc Updates a pet in the store with form data +-spec update_pet_with_form(integer(), binary(), binary()) -> ok | {error, integer()}. +update_pet_with_form(PetId, Name, Status) -> + Method = post, + Path = ["/pet/", PetId, ""], + QS = [], + Headers = [], + Body1 = {form, [{<<"name">>, Name}, {<<"status">>, Status}]}, + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, _RespHeaders, _ClientRef} -> + ok; + {ok, Status, _RespHeaders, _ClientRef} -> + {error, Status} + end. + +%% @doc uploads an image +-spec upload_file(integer(), binary(), binary()) -> {ok, list(), swagger_api_response:swagger_api_response()} | {error, string()}. +upload_file(PetId, AdditionalMetadata, File) -> + Method = post, + Path = ["/pet/", PetId, "/uploadImage"], + QS = [], + Headers = [], + Body1 = {form, [{<<"additionalMetadata">>, AdditionalMetadata}, {<<"file">>, File}]}, + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, RespHeaders, ClientRef} -> + {ok, Body} = hackney:body(ClientRef), + {ok, RespHeaders, jsx:decode(Body, [returns_maps, {labels, attempt_atom}])} + end. + + diff --git a/samples/client/petstore/erlang-client/src/swagger_store_api.erl b/samples/client/petstore/erlang-client/src/swagger_store_api.erl new file mode 100644 index 00000000000..1061556f5f6 --- /dev/null +++ b/samples/client/petstore/erlang-client/src/swagger_store_api.erl @@ -0,0 +1,88 @@ +-module(swagger_store_api). + +-export([delete_order/1, + get_inventory/0, + get_order_by_id/1, + place_order/1]). + +-define(BASE_URL, <<"http://petstore.swagger.io/v2">>). + +%% @doc Delete purchase order by ID +%% For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors +-spec delete_order(binary()) -> ok | {error, integer()}. +delete_order(OrderId) -> + Method = delete, + Path = ["/store/order/", OrderId, ""], + QS = [], + Headers = [], + Body1 = [], + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, _RespHeaders, _ClientRef} -> + ok; + {ok, Status, _RespHeaders, _ClientRef} -> + {error, Status} + end. + +%% @doc Returns pet inventories by status +%% Returns a map of status codes to quantities +-spec get_inventory() -> {ok, list(), maps:map()} | {error, string()}. +get_inventory() -> + Method = get, + Path = ["/store/inventory"], + QS = [], + Headers = [], + Body1 = [], + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, RespHeaders, ClientRef} -> + {ok, Body} = hackney:body(ClientRef), + {ok, RespHeaders, jsx:decode(Body, [returns_maps, {labels, attempt_atom}])} + end. + +%% @doc Find purchase order by ID +%% For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions +-spec get_order_by_id(integer()) -> {ok, list(), swagger_order:swagger_order()} | {error, string()}. +get_order_by_id(OrderId) -> + Method = get, + Path = ["/store/order/", OrderId, ""], + QS = [], + Headers = [], + Body1 = [], + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, RespHeaders, ClientRef} -> + {ok, Body} = hackney:body(ClientRef), + {ok, RespHeaders, jsx:decode(Body, [returns_maps, {labels, attempt_atom}])}; + {ok, 400, _RespHeaders, _ClientRef} -> + {error, "Invalid ID supplied"}; + {ok, 404, _RespHeaders, _ClientRef} -> + {error, "Order not found"} + end. + +%% @doc Place an order for a pet +-spec place_order(swagger_order:swagger_order()) -> {ok, list(), swagger_order:swagger_order()} | {error, string()}. +place_order(Body) -> + Method = post, + Path = ["/store/order"], + QS = [], + Headers = [], + Body1 = Body, + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, RespHeaders, ClientRef} -> + {ok, Body} = hackney:body(ClientRef), + {ok, RespHeaders, jsx:decode(Body, [returns_maps, {labels, attempt_atom}])}; + {ok, 400, _RespHeaders, _ClientRef} -> + {error, "Invalid Order"} + end. + + diff --git a/samples/client/petstore/erlang-client/src/swagger_tag.erl b/samples/client/petstore/erlang-client/src/swagger_tag.erl new file mode 100644 index 00000000000..5abdf9b959f --- /dev/null +++ b/samples/client/petstore/erlang-client/src/swagger_tag.erl @@ -0,0 +1,17 @@ +-module(swagger_tag). + +-export_type([swagger_tag/0, + encode/1, + decode/1]). + +-type swagger_tag() :: + #{ 'id' => integer(), + 'name' => binary() + }. + +encode(#{ 'id' := Id, + 'name' := Name + }) -> + #{ 'id' => Id, + 'name' => Name + } diff --git a/samples/client/petstore/erlang-client/src/swagger_user.erl b/samples/client/petstore/erlang-client/src/swagger_user.erl new file mode 100644 index 00000000000..8c82c40488e --- /dev/null +++ b/samples/client/petstore/erlang-client/src/swagger_user.erl @@ -0,0 +1,35 @@ +-module(swagger_user). + +-export_type([swagger_user/0, + encode/1, + decode/1]). + +-type swagger_user() :: + #{ 'id' => integer(), + 'username' => binary(), + 'firstName' => binary(), + 'lastName' => binary(), + 'email' => binary(), + 'password' => binary(), + 'phone' => binary(), + 'userStatus' => integer() + }. + +encode(#{ 'id' := Id, + 'username' := Username, + 'firstName' := FirstName, + 'lastName' := LastName, + 'email' := Email, + 'password' := Password, + 'phone' := Phone, + 'userStatus' := UserStatus + }) -> + #{ 'id' => Id, + 'username' => Username, + 'firstName' => FirstName, + 'lastName' => LastName, + 'email' => Email, + 'password' => Password, + 'phone' => Phone, + 'userStatus' => UserStatus + } diff --git a/samples/client/petstore/erlang-client/src/swagger_user_api.erl b/samples/client/petstore/erlang-client/src/swagger_user_api.erl new file mode 100644 index 00000000000..fe2a84d78a8 --- /dev/null +++ b/samples/client/petstore/erlang-client/src/swagger_user_api.erl @@ -0,0 +1,165 @@ +-module(swagger_user_api). + +-export([create_user/1, + create_users_with_array_input/1, + create_users_with_list_input/1, + delete_user/1, + get_user_by_name/1, + login_user/2, + logout_user/0, + update_user/2]). + +-define(BASE_URL, <<"http://petstore.swagger.io/v2">>). + +%% @doc Create user +%% This can only be done by the logged in user. +-spec create_user(swagger_user:swagger_user()) -> ok | {error, integer()}. +create_user(Body) -> + Method = post, + Path = ["/user"], + QS = [], + Headers = [], + Body1 = Body, + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, _RespHeaders, _ClientRef} -> + ok; + {ok, Status, _RespHeaders, _ClientRef} -> + {error, Status} + end. + +%% @doc Creates list of users with given input array +-spec create_users_with_array_input(list()) -> ok | {error, integer()}. +create_users_with_array_input(Body) -> + Method = post, + Path = ["/user/createWithArray"], + QS = [], + Headers = [], + Body1 = Body, + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, _RespHeaders, _ClientRef} -> + ok; + {ok, Status, _RespHeaders, _ClientRef} -> + {error, Status} + end. + +%% @doc Creates list of users with given input array +-spec create_users_with_list_input(list()) -> ok | {error, integer()}. +create_users_with_list_input(Body) -> + Method = post, + Path = ["/user/createWithList"], + QS = [], + Headers = [], + Body1 = Body, + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, _RespHeaders, _ClientRef} -> + ok; + {ok, Status, _RespHeaders, _ClientRef} -> + {error, Status} + end. + +%% @doc Delete user +%% This can only be done by the logged in user. +-spec delete_user(binary()) -> ok | {error, integer()}. +delete_user(Username) -> + Method = delete, + Path = ["/user/", Username, ""], + QS = [], + Headers = [], + Body1 = [], + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, _RespHeaders, _ClientRef} -> + ok; + {ok, Status, _RespHeaders, _ClientRef} -> + {error, Status} + end. + +%% @doc Get user by user name +-spec get_user_by_name(binary()) -> {ok, list(), swagger_user:swagger_user()} | {error, string()}. +get_user_by_name(Username) -> + Method = get, + Path = ["/user/", Username, ""], + QS = [], + Headers = [], + Body1 = [], + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, RespHeaders, ClientRef} -> + {ok, Body} = hackney:body(ClientRef), + {ok, RespHeaders, jsx:decode(Body, [returns_maps, {labels, attempt_atom}])}; + {ok, 400, _RespHeaders, _ClientRef} -> + {error, "Invalid username supplied"}; + {ok, 404, _RespHeaders, _ClientRef} -> + {error, "User not found"} + end. + +%% @doc Logs user into the system +-spec login_user(binary(), binary()) -> {ok, list(), binary()} | {error, string()}. +login_user(Username, Password) -> + Method = get, + Path = ["/user/login"], + QS = lists:flatten([{<<"username">>, Username}, {<<"password">>, Password}]), + Headers = [], + Body1 = [], + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, RespHeaders, ClientRef} -> + {ok, Body} = hackney:body(ClientRef), + {ok, RespHeaders, jsx:decode(Body, [returns_maps, {labels, attempt_atom}])}; + {ok, 400, _RespHeaders, _ClientRef} -> + {error, "Invalid username/password supplied"} + end. + +%% @doc Logs out current logged in user session +-spec logout_user() -> ok | {error, integer()}. +logout_user() -> + Method = get, + Path = ["/user/logout"], + QS = [], + Headers = [], + Body1 = [], + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, _RespHeaders, _ClientRef} -> + ok; + {ok, Status, _RespHeaders, _ClientRef} -> + {error, Status} + end. + +%% @doc Updated user +%% This can only be done by the logged in user. +-spec update_user(binary(), swagger_user:swagger_user()) -> ok | {error, integer()}. +update_user(Username, Body) -> + Method = put, + Path = ["/user/", Username, ""], + QS = [], + Headers = [], + Body1 = Body, + Opts = [], + Url = hackney_url:make_url(?BASE_URL, Path, QS), + + case hackney:request(Method, Url, Headers, Body1, Opts) of + {ok, 200, _RespHeaders, _ClientRef} -> + ok; + {ok, Status, _RespHeaders, _ClientRef} -> + {error, Status} + end. + + diff --git a/samples/client/petstore/haskell-http-client/README.md b/samples/client/petstore/haskell-http-client/README.md index 2f2a6b4ca70..e42023ce834 100644 --- a/samples/client/petstore/haskell-http-client/README.md +++ b/samples/client/petstore/haskell-http-client/README.md @@ -48,11 +48,6 @@ haskell-http-client * Model Inheritance -* Default Parameter Values - -* Enum Parameters - - This is beta software; other cases may not be supported. ### Codegen "additional properties" parameters @@ -67,10 +62,11 @@ These options allow some customization of the code generation process. | allowToJsonNulls | allow emitting JSON Null during model encoding to JSON | false | false | | dateFormat | format string used to parse/render a date | %Y-%m-%d | %Y-%m-%d | | dateTimeFormat | format string used to parse/render a datetime. (Defaults to [formatISO8601Millis][1] when not provided) | | | +| generateEnums | Generate specific datatypes for swagger enums | true | true | | generateFormUrlEncodedInstances | Generate FromForm/ToForm instances for models used by x-www-form-urlencoded operations (model fields must be primitive types) | true | true | | generateLenses | Generate Lens optics for Models | true | true | | generateModelConstructors | Generate smart constructors (only supply required fields) for models | true | true | -| inlineConsumesContentTypes | Inline (hardcode) the content-type on operations that do not have multiple content-types (Consumes) | false | false | +| inlineMimeTypes | Inline (hardcode) the content-type and accept parameters on operations, when there is only 1 option | false | false | | modelDeriving | Additional classes to include in the deriving() clause of Models | | | | strictFields | Add strictness annotations to all model fields | true | true | | useMonadLogger | Use the monad-logger package to provide logging (if instead false, use the katip logging package) | false | false | @@ -184,11 +180,17 @@ config0 <- withStdoutLogging =<< newConfig let config = config0 `addAuthMethod` AuthOAuthFoo "secret-key" -let addFooRequest = addFoo MimeJSON foomodel requiredparam1 requiredparam2 +let addFooRequest = + addFoo + (ContentType MimeJSON) + (Accept MimeXML) + (ParamBar paramBar) + (ParamQux paramQux) + modelBaz `applyOptionalParam` FooId 1 `applyOptionalParam` FooName "name" `setHeader` [("qux_header","xxyy")] -addFooResult <- dispatchMime mgr config addFooRequest MimeXML +addFooResult <- dispatchMime mgr config addFooRequest ``` -See the example app and the haddocks for details. \ No newline at end of file +See the example app and the haddocks for details. diff --git a/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-API.html b/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-API.html index 4390d97a497..4b1d0188d09 100644 --- a/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-API.html +++ b/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-API.html @@ -1,4 +1,4 @@ SwaggerPetstore.API

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Safe HaskellNone
LanguageHaskell2010

SwaggerPetstore.API

Description

 

Synopsis

Operations

AnotherFake

testSpecialTags

testSpecialTags Source #

Arguments

:: (Consumes TestSpecialTags contentType, MimeRender contentType Client) 
=> contentType

request content-type (MimeType)

-> Client

"body" - client model

-> SwaggerPetstoreRequest TestSpecialTags contentType Client 
PATCH /another-fake/dummy

To test special tags

To test special tags

data TestSpecialTags Source #

Instances

Fake

fakeOuterBooleanSerialize

fakeOuterBooleanSerialize Source #

Arguments

:: Consumes FakeOuterBooleanSerialize contentType 
=> contentType

request content-type (MimeType)

-> SwaggerPetstoreRequest FakeOuterBooleanSerialize contentType OuterBoolean 
POST /fake/outer/boolean

Test serialization of outer boolean types

fakeOuterCompositeSerialize

fakeOuterCompositeSerialize Source #

Arguments

:: Consumes FakeOuterCompositeSerialize contentType 
=> contentType

request content-type (MimeType)

-> SwaggerPetstoreRequest FakeOuterCompositeSerialize contentType OuterComposite 
POST /fake/outer/composite

Test serialization of object with outer number type

fakeOuterNumberSerialize

fakeOuterNumberSerialize Source #

Arguments

:: Consumes FakeOuterNumberSerialize contentType 
=> contentType

request content-type (MimeType)

-> SwaggerPetstoreRequest FakeOuterNumberSerialize contentType OuterNumber 
POST /fake/outer/number

Test serialization of outer number types

fakeOuterStringSerialize

fakeOuterStringSerialize Source #

Arguments

:: Consumes FakeOuterStringSerialize contentType 
=> contentType

request content-type (MimeType)

-> SwaggerPetstoreRequest FakeOuterStringSerialize contentType OuterString 
POST /fake/outer/string

Test serialization of outer string types

testClientModel

testClientModel Source #

Arguments

:: (Consumes TestClientModel contentType, MimeRender contentType Client) 
=> contentType

request content-type (MimeType)

-> Client

"body" - client model

-> SwaggerPetstoreRequest TestClientModel contentType Client 
PATCH /fake

To test "client" model

To test "client" model

data TestClientModel Source #

Instances

testEndpointParameters

testEndpointParameters Source #

Arguments

:: Consumes TestEndpointParameters contentType 
=> contentType

request content-type (MimeType)

-> Number

"number" - None

-> ParamDouble

"double" - None

-> PatternWithoutDelimiter

"patternWithoutDelimiter" - None

-> Byte

"byte" - None

-> SwaggerPetstoreRequest TestEndpointParameters contentType res 
POST /fake

Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트

Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트

AuthMethod: AuthBasicHttpBasicTest

Note: Has Produces instances, but no response schema

data TestEndpointParameters Source #

Instances

Produces TestEndpointParameters MimeXmlCharsetutf8 Source #
application/xml; charset=utf-8
Produces TestEndpointParameters MimeJsonCharsetutf8 Source #
application/json; charset=utf-8
Consumes TestEndpointParameters MimeXmlCharsetutf8 Source #
application/xml; charset=utf-8
Consumes TestEndpointParameters MimeJsonCharsetutf8 Source #
application/json; charset=utf-8
HasOptionalParam TestEndpointParameters Password Source #

Optional Param "password" - None

HasOptionalParam TestEndpointParameters ParamString Source #

Optional Param "string" - None

HasOptionalParam TestEndpointParameters ParamInteger Source #

Optional Param "integer" - None

HasOptionalParam TestEndpointParameters ParamFloat Source #

Optional Param "float" - None

HasOptionalParam TestEndpointParameters ParamDateTime Source #

Optional Param "dateTime" - None

HasOptionalParam TestEndpointParameters ParamDate Source #

Optional Param "date" - None

HasOptionalParam TestEndpointParameters ParamBinary Source #

Optional Param "binary" - None

HasOptionalParam TestEndpointParameters Int64 Source #

Optional Param "int64" - None

HasOptionalParam TestEndpointParameters Int32 Source #

Optional Param "int32" - None

HasOptionalParam TestEndpointParameters Callback Source #

Optional Param "callback" - None

testEnumParameters

testEnumParameters Source #

Arguments

:: Consumes TestEnumParameters contentType 
=> contentType

request content-type (MimeType)

-> SwaggerPetstoreRequest TestEnumParameters contentType res 
GET /fake

To test enum parameters

To test enum parameters

Note: Has Produces instances, but no response schema

data TestEnumParameters Source #

Instances

Produces TestEnumParameters MimeAny Source #
*/*
Consumes TestEnumParameters MimeAny Source #
*/*
HasOptionalParam TestEnumParameters EnumQueryStringArray Source #

Optional Param "enum_query_string_array" - Query parameter enum test (string array)

HasOptionalParam TestEnumParameters EnumQueryString Source #

Optional Param "enum_query_string" - Query parameter enum test (string)

HasOptionalParam TestEnumParameters EnumQueryInteger Source #

Optional Param "enum_query_integer" - Query parameter enum test (double)

HasOptionalParam TestEnumParameters EnumQueryDouble Source #

Optional Param "enum_query_double" - Query parameter enum test (double)

HasOptionalParam TestEnumParameters EnumHeaderStringArray Source #

Optional Param "enum_header_string_array" - Header parameter enum test (string array)

HasOptionalParam TestEnumParameters EnumHeaderString Source #

Optional Param "enum_header_string" - Header parameter enum test (string)

HasOptionalParam TestEnumParameters EnumFormStringArray Source #

Optional Param "enum_form_string_array" - Form parameter enum test (string array)

HasOptionalParam TestEnumParameters EnumFormString Source #

Optional Param "enum_form_string" - Form parameter enum test (string)

testJsonFormData

testJsonFormData Source #

Arguments

:: Consumes TestJsonFormData contentType 
=> contentType

request content-type (MimeType)

-> Param

"param" - field1

-> Param2

"param2" - field2

-> SwaggerPetstoreRequest TestJsonFormData contentType NoContent 
GET /fake/jsonFormData

test json serialization of form data

FakeClassnameTags123

testClassname

testClassname Source #

Arguments

:: (Consumes TestClassname contentType, MimeRender contentType Client) 
=> contentType

request content-type (MimeType)

-> Client

"body" - client model

-> SwaggerPetstoreRequest TestClassname contentType Client 
PATCH /fake_classname_test

To test class name in snake case

AuthMethod: AuthApiKeyApiKeyQuery

data TestClassname Source #

Instances

Produces TestClassname MimeJSON Source #
application/json
Consumes TestClassname MimeJSON Source #
application/json
HasBodyParam TestClassname Client Source #

Body Param "body" - client model

Methods

setBodyParam :: (Consumes TestClassname contentType, MimeRender contentType Client) => SwaggerPetstoreRequest TestClassname contentType res -> Client -> SwaggerPetstoreRequest TestClassname contentType res Source #

Pet

addPet

addPet Source #

Arguments

:: (Consumes AddPet contentType, MimeRender contentType Pet) 
=> contentType

request content-type (MimeType)

-> Pet

"body" - Pet object that needs to be added to the store

-> SwaggerPetstoreRequest AddPet contentType res 
POST /pet

Add a new pet to the store

AuthMethod: AuthOAuthPetstoreAuth

Note: Has Produces instances, but no response schema

data AddPet Source #

Instances

Produces AddPet MimeXML Source #
application/xml
Produces AddPet MimeJSON Source #
application/json
Consumes AddPet MimeXML Source #
application/xml
Consumes AddPet MimeJSON Source #
application/json
HasBodyParam AddPet Pet Source #

Body Param "body" - Pet object that needs to be added to the store

Methods

setBodyParam :: (Consumes AddPet contentType, MimeRender contentType Pet) => SwaggerPetstoreRequest AddPet contentType res -> Pet -> SwaggerPetstoreRequest AddPet contentType res Source #

deletePet

deletePet Source #

Arguments

:: PetId

"petId" - Pet id to delete

-> SwaggerPetstoreRequest DeletePet MimeNoContent res 
DELETE /pet/{petId}

Deletes a pet

AuthMethod: AuthOAuthPetstoreAuth

Note: Has Produces instances, but no response schema

findPetsByStatus

findPetsByStatus Source #

Arguments

:: Status

"status" - Status values that need to be considered for filter

-> SwaggerPetstoreRequest FindPetsByStatus MimeNoContent [Pet] 
GET /pet/findByStatus

Finds Pets by status

Multiple status values can be provided with comma separated strings

AuthMethod: AuthOAuthPetstoreAuth

findPetsByTags

findPetsByTags Source #

Arguments

:: Tags

"tags" - Tags to filter by

-> SwaggerPetstoreRequest FindPetsByTags MimeNoContent [Pet] 

Deprecated:

GET /pet/findByTags

Finds Pets by tags

Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.

AuthMethod: AuthOAuthPetstoreAuth

getPetById

getPetById Source #

Arguments

:: PetId

"petId" - ID of pet to return

-> SwaggerPetstoreRequest GetPetById MimeNoContent Pet 
GET /pet/{petId}

Find pet by ID

Returns a single pet

AuthMethod: AuthApiKeyApiKey

data GetPetById Source #

Instances

updatePet

updatePet Source #

Arguments

:: (Consumes UpdatePet contentType, MimeRender contentType Pet) 
=> contentType

request content-type (MimeType)

-> Pet

"body" - Pet object that needs to be added to the store

-> SwaggerPetstoreRequest UpdatePet contentType res 
PUT /pet

Update an existing pet

AuthMethod: AuthOAuthPetstoreAuth

Note: Has Produces instances, but no response schema

data UpdatePet Source #

Instances

Produces UpdatePet MimeXML Source #
application/xml
Produces UpdatePet MimeJSON Source #
application/json
Consumes UpdatePet MimeXML Source #
application/xml
Consumes UpdatePet MimeJSON Source #
application/json
HasBodyParam UpdatePet Pet Source #

Body Param "body" - Pet object that needs to be added to the store

Methods

setBodyParam :: (Consumes UpdatePet contentType, MimeRender contentType Pet) => SwaggerPetstoreRequest UpdatePet contentType res -> Pet -> SwaggerPetstoreRequest UpdatePet contentType res Source #

updatePetWithForm

updatePetWithForm Source #

Arguments

:: Consumes UpdatePetWithForm contentType 
=> contentType

request content-type (MimeType)

-> PetId

"petId" - ID of pet that needs to be updated

-> SwaggerPetstoreRequest UpdatePetWithForm contentType res 
POST /pet/{petId}

Updates a pet in the store with form data

AuthMethod: AuthOAuthPetstoreAuth

Note: Has Produces instances, but no response schema

uploadFile

uploadFile Source #

Arguments

:: Consumes UploadFile contentType 
=> contentType

request content-type (MimeType)

-> PetId

"petId" - ID of pet to update

-> SwaggerPetstoreRequest UploadFile contentType ApiResponse 
POST /pet/{petId}/uploadImage

uploads an image

AuthMethod: AuthOAuthPetstoreAuth

data UploadFile Source #

Instances

Produces UploadFile MimeJSON Source #
application/json
Consumes UploadFile MimeMultipartFormData Source #
multipart/form-data
HasOptionalParam UploadFile File Source #

Optional Param "file" - file to upload

HasOptionalParam UploadFile AdditionalMetadata Source #

Optional Param "additionalMetadata" - Additional data to pass to server

Store

deleteOrder

deleteOrder Source #

Arguments

:: OrderIdText

"orderId" - ID of the order that needs to be deleted

-> SwaggerPetstoreRequest DeleteOrder MimeNoContent res 
DELETE /store/order/{order_id}

Delete purchase order by ID

For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors

Note: Has Produces instances, but no response schema

data DeleteOrder Source #

Instances

getInventory

getInventory :: SwaggerPetstoreRequest GetInventory MimeNoContent (Map String Int) Source #

GET /store/inventory

Returns pet inventories by status

Returns a map of status codes to quantities

AuthMethod: AuthApiKeyApiKey

data GetInventory Source #

Instances

getOrderById

getOrderById Source #

Arguments

:: OrderId

"orderId" - ID of pet that needs to be fetched

-> SwaggerPetstoreRequest GetOrderById MimeNoContent Order 
GET /store/order/{order_id}

Find purchase order by ID

For valid response try integer IDs with value 5 or 10. Other values will generated exceptions

placeOrder

placeOrder Source #

Arguments

:: (Consumes PlaceOrder contentType, MimeRender contentType Order) 
=> contentType

request content-type (MimeType)

-> Order

"body" - order placed for purchasing the pet

-> SwaggerPetstoreRequest PlaceOrder contentType Order 
POST /store/order

Place an order for a pet

data PlaceOrder Source #

Instances

Produces PlaceOrder MimeXML Source #
application/xml
Produces PlaceOrder MimeJSON Source #
application/json
HasBodyParam PlaceOrder Order Source #

Body Param "body" - order placed for purchasing the pet

Methods

setBodyParam :: (Consumes PlaceOrder contentType, MimeRender contentType Order) => SwaggerPetstoreRequest PlaceOrder contentType res -> Order -> SwaggerPetstoreRequest PlaceOrder contentType res Source #

User

createUser

createUser Source #

Arguments

:: (Consumes CreateUser contentType, MimeRender contentType User) 
=> contentType

request content-type (MimeType)

-> User

"body" - Created user object

-> SwaggerPetstoreRequest CreateUser contentType res 
POST /user

Create user

This can only be done by the logged in user.

Note: Has Produces instances, but no response schema

data CreateUser Source #

Instances

Produces CreateUser MimeXML Source #
application/xml
Produces CreateUser MimeJSON Source #
application/json
HasBodyParam CreateUser User Source #

Body Param "body" - Created user object

Methods

setBodyParam :: (Consumes CreateUser contentType, MimeRender contentType User) => SwaggerPetstoreRequest CreateUser contentType res -> User -> SwaggerPetstoreRequest CreateUser contentType res Source #

createUsersWithArrayInput

createUsersWithArrayInput Source #

Arguments

:: (Consumes CreateUsersWithArrayInput contentType, MimeRender contentType Body) 
=> contentType

request content-type (MimeType)

-> Body

"body" - List of user object

-> SwaggerPetstoreRequest CreateUsersWithArrayInput contentType res 
POST /user/createWithArray

Creates list of users with given input array

Note: Has Produces instances, but no response schema

createUsersWithListInput

createUsersWithListInput Source #

Arguments

:: (Consumes CreateUsersWithListInput contentType, MimeRender contentType Body) 
=> contentType

request content-type (MimeType)

-> Body

"body" - List of user object

-> SwaggerPetstoreRequest CreateUsersWithListInput contentType res 
POST /user/createWithList

Creates list of users with given input array

Note: Has Produces instances, but no response schema

deleteUser

deleteUser Source #

Arguments

:: Username

"username" - The name that needs to be deleted

-> SwaggerPetstoreRequest DeleteUser MimeNoContent res 
DELETE /user/{username}

Delete user

This can only be done by the logged in user.

Note: Has Produces instances, but no response schema

data DeleteUser Source #

Instances

getUserByName

getUserByName Source #

Arguments

:: Username

"username" - The name that needs to be fetched. Use user1 for testing.

-> SwaggerPetstoreRequest GetUserByName MimeNoContent User 
GET /user/{username}

Get user by user name

loginUser

loginUser Source #

Arguments

:: Username

"username" - The user name for login

-> Password

"password" - The password for login in clear text

-> SwaggerPetstoreRequest LoginUser MimeNoContent Text 
GET /user/login

Logs user into the system

data LoginUser Source #

Instances

logoutUser

logoutUser :: SwaggerPetstoreRequest LogoutUser MimeNoContent res Source #

GET /user/logout

Logs out current logged in user session

Note: Has Produces instances, but no response schema

data LogoutUser Source #

Instances

updateUser

updateUser Source #

Arguments

:: (Consumes UpdateUser contentType, MimeRender contentType User) 
=> contentType

request content-type (MimeType)

-> Username

"username" - name that need to be deleted

-> User

"body" - Updated user object

-> SwaggerPetstoreRequest UpdateUser contentType res 
PUT /user/{username}

Updated user

This can only be done by the logged in user.

Note: Has Produces instances, but no response schema

data UpdateUser Source #

Instances

Produces UpdateUser MimeXML Source #
application/xml
Produces UpdateUser MimeJSON Source #
application/json
HasBodyParam UpdateUser User Source #

Body Param "body" - Updated user object

Methods

setBodyParam :: (Consumes UpdateUser contentType, MimeRender contentType User) => SwaggerPetstoreRequest UpdateUser contentType res -> User -> SwaggerPetstoreRequest UpdateUser contentType res Source #

Parameter newtypes

newtype Body Source #

Constructors

Body 

Fields

newtype Byte Source #

Constructors

Byte 

Fields

Instances

Eq Byte Source # 

Methods

(==) :: Byte -> Byte -> Bool #

(/=) :: Byte -> Byte -> Bool #

Show Byte Source # 

Methods

showsPrec :: Int -> Byte -> ShowS #

show :: Byte -> String #

showList :: [Byte] -> ShowS #

newtype File Source #

Constructors

File 

Fields

Instances

Eq File Source # 

Methods

(==) :: File -> File -> Bool #

(/=) :: File -> File -> Bool #

Show File Source # 

Methods

showsPrec :: Int -> File -> ShowS #

show :: File -> String #

showList :: [File] -> ShowS #

HasOptionalParam UploadFile File Source #

Optional Param "file" - file to upload

newtype Name2 Source #

Constructors

Name2 

Fields

newtype Number Source #

Constructors

Number 

Fields

Instances

newtype OrderId Source #

Constructors

OrderId 

Fields

newtype Param Source #

Constructors

Param 

Fields

Instances

Eq Param Source # 

Methods

(==) :: Param -> Param -> Bool #

(/=) :: Param -> Param -> Bool #

Show Param Source # 

Methods

showsPrec :: Int -> Param -> ShowS #

show :: Param -> String #

showList :: [Param] -> ShowS #

newtype Param2 Source #

Constructors

Param2 

Fields

Instances

newtype PetId Source #

Constructors

PetId 

Fields

Instances

Eq PetId Source # 

Methods

(==) :: PetId -> PetId -> Bool #

(/=) :: PetId -> PetId -> Bool #

Show PetId Source # 

Methods

showsPrec :: Int -> PetId -> ShowS #

show :: PetId -> String #

showList :: [PetId] -> ShowS #

newtype Status Source #

Constructors

Status 

Fields

Instances

newtype Tags Source #

Constructors

Tags 

Fields

Instances

Eq Tags Source # 

Methods

(==) :: Tags -> Tags -> Bool #

(/=) :: Tags -> Tags -> Bool #

Show Tags Source # 

Methods

showsPrec :: Int -> Tags -> ShowS #

show :: Tags -> String #

showList :: [Tags] -> ShowS #

newtype Username Source #

Constructors

Username 

Fields

Auth Methods

AuthApiKeyApiKey

AuthApiKeyApiKeyQuery

AuthBasicHttpBasicTest

AuthOAuthPetstoreAuth

Custom Mime Types

MimeJsonCharsetutf8

MimeXmlCharsetutf8

\ No newline at end of file +

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Safe HaskellNone
LanguageHaskell2010

SwaggerPetstore.API

Description

 

Synopsis

Operations

AnotherFake

testSpecialTags

testSpecialTags Source #

Arguments

:: (Consumes TestSpecialTags contentType, MimeRender contentType Client) 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> Client

"body" - client model

-> SwaggerPetstoreRequest TestSpecialTags contentType Client accept 
PATCH /another-fake/dummy

To test special tags

To test special tags

data TestSpecialTags Source #

Instances

Produces TestSpecialTags MimeJSON Source #
application/json
Consumes TestSpecialTags MimeJSON Source #
application/json
HasBodyParam TestSpecialTags Client Source #

Body Param "body" - client model

Methods

setBodyParam :: (Consumes TestSpecialTags contentType, MimeRender contentType Client) => SwaggerPetstoreRequest TestSpecialTags contentType res accept -> Client -> SwaggerPetstoreRequest TestSpecialTags contentType res accept Source #

Fake

fakeOuterBooleanSerialize

fakeOuterBooleanSerialize Source #

Arguments

:: Consumes FakeOuterBooleanSerialize contentType 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> SwaggerPetstoreRequest FakeOuterBooleanSerialize contentType OuterBoolean accept 
POST /fake/outer/boolean

Test serialization of outer boolean types

fakeOuterCompositeSerialize

fakeOuterCompositeSerialize Source #

Arguments

:: Consumes FakeOuterCompositeSerialize contentType 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> SwaggerPetstoreRequest FakeOuterCompositeSerialize contentType OuterComposite accept 
POST /fake/outer/composite

Test serialization of object with outer number type

fakeOuterNumberSerialize

fakeOuterNumberSerialize Source #

Arguments

:: Consumes FakeOuterNumberSerialize contentType 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> SwaggerPetstoreRequest FakeOuterNumberSerialize contentType OuterNumber accept 
POST /fake/outer/number

Test serialization of outer number types

fakeOuterStringSerialize

fakeOuterStringSerialize Source #

Arguments

:: Consumes FakeOuterStringSerialize contentType 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> SwaggerPetstoreRequest FakeOuterStringSerialize contentType OuterString accept 
POST /fake/outer/string

Test serialization of outer string types

testClientModel

testClientModel Source #

Arguments

:: (Consumes TestClientModel contentType, MimeRender contentType Client) 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> Client

"body" - client model

-> SwaggerPetstoreRequest TestClientModel contentType Client accept 
PATCH /fake

To test "client" model

To test "client" model

data TestClientModel Source #

Instances

Produces TestClientModel MimeJSON Source #
application/json
Consumes TestClientModel MimeJSON Source #
application/json
HasBodyParam TestClientModel Client Source #

Body Param "body" - client model

Methods

setBodyParam :: (Consumes TestClientModel contentType, MimeRender contentType Client) => SwaggerPetstoreRequest TestClientModel contentType res accept -> Client -> SwaggerPetstoreRequest TestClientModel contentType res accept Source #

testEndpointParameters

testEndpointParameters Source #

Arguments

:: Consumes TestEndpointParameters contentType 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> Number

"number" - None

-> ParamDouble

"double" - None

-> PatternWithoutDelimiter

"patternWithoutDelimiter" - None

-> Byte

"byte" - None

-> SwaggerPetstoreRequest TestEndpointParameters contentType res accept 
POST /fake

Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트

Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트

AuthMethod: AuthBasicHttpBasicTest

Note: Has Produces instances, but no response schema

data TestEndpointParameters Source #

Instances

Produces TestEndpointParameters MimeXmlCharsetutf8 Source #
application/xml; charset=utf-8
Produces TestEndpointParameters MimeJsonCharsetutf8 Source #
application/json; charset=utf-8
Consumes TestEndpointParameters MimeXmlCharsetutf8 Source #
application/xml; charset=utf-8
Consumes TestEndpointParameters MimeJsonCharsetutf8 Source #
application/json; charset=utf-8
HasOptionalParam TestEndpointParameters Password Source #

Optional Param "password" - None

HasOptionalParam TestEndpointParameters ParamString Source #

Optional Param "string" - None

HasOptionalParam TestEndpointParameters ParamInteger Source #

Optional Param "integer" - None

HasOptionalParam TestEndpointParameters ParamFloat Source #

Optional Param "float" - None

HasOptionalParam TestEndpointParameters ParamDateTime Source #

Optional Param "dateTime" - None

HasOptionalParam TestEndpointParameters ParamDate Source #

Optional Param "date" - None

HasOptionalParam TestEndpointParameters ParamBinary Source #

Optional Param "binary" - None

HasOptionalParam TestEndpointParameters Int64 Source #

Optional Param "int64" - None

HasOptionalParam TestEndpointParameters Int32 Source #

Optional Param "int32" - None

HasOptionalParam TestEndpointParameters Callback Source #

Optional Param "callback" - None

testEnumParameters

testEnumParameters Source #

Arguments

:: Consumes TestEnumParameters contentType 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> SwaggerPetstoreRequest TestEnumParameters contentType res accept 
GET /fake

To test enum parameters

To test enum parameters

Note: Has Produces instances, but no response schema

data TestEnumParameters Source #

Instances

Produces TestEnumParameters MimeAny Source #
*/*
Consumes TestEnumParameters MimeAny Source #
*/*
HasOptionalParam TestEnumParameters EnumQueryStringArray Source #

Optional Param "enum_query_string_array" - Query parameter enum test (string array)

HasOptionalParam TestEnumParameters EnumQueryString Source #

Optional Param "enum_query_string" - Query parameter enum test (string)

HasOptionalParam TestEnumParameters EnumQueryInteger Source #

Optional Param "enum_query_integer" - Query parameter enum test (double)

HasOptionalParam TestEnumParameters EnumQueryDouble Source #

Optional Param "enum_query_double" - Query parameter enum test (double)

HasOptionalParam TestEnumParameters EnumHeaderStringArray Source #

Optional Param "enum_header_string_array" - Header parameter enum test (string array)

HasOptionalParam TestEnumParameters EnumHeaderString Source #

Optional Param "enum_header_string" - Header parameter enum test (string)

HasOptionalParam TestEnumParameters EnumFormStringArray Source #

Optional Param "enum_form_string_array" - Form parameter enum test (string array)

HasOptionalParam TestEnumParameters EnumFormString Source #

Optional Param "enum_form_string" - Form parameter enum test (string)

testInlineAdditionalProperties

testInlineAdditionalProperties Source #

Arguments

:: (Consumes TestInlineAdditionalProperties contentType, MimeRender contentType Value) 
=> ContentType contentType

request content-type (MimeType)

-> Value

"param" - request body

-> SwaggerPetstoreRequest TestInlineAdditionalProperties contentType NoContent MimeNoContent 
POST /fake/inline-additionalProperties

test inline additionalProperties

testJsonFormData

testJsonFormData Source #

Arguments

:: Consumes TestJsonFormData contentType 
=> ContentType contentType

request content-type (MimeType)

-> Param

"param" - field1

-> Param2

"param2" - field2

-> SwaggerPetstoreRequest TestJsonFormData contentType NoContent MimeNoContent 
GET /fake/jsonFormData

test json serialization of form data

FakeClassnameTags123

testClassname

testClassname Source #

Arguments

:: (Consumes TestClassname contentType, MimeRender contentType Client) 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> Client

"body" - client model

-> SwaggerPetstoreRequest TestClassname contentType Client accept 
PATCH /fake_classname_test

To test class name in snake case

AuthMethod: AuthApiKeyApiKeyQuery

data TestClassname Source #

Instances

Produces TestClassname MimeJSON Source #
application/json
Consumes TestClassname MimeJSON Source #
application/json
HasBodyParam TestClassname Client Source #

Body Param "body" - client model

Methods

setBodyParam :: (Consumes TestClassname contentType, MimeRender contentType Client) => SwaggerPetstoreRequest TestClassname contentType res accept -> Client -> SwaggerPetstoreRequest TestClassname contentType res accept Source #

Pet

addPet

addPet Source #

Arguments

:: (Consumes AddPet contentType, MimeRender contentType Pet) 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> Pet

"body" - Pet object that needs to be added to the store

-> SwaggerPetstoreRequest AddPet contentType res accept 
POST /pet

Add a new pet to the store

AuthMethod: AuthOAuthPetstoreAuth

Note: Has Produces instances, but no response schema

data AddPet Source #

Instances

Produces AddPet MimeXML Source #
application/xml
Produces AddPet MimeJSON Source #
application/json
Consumes AddPet MimeXML Source #
application/xml
Consumes AddPet MimeJSON Source #
application/json
HasBodyParam AddPet Pet Source #

Body Param "body" - Pet object that needs to be added to the store

Methods

setBodyParam :: (Consumes AddPet contentType, MimeRender contentType Pet) => SwaggerPetstoreRequest AddPet contentType res accept -> Pet -> SwaggerPetstoreRequest AddPet contentType res accept Source #

deletePet

deletePet Source #

Arguments

:: Accept accept

request accept (MimeType)

-> PetId

"petId" - Pet id to delete

-> SwaggerPetstoreRequest DeletePet MimeNoContent res accept 
DELETE /pet/{petId}

Deletes a pet

AuthMethod: AuthOAuthPetstoreAuth

Note: Has Produces instances, but no response schema

data DeletePet Source #

Instances

findPetsByStatus

findPetsByStatus Source #

Arguments

:: Accept accept

request accept (MimeType)

-> Status

"status" - Status values that need to be considered for filter

-> SwaggerPetstoreRequest FindPetsByStatus MimeNoContent [Pet] accept 
GET /pet/findByStatus

Finds Pets by status

Multiple status values can be provided with comma separated strings

AuthMethod: AuthOAuthPetstoreAuth

findPetsByTags

findPetsByTags Source #

Arguments

:: Accept accept

request accept (MimeType)

-> Tags

"tags" - Tags to filter by

-> SwaggerPetstoreRequest FindPetsByTags MimeNoContent [Pet] accept 

Deprecated:

GET /pet/findByTags

Finds Pets by tags

Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.

AuthMethod: AuthOAuthPetstoreAuth

getPetById

getPetById Source #

Arguments

:: Accept accept

request accept (MimeType)

-> PetId

"petId" - ID of pet to return

-> SwaggerPetstoreRequest GetPetById MimeNoContent Pet accept 
GET /pet/{petId}

Find pet by ID

Returns a single pet

AuthMethod: AuthApiKeyApiKey

data GetPetById Source #

Instances

updatePet

updatePet Source #

Arguments

:: (Consumes UpdatePet contentType, MimeRender contentType Pet) 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> Pet

"body" - Pet object that needs to be added to the store

-> SwaggerPetstoreRequest UpdatePet contentType res accept 
PUT /pet

Update an existing pet

AuthMethod: AuthOAuthPetstoreAuth

Note: Has Produces instances, but no response schema

data UpdatePet Source #

Instances

Produces UpdatePet MimeXML Source #
application/xml
Produces UpdatePet MimeJSON Source #
application/json
Consumes UpdatePet MimeXML Source #
application/xml
Consumes UpdatePet MimeJSON Source #
application/json
HasBodyParam UpdatePet Pet Source #

Body Param "body" - Pet object that needs to be added to the store

Methods

setBodyParam :: (Consumes UpdatePet contentType, MimeRender contentType Pet) => SwaggerPetstoreRequest UpdatePet contentType res accept -> Pet -> SwaggerPetstoreRequest UpdatePet contentType res accept Source #

updatePetWithForm

updatePetWithForm Source #

Arguments

:: Consumes UpdatePetWithForm contentType 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> PetId

"petId" - ID of pet that needs to be updated

-> SwaggerPetstoreRequest UpdatePetWithForm contentType res accept 
POST /pet/{petId}

Updates a pet in the store with form data

AuthMethod: AuthOAuthPetstoreAuth

Note: Has Produces instances, but no response schema

data UpdatePetWithForm Source #

Instances

Produces UpdatePetWithForm MimeXML Source #
application/xml
Produces UpdatePetWithForm MimeJSON Source #
application/json
Consumes UpdatePetWithForm MimeFormUrlEncoded Source #
application/x-www-form-urlencoded
HasOptionalParam UpdatePetWithForm StatusText Source #

Optional Param "status" - Updated status of the pet

HasOptionalParam UpdatePetWithForm Name2 Source #

Optional Param "name" - Updated name of the pet

uploadFile

uploadFile Source #

Arguments

:: Consumes UploadFile contentType 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> PetId

"petId" - ID of pet to update

-> SwaggerPetstoreRequest UploadFile contentType ApiResponse accept 
POST /pet/{petId}/uploadImage

uploads an image

AuthMethod: AuthOAuthPetstoreAuth

data UploadFile Source #

Instances

Produces UploadFile MimeJSON Source #
application/json
Consumes UploadFile MimeMultipartFormData Source #
multipart/form-data
HasOptionalParam UploadFile File Source #

Optional Param "file" - file to upload

Methods

applyOptionalParam :: SwaggerPetstoreRequest UploadFile contentType res accept -> File -> SwaggerPetstoreRequest UploadFile contentType res accept Source #

(-&-) :: SwaggerPetstoreRequest UploadFile contentType res accept -> File -> SwaggerPetstoreRequest UploadFile contentType res accept Source #

HasOptionalParam UploadFile AdditionalMetadata Source #

Optional Param "additionalMetadata" - Additional data to pass to server

Store

deleteOrder

deleteOrder Source #

Arguments

:: Accept accept

request accept (MimeType)

-> OrderIdText

"orderId" - ID of the order that needs to be deleted

-> SwaggerPetstoreRequest DeleteOrder MimeNoContent res accept 
DELETE /store/order/{order_id}

Delete purchase order by ID

For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors

Note: Has Produces instances, but no response schema

data DeleteOrder Source #

Instances

getInventory

getInventory Source #

Arguments

:: Accept accept

request accept (MimeType)

-> SwaggerPetstoreRequest GetInventory MimeNoContent (Map String Int) accept 
GET /store/inventory

Returns pet inventories by status

Returns a map of status codes to quantities

AuthMethod: AuthApiKeyApiKey

data GetInventory Source #

Instances

getOrderById

getOrderById Source #

Arguments

:: Accept accept

request accept (MimeType)

-> OrderId

"orderId" - ID of pet that needs to be fetched

-> SwaggerPetstoreRequest GetOrderById MimeNoContent Order accept 
GET /store/order/{order_id}

Find purchase order by ID

For valid response try integer IDs with value 5 or 10. Other values will generated exceptions

placeOrder

placeOrder Source #

Arguments

:: (Consumes PlaceOrder contentType, MimeRender contentType Order) 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> Order

"body" - order placed for purchasing the pet

-> SwaggerPetstoreRequest PlaceOrder contentType Order accept 
POST /store/order

Place an order for a pet

data PlaceOrder Source #

Instances

Produces PlaceOrder MimeXML Source #
application/xml
Produces PlaceOrder MimeJSON Source #
application/json
HasBodyParam PlaceOrder Order Source #

Body Param "body" - order placed for purchasing the pet

Methods

setBodyParam :: (Consumes PlaceOrder contentType, MimeRender contentType Order) => SwaggerPetstoreRequest PlaceOrder contentType res accept -> Order -> SwaggerPetstoreRequest PlaceOrder contentType res accept Source #

User

createUser

createUser Source #

Arguments

:: (Consumes CreateUser contentType, MimeRender contentType User) 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> User

"body" - Created user object

-> SwaggerPetstoreRequest CreateUser contentType res accept 
POST /user

Create user

This can only be done by the logged in user.

Note: Has Produces instances, but no response schema

data CreateUser Source #

Instances

Produces CreateUser MimeXML Source #
application/xml
Produces CreateUser MimeJSON Source #
application/json
HasBodyParam CreateUser User Source #

Body Param "body" - Created user object

Methods

setBodyParam :: (Consumes CreateUser contentType, MimeRender contentType User) => SwaggerPetstoreRequest CreateUser contentType res accept -> User -> SwaggerPetstoreRequest CreateUser contentType res accept Source #

createUsersWithArrayInput

createUsersWithArrayInput Source #

Arguments

:: (Consumes CreateUsersWithArrayInput contentType, MimeRender contentType Body) 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> Body

"body" - List of user object

-> SwaggerPetstoreRequest CreateUsersWithArrayInput contentType res accept 
POST /user/createWithArray

Creates list of users with given input array

Note: Has Produces instances, but no response schema

createUsersWithListInput

createUsersWithListInput Source #

Arguments

:: (Consumes CreateUsersWithListInput contentType, MimeRender contentType Body) 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> Body

"body" - List of user object

-> SwaggerPetstoreRequest CreateUsersWithListInput contentType res accept 
POST /user/createWithList

Creates list of users with given input array

Note: Has Produces instances, but no response schema

deleteUser

deleteUser Source #

Arguments

:: Accept accept

request accept (MimeType)

-> Username

"username" - The name that needs to be deleted

-> SwaggerPetstoreRequest DeleteUser MimeNoContent res accept 
DELETE /user/{username}

Delete user

This can only be done by the logged in user.

Note: Has Produces instances, but no response schema

data DeleteUser Source #

Instances

getUserByName

getUserByName Source #

Arguments

:: Accept accept

request accept (MimeType)

-> Username

"username" - The name that needs to be fetched. Use user1 for testing.

-> SwaggerPetstoreRequest GetUserByName MimeNoContent User accept 
GET /user/{username}

Get user by user name

loginUser

loginUser Source #

Arguments

:: Accept accept

request accept (MimeType)

-> Username

"username" - The user name for login

-> Password

"password" - The password for login in clear text

-> SwaggerPetstoreRequest LoginUser MimeNoContent Text accept 
GET /user/login

Logs user into the system

data LoginUser Source #

Instances

logoutUser

logoutUser Source #

Arguments

:: Accept accept

request accept (MimeType)

-> SwaggerPetstoreRequest LogoutUser MimeNoContent res accept 
GET /user/logout

Logs out current logged in user session

Note: Has Produces instances, but no response schema

data LogoutUser Source #

Instances

updateUser

updateUser Source #

Arguments

:: (Consumes UpdateUser contentType, MimeRender contentType User) 
=> ContentType contentType

request content-type (MimeType)

-> Accept accept

request accept (MimeType)

-> Username

"username" - name that need to be deleted

-> User

"body" - Updated user object

-> SwaggerPetstoreRequest UpdateUser contentType res accept 
PUT /user/{username}

Updated user

This can only be done by the logged in user.

Note: Has Produces instances, but no response schema

data UpdateUser Source #

Instances

Produces UpdateUser MimeXML Source #
application/xml
Produces UpdateUser MimeJSON Source #
application/json
HasBodyParam UpdateUser User Source #

Body Param "body" - Updated user object

Methods

setBodyParam :: (Consumes UpdateUser contentType, MimeRender contentType User) => SwaggerPetstoreRequest UpdateUser contentType res accept -> User -> SwaggerPetstoreRequest UpdateUser contentType res accept Source #

Parameter newtypes

newtype ApiKey Source #

Constructors

ApiKey 

Fields

Instances

newtype Body Source #

Constructors

Body 

Fields

Instances

Eq Body Source # 

Methods

(==) :: Body -> Body -> Bool #

(/=) :: Body -> Body -> Bool #

Show Body Source # 

Methods

showsPrec :: Int -> Body -> ShowS #

show :: Body -> String #

showList :: [Body] -> ShowS #

ToJSON Body Source # 
HasBodyParam CreateUsersWithListInput Body Source #

Body Param "body" - List of user object

HasBodyParam CreateUsersWithArrayInput Body Source #

Body Param "body" - List of user object

newtype Byte Source #

Constructors

Byte 

Fields

Instances

Eq Byte Source # 

Methods

(==) :: Byte -> Byte -> Bool #

(/=) :: Byte -> Byte -> Bool #

Show Byte Source # 

Methods

showsPrec :: Int -> Byte -> ShowS #

show :: Byte -> String #

showList :: [Byte] -> ShowS #

newtype File Source #

Constructors

File 

Fields

Instances

Eq File Source # 

Methods

(==) :: File -> File -> Bool #

(/=) :: File -> File -> Bool #

Show File Source # 

Methods

showsPrec :: Int -> File -> ShowS #

show :: File -> String #

showList :: [File] -> ShowS #

HasOptionalParam UploadFile File Source #

Optional Param "file" - file to upload

Methods

applyOptionalParam :: SwaggerPetstoreRequest UploadFile contentType res accept -> File -> SwaggerPetstoreRequest UploadFile contentType res accept Source #

(-&-) :: SwaggerPetstoreRequest UploadFile contentType res accept -> File -> SwaggerPetstoreRequest UploadFile contentType res accept Source #

newtype Int32 Source #

Constructors

Int32 

Fields

newtype Int64 Source #

Constructors

Int64 

Fields

newtype Name2 Source #

Constructors

Name2 

Fields

Instances

Eq Name2 Source # 

Methods

(==) :: Name2 -> Name2 -> Bool #

(/=) :: Name2 -> Name2 -> Bool #

Show Name2 Source # 

Methods

showsPrec :: Int -> Name2 -> ShowS #

show :: Name2 -> String #

showList :: [Name2] -> ShowS #

HasOptionalParam UpdatePetWithForm Name2 Source #

Optional Param "name" - Updated name of the pet

newtype Number Source #

Constructors

Number 

Fields

Instances

newtype OrderId Source #

Constructors

OrderId 

Fields

newtype Param Source #

Constructors

Param 

Fields

Instances

Eq Param Source # 

Methods

(==) :: Param -> Param -> Bool #

(/=) :: Param -> Param -> Bool #

Show Param Source # 

Methods

showsPrec :: Int -> Param -> ShowS #

show :: Param -> String #

showList :: [Param] -> ShowS #

newtype Param2 Source #

Constructors

Param2 

Fields

Instances

newtype PetId Source #

Constructors

PetId 

Fields

Instances

Eq PetId Source # 

Methods

(==) :: PetId -> PetId -> Bool #

(/=) :: PetId -> PetId -> Bool #

Show PetId Source # 

Methods

showsPrec :: Int -> PetId -> ShowS #

show :: PetId -> String #

showList :: [PetId] -> ShowS #

newtype Status Source #

Constructors

Status 

Fields

Instances

newtype Tags Source #

Constructors

Tags 

Fields

Instances

Eq Tags Source # 

Methods

(==) :: Tags -> Tags -> Bool #

(/=) :: Tags -> Tags -> Bool #

Show Tags Source # 

Methods

showsPrec :: Int -> Tags -> ShowS #

show :: Tags -> String #

showList :: [Tags] -> ShowS #

newtype Username Source #

Constructors

Username 

Fields

Auth Methods

AuthApiKeyApiKey

AuthApiKeyApiKeyQuery

AuthBasicHttpBasicTest

AuthOAuthPetstoreAuth

Custom Mime Types

MimeJsonCharsetutf8

MimeXmlCharsetutf8

\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-Client.html b/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-Client.html index 5d923cb5060..37abb6a7ea4 100644 --- a/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-Client.html +++ b/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-Client.html @@ -1,4 +1,4 @@ SwaggerPetstore.Client

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Safe HaskellNone
LanguageHaskell2010

SwaggerPetstore.Client

Description

 

Synopsis

Dispatch

Lbs

dispatchLbs Source #

Arguments

:: (Produces req accept, MimeType contentType) 
=> Manager

http-client Connection manager

-> SwaggerPetstoreConfig

config

-> SwaggerPetstoreRequest req contentType res

request

-> accept

"accept" MimeType

-> IO (Response ByteString)

response

send a request returning the raw http response

Mime

data MimeResult res Source #

pair of decoded http body and http response

Constructors

MimeResult 

Fields

Instances

Functor MimeResult Source # 

Methods

fmap :: (a -> b) -> MimeResult a -> MimeResult b #

(<$) :: a -> MimeResult b -> MimeResult a #

Foldable MimeResult Source # 

Methods

fold :: Monoid m => MimeResult m -> m #

foldMap :: Monoid m => (a -> m) -> MimeResult a -> m #

foldr :: (a -> b -> b) -> b -> MimeResult a -> b #

foldr' :: (a -> b -> b) -> b -> MimeResult a -> b #

foldl :: (b -> a -> b) -> b -> MimeResult a -> b #

foldl' :: (b -> a -> b) -> b -> MimeResult a -> b #

foldr1 :: (a -> a -> a) -> MimeResult a -> a #

foldl1 :: (a -> a -> a) -> MimeResult a -> a #

toList :: MimeResult a -> [a] #

null :: MimeResult a -> Bool #

length :: MimeResult a -> Int #

elem :: Eq a => a -> MimeResult a -> Bool #

maximum :: Ord a => MimeResult a -> a #

minimum :: Ord a => MimeResult a -> a #

sum :: Num a => MimeResult a -> a #

product :: Num a => MimeResult a -> a #

Traversable MimeResult Source # 

Methods

traverse :: Applicative f => (a -> f b) -> MimeResult a -> f (MimeResult b) #

sequenceA :: Applicative f => MimeResult (f a) -> f (MimeResult a) #

mapM :: Monad m => (a -> m b) -> MimeResult a -> m (MimeResult b) #

sequence :: Monad m => MimeResult (m a) -> m (MimeResult a) #

Show res => Show (MimeResult res) Source # 

Methods

showsPrec :: Int -> MimeResult res -> ShowS #

show :: MimeResult res -> String #

showList :: [MimeResult res] -> ShowS #

data MimeError Source #

pair of unrender/parser error and http response

Constructors

MimeError 

Fields

dispatchMime Source #

Arguments

:: (Produces req accept, MimeUnrender accept res, MimeType contentType) 
=> Manager

http-client Connection manager

-> SwaggerPetstoreConfig

config

-> SwaggerPetstoreRequest req contentType res

request

-> accept

"accept" MimeType

-> IO (MimeResult res)

response

send a request returning the MimeResult

dispatchMime' Source #

Arguments

:: (Produces req accept, MimeUnrender accept res, MimeType contentType) 
=> Manager

http-client Connection manager

-> SwaggerPetstoreConfig

config

-> SwaggerPetstoreRequest req contentType res

request

-> accept

"accept" MimeType

-> IO (Either MimeError res)

response

like dispatchMime, but only returns the decoded http body

Unsafe

dispatchLbsUnsafe Source #

Arguments

:: (MimeType accept, MimeType contentType) 
=> Manager

http-client Connection manager

-> SwaggerPetstoreConfig

config

-> SwaggerPetstoreRequest req contentType res

request

-> accept

"accept" MimeType

-> IO (Response ByteString)

response

like dispatchReqLbs, but does not validate the operation is a Producer of the "accept" MimeType. (Useful if the server's response is undocumented)

dispatchInitUnsafe Source #

Arguments

:: Manager

http-client Connection manager

-> SwaggerPetstoreConfig

config

-> InitRequest req contentType res accept

init request

-> IO (Response ByteString)

response

dispatch an InitRequest

InitRequest

newtype InitRequest req contentType res accept Source #

wraps an http-client Request with request/response type parameters

Constructors

InitRequest 

Instances

Show (InitRequest req contentType res accept) Source # 

Methods

showsPrec :: Int -> InitRequest req contentType res accept -> ShowS #

show :: InitRequest req contentType res accept -> String #

showList :: [InitRequest req contentType res accept] -> ShowS #

_toInitRequest Source #

Arguments

:: (MimeType accept, MimeType contentType) 
=> SwaggerPetstoreConfig

config

-> SwaggerPetstoreRequest req contentType res

request

-> accept

"accept" MimeType

-> IO (InitRequest req contentType res accept)

initialized request

Build an http-client Request record from the supplied config and request

modifyInitRequest :: InitRequest req contentType res accept -> (Request -> Request) -> InitRequest req contentType res accept Source #

modify the underlying Request

modifyInitRequestM :: Monad m => InitRequest req contentType res accept -> (Request -> m Request) -> m (InitRequest req contentType res accept) Source #

modify the underlying Request (monadic)

Logging

runConfigLog :: MonadIO m => SwaggerPetstoreConfig -> LogExec m Source #

Run a block using the configured logger instance

runConfigLogWithExceptions :: (MonadCatch m, MonadIO m) => Text -> SwaggerPetstoreConfig -> LogExec m Source #

Run a block using the configured logger instance (logs exceptions)

\ No newline at end of file +

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Safe HaskellNone
LanguageHaskell2010

SwaggerPetstore.Client

Description

 

Synopsis

Dispatch

Lbs

dispatchLbs Source #

Arguments

:: (Produces req accept, MimeType contentType) 
=> Manager

http-client Connection manager

-> SwaggerPetstoreConfig

config

-> SwaggerPetstoreRequest req contentType res accept

request

-> IO (Response ByteString)

response

send a request returning the raw http response

Mime

data MimeResult res Source #

pair of decoded http body and http response

Constructors

MimeResult 

Fields

Instances

Functor MimeResult Source # 

Methods

fmap :: (a -> b) -> MimeResult a -> MimeResult b #

(<$) :: a -> MimeResult b -> MimeResult a #

Foldable MimeResult Source # 

Methods

fold :: Monoid m => MimeResult m -> m #

foldMap :: Monoid m => (a -> m) -> MimeResult a -> m #

foldr :: (a -> b -> b) -> b -> MimeResult a -> b #

foldr' :: (a -> b -> b) -> b -> MimeResult a -> b #

foldl :: (b -> a -> b) -> b -> MimeResult a -> b #

foldl' :: (b -> a -> b) -> b -> MimeResult a -> b #

foldr1 :: (a -> a -> a) -> MimeResult a -> a #

foldl1 :: (a -> a -> a) -> MimeResult a -> a #

toList :: MimeResult a -> [a] #

null :: MimeResult a -> Bool #

length :: MimeResult a -> Int #

elem :: Eq a => a -> MimeResult a -> Bool #

maximum :: Ord a => MimeResult a -> a #

minimum :: Ord a => MimeResult a -> a #

sum :: Num a => MimeResult a -> a #

product :: Num a => MimeResult a -> a #

Traversable MimeResult Source # 

Methods

traverse :: Applicative f => (a -> f b) -> MimeResult a -> f (MimeResult b) #

sequenceA :: Applicative f => MimeResult (f a) -> f (MimeResult a) #

mapM :: Monad m => (a -> m b) -> MimeResult a -> m (MimeResult b) #

sequence :: Monad m => MimeResult (m a) -> m (MimeResult a) #

Show res => Show (MimeResult res) Source # 

Methods

showsPrec :: Int -> MimeResult res -> ShowS #

show :: MimeResult res -> String #

showList :: [MimeResult res] -> ShowS #

data MimeError Source #

pair of unrender/parser error and http response

Constructors

MimeError 

Fields

dispatchMime Source #

Arguments

:: (Produces req accept, MimeUnrender accept res, MimeType contentType) 
=> Manager

http-client Connection manager

-> SwaggerPetstoreConfig

config

-> SwaggerPetstoreRequest req contentType res accept

request

-> IO (MimeResult res)

response

send a request returning the MimeResult

dispatchMime' Source #

Arguments

:: (Produces req accept, MimeUnrender accept res, MimeType contentType) 
=> Manager

http-client Connection manager

-> SwaggerPetstoreConfig

config

-> SwaggerPetstoreRequest req contentType res accept

request

-> IO (Either MimeError res)

response

like dispatchMime, but only returns the decoded http body

Unsafe

dispatchLbsUnsafe Source #

Arguments

:: (MimeType accept, MimeType contentType) 
=> Manager

http-client Connection manager

-> SwaggerPetstoreConfig

config

-> SwaggerPetstoreRequest req contentType res accept

request

-> IO (Response ByteString)

response

like dispatchReqLbs, but does not validate the operation is a Producer of the "accept" MimeType. (Useful if the server's response is undocumented)

dispatchInitUnsafe Source #

Arguments

:: Manager

http-client Connection manager

-> SwaggerPetstoreConfig

config

-> InitRequest req contentType res accept

init request

-> IO (Response ByteString)

response

dispatch an InitRequest

InitRequest

newtype InitRequest req contentType res accept Source #

wraps an http-client Request with request/response type parameters

Constructors

InitRequest 

Instances

Show (InitRequest req contentType res accept) Source # 

Methods

showsPrec :: Int -> InitRequest req contentType res accept -> ShowS #

show :: InitRequest req contentType res accept -> String #

showList :: [InitRequest req contentType res accept] -> ShowS #

_toInitRequest Source #

Arguments

:: (MimeType accept, MimeType contentType) 
=> SwaggerPetstoreConfig

config

-> SwaggerPetstoreRequest req contentType res accept

request

-> IO (InitRequest req contentType res accept)

initialized request

Build an http-client Request record from the supplied config and request

modifyInitRequest :: InitRequest req contentType res accept -> (Request -> Request) -> InitRequest req contentType res accept Source #

modify the underlying Request

modifyInitRequestM :: Monad m => InitRequest req contentType res accept -> (Request -> m Request) -> m (InitRequest req contentType res accept) Source #

modify the underlying Request (monadic)

Logging

runConfigLog :: MonadIO m => SwaggerPetstoreConfig -> LogExec m Source #

Run a block using the configured logger instance

runConfigLogWithExceptions :: (MonadCatch m, MonadIO m) => Text -> SwaggerPetstoreConfig -> LogExec m Source #

Run a block using the configured logger instance (logs exceptions)

\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-Core.html b/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-Core.html index 684f3ff14b6..6a8a42803f7 100644 --- a/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-Core.html +++ b/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-Core.html @@ -1,4 +1,4 @@ SwaggerPetstore.Core

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Safe HaskellNone
LanguageHaskell2010

SwaggerPetstore.Core

Description

 

Synopsis

SwaggerPetstoreConfig

data SwaggerPetstoreConfig Source #

Constructors

SwaggerPetstoreConfig 

Fields

newConfig :: IO SwaggerPetstoreConfig Source #

constructs a default SwaggerPetstoreConfig

configHost:

http://petstore.swagger.io:80/v2

configUserAgent:

"swagger-haskell-http-client/1.0.0"

addAuthMethod :: AuthMethod auth => SwaggerPetstoreConfig -> auth -> SwaggerPetstoreConfig Source #

updates config use AuthMethod on matching requests

withStdoutLogging :: SwaggerPetstoreConfig -> IO SwaggerPetstoreConfig Source #

updates the config to use stdout logging

withStderrLogging :: SwaggerPetstoreConfig -> IO SwaggerPetstoreConfig Source #

updates the config to use stderr logging

withNoLogging :: SwaggerPetstoreConfig -> SwaggerPetstoreConfig Source #

updates the config to disable logging

SwaggerPetstoreRequest

data SwaggerPetstoreRequest req contentType res Source #

Represents a request. The "req" type variable is the request type. The "res" type variable is the response type.

Constructors

SwaggerPetstoreRequest 

Fields

Instances

Show (SwaggerPetstoreRequest req contentType res) Source # 

Methods

showsPrec :: Int -> SwaggerPetstoreRequest req contentType res -> ShowS #

show :: SwaggerPetstoreRequest req contentType res -> String #

showList :: [SwaggerPetstoreRequest req contentType res] -> ShowS #

HasBodyParam

class HasBodyParam req param where Source #

Designates the body parameter of a request

Methods

setBodyParam :: forall contentType res. (Consumes req contentType, MimeRender contentType param) => SwaggerPetstoreRequest req contentType res -> param -> SwaggerPetstoreRequest req contentType res Source #

Instances

HasBodyParam UpdateUser User Source #

Body Param "body" - Updated user object

Methods

setBodyParam :: (Consumes UpdateUser contentType, MimeRender contentType User) => SwaggerPetstoreRequest UpdateUser contentType res -> User -> SwaggerPetstoreRequest UpdateUser contentType res Source #

HasBodyParam CreateUsersWithListInput Body Source #

Body Param "body" - List of user object

HasBodyParam CreateUsersWithArrayInput Body Source #

Body Param "body" - List of user object

HasBodyParam CreateUser User Source #

Body Param "body" - Created user object

Methods

setBodyParam :: (Consumes CreateUser contentType, MimeRender contentType User) => SwaggerPetstoreRequest CreateUser contentType res -> User -> SwaggerPetstoreRequest CreateUser contentType res Source #

HasBodyParam PlaceOrder Order Source #

Body Param "body" - order placed for purchasing the pet

Methods

setBodyParam :: (Consumes PlaceOrder contentType, MimeRender contentType Order) => SwaggerPetstoreRequest PlaceOrder contentType res -> Order -> SwaggerPetstoreRequest PlaceOrder contentType res Source #

HasBodyParam UpdatePet Pet Source #

Body Param "body" - Pet object that needs to be added to the store

Methods

setBodyParam :: (Consumes UpdatePet contentType, MimeRender contentType Pet) => SwaggerPetstoreRequest UpdatePet contentType res -> Pet -> SwaggerPetstoreRequest UpdatePet contentType res Source #

HasBodyParam AddPet Pet Source #

Body Param "body" - Pet object that needs to be added to the store

Methods

setBodyParam :: (Consumes AddPet contentType, MimeRender contentType Pet) => SwaggerPetstoreRequest AddPet contentType res -> Pet -> SwaggerPetstoreRequest AddPet contentType res Source #

HasBodyParam TestClassname Client Source #

Body Param "body" - client model

Methods

setBodyParam :: (Consumes TestClassname contentType, MimeRender contentType Client) => SwaggerPetstoreRequest TestClassname contentType res -> Client -> SwaggerPetstoreRequest TestClassname contentType res Source #

HasBodyParam TestClientModel Client Source #

Body Param "body" - client model

HasBodyParam FakeOuterStringSerialize OuterString Source #

Body Param "body" - Input string as post body

HasBodyParam FakeOuterNumberSerialize OuterNumber Source #

Body Param "body" - Input number as post body

HasBodyParam FakeOuterCompositeSerialize OuterComposite Source #

Body Param "body" - Input composite as post body

HasBodyParam FakeOuterBooleanSerialize OuterBoolean Source #

Body Param "body" - Input boolean as post body

HasBodyParam TestSpecialTags Client Source #

Body Param "body" - client model

HasOptionalParam

class HasOptionalParam req param where Source #

Designates the optional parameters of a request

Minimal complete definition

applyOptionalParam | (-&-)

Methods

applyOptionalParam :: SwaggerPetstoreRequest req contentType res -> param -> SwaggerPetstoreRequest req contentType res Source #

Apply an optional parameter to a request

(-&-) :: SwaggerPetstoreRequest req contentType res -> param -> SwaggerPetstoreRequest req contentType res infixl 2 Source #

infix operator / alias for addOptionalParam

Instances

HasOptionalParam UploadFile File Source #

Optional Param "file" - file to upload

HasOptionalParam UploadFile AdditionalMetadata Source #

Optional Param "additionalMetadata" - Additional data to pass to server

HasOptionalParam UpdatePetWithForm StatusText Source #

Optional Param "status" - Updated status of the pet

HasOptionalParam UpdatePetWithForm Name2 Source #

Optional Param "name" - Updated name of the pet

HasOptionalParam DeletePet ApiKey Source # 
HasOptionalParam TestEnumParameters EnumQueryStringArray Source #

Optional Param "enum_query_string_array" - Query parameter enum test (string array)

HasOptionalParam TestEnumParameters EnumQueryString Source #

Optional Param "enum_query_string" - Query parameter enum test (string)

HasOptionalParam TestEnumParameters EnumQueryInteger Source #

Optional Param "enum_query_integer" - Query parameter enum test (double)

HasOptionalParam TestEnumParameters EnumQueryDouble Source #

Optional Param "enum_query_double" - Query parameter enum test (double)

HasOptionalParam TestEnumParameters EnumHeaderStringArray Source #

Optional Param "enum_header_string_array" - Header parameter enum test (string array)

HasOptionalParam TestEnumParameters EnumHeaderString Source #

Optional Param "enum_header_string" - Header parameter enum test (string)

HasOptionalParam TestEnumParameters EnumFormStringArray Source #

Optional Param "enum_form_string_array" - Form parameter enum test (string array)

HasOptionalParam TestEnumParameters EnumFormString Source #

Optional Param "enum_form_string" - Form parameter enum test (string)

HasOptionalParam TestEndpointParameters Password Source #

Optional Param "password" - None

HasOptionalParam TestEndpointParameters ParamString Source #

Optional Param "string" - None

HasOptionalParam TestEndpointParameters ParamInteger Source #

Optional Param "integer" - None

HasOptionalParam TestEndpointParameters ParamFloat Source #

Optional Param "float" - None

HasOptionalParam TestEndpointParameters ParamDateTime Source #

Optional Param "dateTime" - None

HasOptionalParam TestEndpointParameters ParamDate Source #

Optional Param "date" - None

HasOptionalParam TestEndpointParameters ParamBinary Source #

Optional Param "binary" - None

HasOptionalParam TestEndpointParameters Int64 Source #

Optional Param "int64" - None

HasOptionalParam TestEndpointParameters Int32 Source #

Optional Param "int32" - None

HasOptionalParam TestEndpointParameters Callback Source #

Optional Param "callback" - None

data Params Source #

Request Params

Instances

SwaggerPetstoreRequest Utils

_mkRequest Source #

Arguments

:: Method

Method

-> [ByteString]

Endpoint

-> SwaggerPetstoreRequest req contentType res

req: Request Type, res: Response Type

setHeader :: SwaggerPetstoreRequest req contentType res -> [Header] -> SwaggerPetstoreRequest req contentType res Source #

removeHeader :: SwaggerPetstoreRequest req contentType res -> [HeaderName] -> SwaggerPetstoreRequest req contentType res Source #

_setContentTypeHeader :: forall req contentType res. MimeType contentType => SwaggerPetstoreRequest req contentType res -> SwaggerPetstoreRequest req contentType res Source #

_setAcceptHeader :: forall req contentType res accept. MimeType accept => SwaggerPetstoreRequest req contentType res -> accept -> SwaggerPetstoreRequest req contentType res Source #

setQuery :: SwaggerPetstoreRequest req contentType res -> [QueryItem] -> SwaggerPetstoreRequest req contentType res Source #

addForm :: SwaggerPetstoreRequest req contentType res -> Form -> SwaggerPetstoreRequest req contentType res Source #

_addMultiFormPart :: SwaggerPetstoreRequest req contentType res -> Part -> SwaggerPetstoreRequest req contentType res Source #

_setBodyBS :: SwaggerPetstoreRequest req contentType res -> ByteString -> SwaggerPetstoreRequest req contentType res Source #

_setBodyLBS :: SwaggerPetstoreRequest req contentType res -> ByteString -> SwaggerPetstoreRequest req contentType res Source #

_hasAuthType :: AuthMethod authMethod => SwaggerPetstoreRequest req contentType res -> Proxy authMethod -> SwaggerPetstoreRequest req contentType res Source #

Params Utils

Swagger CollectionFormat Utils

data CollectionFormat Source #

Determines the format of the array if type array is used.

Constructors

CommaSeparated

CSV format for multiple parameters.

SpaceSeparated

Also called SSV

TabSeparated

Also called TSV

PipeSeparated

`value1|value2|value2`

MultiParamArray

Using multiple GET parameters, e.g. `foo=bar&foo=baz`. This is valid only for parameters in "query" (Query) or "formData" (Form)

_toColl :: Traversable f => CollectionFormat -> (f a -> [(b, ByteString)]) -> f [a] -> [(b, ByteString)] Source #

_toCollA :: (Traversable f, Traversable t, Alternative t) => CollectionFormat -> (f (t a) -> [(b, t ByteString)]) -> f (t [a]) -> [(b, t ByteString)] Source #

_toCollA' :: (Monoid c, Traversable f, Traversable t, Alternative t) => CollectionFormat -> (f (t a) -> [(b, t c)]) -> (Char -> c) -> f (t [a]) -> [(b, t c)] Source #

AuthMethods

data AnyAuthMethod Source #

An existential wrapper for any AuthMethod

Constructors

AuthMethod a => AnyAuthMethod a 

_applyAuthMethods :: SwaggerPetstoreRequest req contentType res -> SwaggerPetstoreConfig -> IO (SwaggerPetstoreRequest req contentType res) Source #

apply all matching AuthMethods in config to request

Utils

_omitNulls :: [(Text, Value)] -> Value Source #

Removes Null fields. (OpenAPI-Specification 2.0 does not allow Null in JSON)

_toFormItem :: (ToHttpApiData a, Functor f) => t -> f a -> f (t, [Text]) Source #

Encodes fields using WH.toQueryParam

_emptyToNothing :: Maybe String -> Maybe String Source #

Collapse (Just "") to Nothing

_memptyToNothing :: (Monoid a, Eq a) => Maybe a -> Maybe a Source #

Collapse (Just mempty) to Nothing

DateTime Formatting

newtype DateTime Source #

Constructors

DateTime 

Fields

Instances

Eq DateTime Source # 
Data DateTime Source # 

Methods

gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> DateTime -> c DateTime #

gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c DateTime #

toConstr :: DateTime -> Constr #

dataTypeOf :: DateTime -> DataType #

dataCast1 :: Typeable (* -> *) t => (forall d. Data d => c (t d)) -> Maybe (c DateTime) #

dataCast2 :: Typeable (* -> * -> *) t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c DateTime) #

gmapT :: (forall b. Data b => b -> b) -> DateTime -> DateTime #

gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> DateTime -> r #

gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> DateTime -> r #

gmapQ :: (forall d. Data d => d -> u) -> DateTime -> [u] #

gmapQi :: Int -> (forall d. Data d => d -> u) -> DateTime -> u #

gmapM :: Monad m => (forall d. Data d => d -> m d) -> DateTime -> m DateTime #

gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> DateTime -> m DateTime #

gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> DateTime -> m DateTime #

Ord DateTime Source # 
Show DateTime Source # 
ToJSON DateTime Source # 
FromJSON DateTime Source # 
NFData DateTime Source # 

Methods

rnf :: DateTime -> () #

ToHttpApiData DateTime Source # 
FromHttpApiData DateTime Source # 
FormatTime DateTime Source # 
ParseTime DateTime Source # 
MimeRender MimeMultipartFormData DateTime Source # 

_readDateTime :: (ParseTime t, Monad m, Alternative m) => String -> m t Source #

_parseISO8601

_showDateTime :: (t ~ UTCTime, FormatTime t) => t -> String Source #

TI.formatISO8601Millis

_parseISO8601 :: (ParseTime t, Monad m, Alternative m) => String -> m t Source #

parse an ISO8601 date-time string

Date Formatting

newtype Date Source #

Constructors

Date 

Fields

Instances

Enum Date Source # 

Methods

succ :: Date -> Date #

pred :: Date -> Date #

toEnum :: Int -> Date #

fromEnum :: Date -> Int #

enumFrom :: Date -> [Date] #

enumFromThen :: Date -> Date -> [Date] #

enumFromTo :: Date -> Date -> [Date] #

enumFromThenTo :: Date -> Date -> Date -> [Date] #

Eq Date Source # 

Methods

(==) :: Date -> Date -> Bool #

(/=) :: Date -> Date -> Bool #

Data Date Source # 

Methods

gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Date -> c Date #

gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c Date #

toConstr :: Date -> Constr #

dataTypeOf :: Date -> DataType #

dataCast1 :: Typeable (* -> *) t => (forall d. Data d => c (t d)) -> Maybe (c Date) #

dataCast2 :: Typeable (* -> * -> *) t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c Date) #

gmapT :: (forall b. Data b => b -> b) -> Date -> Date #

gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Date -> r #

gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Date -> r #

gmapQ :: (forall d. Data d => d -> u) -> Date -> [u] #

gmapQi :: Int -> (forall d. Data d => d -> u) -> Date -> u #

gmapM :: Monad m => (forall d. Data d => d -> m d) -> Date -> m Date #

gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Date -> m Date #

gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Date -> m Date #

Ord Date Source # 

Methods

compare :: Date -> Date -> Ordering #

(<) :: Date -> Date -> Bool #

(<=) :: Date -> Date -> Bool #

(>) :: Date -> Date -> Bool #

(>=) :: Date -> Date -> Bool #

max :: Date -> Date -> Date #

min :: Date -> Date -> Date #

Show Date Source # 

Methods

showsPrec :: Int -> Date -> ShowS #

show :: Date -> String #

showList :: [Date] -> ShowS #

Ix Date Source # 

Methods

range :: (Date, Date) -> [Date] #

index :: (Date, Date) -> Date -> Int #

unsafeIndex :: (Date, Date) -> Date -> Int

inRange :: (Date, Date) -> Date -> Bool #

rangeSize :: (Date, Date) -> Int #

unsafeRangeSize :: (Date, Date) -> Int

ToJSON Date Source # 
FromJSON Date Source # 
NFData Date Source # 

Methods

rnf :: Date -> () #

ToHttpApiData Date Source # 
FromHttpApiData Date Source # 
FormatTime Date Source # 
ParseTime Date Source # 

Methods

buildTime :: TimeLocale -> [(Char, String)] -> Maybe Date #

MimeRender MimeMultipartFormData Date Source # 

_readDate :: (ParseTime t, Monad m) => String -> m t Source #

TI.parseTimeM True TI.defaultTimeLocale "%Y-%m-%d"

_showDate :: FormatTime t => t -> String Source #

TI.formatTime TI.defaultTimeLocale "%Y-%m-%d"

Byte/Binary Formatting

newtype ByteArray Source #

base64 encoded characters

Constructors

ByteArray 

Instances

Eq ByteArray Source # 
Data ByteArray Source # 

Methods

gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> ByteArray -> c ByteArray #

gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c ByteArray #

toConstr :: ByteArray -> Constr #

dataTypeOf :: ByteArray -> DataType #

dataCast1 :: Typeable (* -> *) t => (forall d. Data d => c (t d)) -> Maybe (c ByteArray) #

dataCast2 :: Typeable (* -> * -> *) t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c ByteArray) #

gmapT :: (forall b. Data b => b -> b) -> ByteArray -> ByteArray #

gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> ByteArray -> r #

gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> ByteArray -> r #

gmapQ :: (forall d. Data d => d -> u) -> ByteArray -> [u] #

gmapQi :: Int -> (forall d. Data d => d -> u) -> ByteArray -> u #

gmapM :: Monad m => (forall d. Data d => d -> m d) -> ByteArray -> m ByteArray #

gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> ByteArray -> m ByteArray #

gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> ByteArray -> m ByteArray #

Ord ByteArray Source # 
Show ByteArray Source # 
ToJSON ByteArray Source # 
FromJSON ByteArray Source # 
NFData ByteArray Source # 

Methods

rnf :: ByteArray -> () #

ToHttpApiData ByteArray Source # 
FromHttpApiData ByteArray Source # 
MimeRender MimeMultipartFormData ByteArray Source # 

_readByteArray :: Monad m => Text -> m ByteArray Source #

read base64 encoded characters

_showByteArray :: ByteArray -> Text Source #

show base64 encoded characters

newtype Binary Source #

any sequence of octets

Constructors

Binary 

Fields

Instances

Eq Binary Source # 

Methods

(==) :: Binary -> Binary -> Bool #

(/=) :: Binary -> Binary -> Bool #

Data Binary Source # 

Methods

gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Binary -> c Binary #

gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c Binary #

toConstr :: Binary -> Constr #

dataTypeOf :: Binary -> DataType #

dataCast1 :: Typeable (* -> *) t => (forall d. Data d => c (t d)) -> Maybe (c Binary) #

dataCast2 :: Typeable (* -> * -> *) t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c Binary) #

gmapT :: (forall b. Data b => b -> b) -> Binary -> Binary #

gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Binary -> r #

gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Binary -> r #

gmapQ :: (forall d. Data d => d -> u) -> Binary -> [u] #

gmapQi :: Int -> (forall d. Data d => d -> u) -> Binary -> u #

gmapM :: Monad m => (forall d. Data d => d -> m d) -> Binary -> m Binary #

gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Binary -> m Binary #

gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Binary -> m Binary #

Ord Binary Source # 
Show Binary Source # 
ToJSON Binary Source # 
FromJSON Binary Source # 
NFData Binary Source # 

Methods

rnf :: Binary -> () #

ToHttpApiData Binary Source # 
FromHttpApiData Binary Source # 
MimeRender MimeMultipartFormData Binary Source # 

Lens Type Aliases

type Lens_' s a = Lens_ s s a a Source #

type Lens_ s t a b = forall f. Functor f => (a -> f b) -> s -> f t Source #

\ No newline at end of file +

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Safe HaskellNone
LanguageHaskell2010

SwaggerPetstore.Core

Description

 

Synopsis

SwaggerPetstoreConfig

data SwaggerPetstoreConfig Source #

Constructors

SwaggerPetstoreConfig 

Fields

newConfig :: IO SwaggerPetstoreConfig Source #

constructs a default SwaggerPetstoreConfig

configHost:

http://petstore.swagger.io:80/v2

configUserAgent:

"swagger-haskell-http-client/1.0.0"

addAuthMethod :: AuthMethod auth => SwaggerPetstoreConfig -> auth -> SwaggerPetstoreConfig Source #

updates config use AuthMethod on matching requests

withStdoutLogging :: SwaggerPetstoreConfig -> IO SwaggerPetstoreConfig Source #

updates the config to use stdout logging

withStderrLogging :: SwaggerPetstoreConfig -> IO SwaggerPetstoreConfig Source #

updates the config to use stderr logging

withNoLogging :: SwaggerPetstoreConfig -> SwaggerPetstoreConfig Source #

updates the config to disable logging

SwaggerPetstoreRequest

data SwaggerPetstoreRequest req contentType res accept Source #

Represents a request.

Type Variables:

  • req - request operation
  • contentType - MimeType associated with request body
  • res - response model
  • accept - MimeType associated with response body

Constructors

SwaggerPetstoreRequest 

Fields

Instances

Show (SwaggerPetstoreRequest req contentType res accept) Source # 

Methods

showsPrec :: Int -> SwaggerPetstoreRequest req contentType res accept -> ShowS #

show :: SwaggerPetstoreRequest req contentType res accept -> String #

showList :: [SwaggerPetstoreRequest req contentType res accept] -> ShowS #

rMethodL :: Lens_' (SwaggerPetstoreRequest req contentType res accept) Method Source #

rMethod Lens

rUrlPathL :: Lens_' (SwaggerPetstoreRequest req contentType res accept) [ByteString] Source #

rParamsL :: Lens_' (SwaggerPetstoreRequest req contentType res accept) Params Source #

rParams Lens

rAuthTypesL :: Lens_' (SwaggerPetstoreRequest req contentType res accept) [TypeRep] Source #

rParams Lens

HasBodyParam

class HasBodyParam req param where Source #

Designates the body parameter of a request

Methods

setBodyParam :: forall contentType res accept. (Consumes req contentType, MimeRender contentType param) => SwaggerPetstoreRequest req contentType res accept -> param -> SwaggerPetstoreRequest req contentType res accept Source #

Instances

HasBodyParam UpdateUser User Source #

Body Param "body" - Updated user object

Methods

setBodyParam :: (Consumes UpdateUser contentType, MimeRender contentType User) => SwaggerPetstoreRequest UpdateUser contentType res accept -> User -> SwaggerPetstoreRequest UpdateUser contentType res accept Source #

HasBodyParam CreateUsersWithListInput Body Source #

Body Param "body" - List of user object

HasBodyParam CreateUsersWithArrayInput Body Source #

Body Param "body" - List of user object

HasBodyParam CreateUser User Source #

Body Param "body" - Created user object

Methods

setBodyParam :: (Consumes CreateUser contentType, MimeRender contentType User) => SwaggerPetstoreRequest CreateUser contentType res accept -> User -> SwaggerPetstoreRequest CreateUser contentType res accept Source #

HasBodyParam PlaceOrder Order Source #

Body Param "body" - order placed for purchasing the pet

Methods

setBodyParam :: (Consumes PlaceOrder contentType, MimeRender contentType Order) => SwaggerPetstoreRequest PlaceOrder contentType res accept -> Order -> SwaggerPetstoreRequest PlaceOrder contentType res accept Source #

HasBodyParam UpdatePet Pet Source #

Body Param "body" - Pet object that needs to be added to the store

Methods

setBodyParam :: (Consumes UpdatePet contentType, MimeRender contentType Pet) => SwaggerPetstoreRequest UpdatePet contentType res accept -> Pet -> SwaggerPetstoreRequest UpdatePet contentType res accept Source #

HasBodyParam AddPet Pet Source #

Body Param "body" - Pet object that needs to be added to the store

Methods

setBodyParam :: (Consumes AddPet contentType, MimeRender contentType Pet) => SwaggerPetstoreRequest AddPet contentType res accept -> Pet -> SwaggerPetstoreRequest AddPet contentType res accept Source #

HasBodyParam TestClassname Client Source #

Body Param "body" - client model

Methods

setBodyParam :: (Consumes TestClassname contentType, MimeRender contentType Client) => SwaggerPetstoreRequest TestClassname contentType res accept -> Client -> SwaggerPetstoreRequest TestClassname contentType res accept Source #

HasBodyParam TestInlineAdditionalProperties Value Source #

Body Param "param" - request body

HasBodyParam TestClientModel Client Source #

Body Param "body" - client model

Methods

setBodyParam :: (Consumes TestClientModel contentType, MimeRender contentType Client) => SwaggerPetstoreRequest TestClientModel contentType res accept -> Client -> SwaggerPetstoreRequest TestClientModel contentType res accept Source #

HasBodyParam FakeOuterStringSerialize OuterString Source #

Body Param "body" - Input string as post body

HasBodyParam FakeOuterNumberSerialize OuterNumber Source #

Body Param "body" - Input number as post body

HasBodyParam FakeOuterCompositeSerialize OuterComposite Source #

Body Param "body" - Input composite as post body

HasBodyParam FakeOuterBooleanSerialize OuterBoolean Source #

Body Param "body" - Input boolean as post body

HasBodyParam TestSpecialTags Client Source #

Body Param "body" - client model

Methods

setBodyParam :: (Consumes TestSpecialTags contentType, MimeRender contentType Client) => SwaggerPetstoreRequest TestSpecialTags contentType res accept -> Client -> SwaggerPetstoreRequest TestSpecialTags contentType res accept Source #

HasOptionalParam

class HasOptionalParam req param where Source #

Designates the optional parameters of a request

Minimal complete definition

applyOptionalParam | (-&-)

Methods

applyOptionalParam :: SwaggerPetstoreRequest req contentType res accept -> param -> SwaggerPetstoreRequest req contentType res accept Source #

Apply an optional parameter to a request

(-&-) :: SwaggerPetstoreRequest req contentType res accept -> param -> SwaggerPetstoreRequest req contentType res accept infixl 2 Source #

infix operator / alias for addOptionalParam

Instances

HasOptionalParam UploadFile File Source #

Optional Param "file" - file to upload

Methods

applyOptionalParam :: SwaggerPetstoreRequest UploadFile contentType res accept -> File -> SwaggerPetstoreRequest UploadFile contentType res accept Source #

(-&-) :: SwaggerPetstoreRequest UploadFile contentType res accept -> File -> SwaggerPetstoreRequest UploadFile contentType res accept Source #

HasOptionalParam UploadFile AdditionalMetadata Source #

Optional Param "additionalMetadata" - Additional data to pass to server

HasOptionalParam UpdatePetWithForm StatusText Source #

Optional Param "status" - Updated status of the pet

HasOptionalParam UpdatePetWithForm Name2 Source #

Optional Param "name" - Updated name of the pet

HasOptionalParam DeletePet ApiKey Source # 

Methods

applyOptionalParam :: SwaggerPetstoreRequest DeletePet contentType res accept -> ApiKey -> SwaggerPetstoreRequest DeletePet contentType res accept Source #

(-&-) :: SwaggerPetstoreRequest DeletePet contentType res accept -> ApiKey -> SwaggerPetstoreRequest DeletePet contentType res accept Source #

HasOptionalParam TestEnumParameters EnumQueryStringArray Source #

Optional Param "enum_query_string_array" - Query parameter enum test (string array)

HasOptionalParam TestEnumParameters EnumQueryString Source #

Optional Param "enum_query_string" - Query parameter enum test (string)

HasOptionalParam TestEnumParameters EnumQueryInteger Source #

Optional Param "enum_query_integer" - Query parameter enum test (double)

HasOptionalParam TestEnumParameters EnumQueryDouble Source #

Optional Param "enum_query_double" - Query parameter enum test (double)

HasOptionalParam TestEnumParameters EnumHeaderStringArray Source #

Optional Param "enum_header_string_array" - Header parameter enum test (string array)

HasOptionalParam TestEnumParameters EnumHeaderString Source #

Optional Param "enum_header_string" - Header parameter enum test (string)

HasOptionalParam TestEnumParameters EnumFormStringArray Source #

Optional Param "enum_form_string_array" - Form parameter enum test (string array)

HasOptionalParam TestEnumParameters EnumFormString Source #

Optional Param "enum_form_string" - Form parameter enum test (string)

HasOptionalParam TestEndpointParameters Password Source #

Optional Param "password" - None

HasOptionalParam TestEndpointParameters ParamString Source #

Optional Param "string" - None

HasOptionalParam TestEndpointParameters ParamInteger Source #

Optional Param "integer" - None

HasOptionalParam TestEndpointParameters ParamFloat Source #

Optional Param "float" - None

HasOptionalParam TestEndpointParameters ParamDateTime Source #

Optional Param "dateTime" - None

HasOptionalParam TestEndpointParameters ParamDate Source #

Optional Param "date" - None

HasOptionalParam TestEndpointParameters ParamBinary Source #

Optional Param "binary" - None

HasOptionalParam TestEndpointParameters Int64 Source #

Optional Param "int64" - None

HasOptionalParam TestEndpointParameters Int32 Source #

Optional Param "int32" - None

HasOptionalParam TestEndpointParameters Callback Source #

Optional Param "callback" - None

data Params Source #

Request Params

Instances

SwaggerPetstoreRequest Utils

_mkRequest Source #

Arguments

:: Method

Method

-> [ByteString]

Endpoint

-> SwaggerPetstoreRequest req contentType res accept

req: Request Type, res: Response Type

setHeader :: SwaggerPetstoreRequest req contentType res accept -> [Header] -> SwaggerPetstoreRequest req contentType res accept Source #

removeHeader :: SwaggerPetstoreRequest req contentType res accept -> [HeaderName] -> SwaggerPetstoreRequest req contentType res accept Source #

_setContentTypeHeader :: forall req contentType res accept. MimeType contentType => SwaggerPetstoreRequest req contentType res accept -> SwaggerPetstoreRequest req contentType res accept Source #

_setAcceptHeader :: forall req contentType res accept. MimeType accept => SwaggerPetstoreRequest req contentType res accept -> SwaggerPetstoreRequest req contentType res accept Source #

setQuery :: SwaggerPetstoreRequest req contentType res accept -> [QueryItem] -> SwaggerPetstoreRequest req contentType res accept Source #

addForm :: SwaggerPetstoreRequest req contentType res accept -> Form -> SwaggerPetstoreRequest req contentType res accept Source #

_addMultiFormPart :: SwaggerPetstoreRequest req contentType res accept -> Part -> SwaggerPetstoreRequest req contentType res accept Source #

_setBodyBS :: SwaggerPetstoreRequest req contentType res accept -> ByteString -> SwaggerPetstoreRequest req contentType res accept Source #

_setBodyLBS :: SwaggerPetstoreRequest req contentType res accept -> ByteString -> SwaggerPetstoreRequest req contentType res accept Source #

_hasAuthType :: AuthMethod authMethod => SwaggerPetstoreRequest req contentType res accept -> Proxy authMethod -> SwaggerPetstoreRequest req contentType res accept Source #

Params Utils

Swagger CollectionFormat Utils

data CollectionFormat Source #

Determines the format of the array if type array is used.

Constructors

CommaSeparated

CSV format for multiple parameters.

SpaceSeparated

Also called SSV

TabSeparated

Also called TSV

PipeSeparated

`value1|value2|value2`

MultiParamArray

Using multiple GET parameters, e.g. `foo=bar&foo=baz`. This is valid only for parameters in "query" (Query) or "formData" (Form)

_toColl :: Traversable f => CollectionFormat -> (f a -> [(b, ByteString)]) -> f [a] -> [(b, ByteString)] Source #

_toCollA :: (Traversable f, Traversable t, Alternative t) => CollectionFormat -> (f (t a) -> [(b, t ByteString)]) -> f (t [a]) -> [(b, t ByteString)] Source #

_toCollA' :: (Monoid c, Traversable f, Traversable t, Alternative t) => CollectionFormat -> (f (t a) -> [(b, t c)]) -> (Char -> c) -> f (t [a]) -> [(b, t c)] Source #

AuthMethods

class Typeable a => AuthMethod a where Source #

Provides a method to apply auth methods to requests

Minimal complete definition

applyAuthMethod

Methods

applyAuthMethod :: SwaggerPetstoreConfig -> a -> SwaggerPetstoreRequest req contentType res accept -> IO (SwaggerPetstoreRequest req contentType res accept) Source #

data AnyAuthMethod Source #

An existential wrapper for any AuthMethod

Constructors

AuthMethod a => AnyAuthMethod a 

Instances

AuthMethod AnyAuthMethod Source # 

Methods

applyAuthMethod :: SwaggerPetstoreConfig -> AnyAuthMethod -> SwaggerPetstoreRequest req contentType res accept -> IO (SwaggerPetstoreRequest req contentType res accept) Source #

_applyAuthMethods :: SwaggerPetstoreRequest req contentType res accept -> SwaggerPetstoreConfig -> IO (SwaggerPetstoreRequest req contentType res accept) Source #

apply all matching AuthMethods in config to request

Utils

_omitNulls :: [(Text, Value)] -> Value Source #

Removes Null fields. (OpenAPI-Specification 2.0 does not allow Null in JSON)

_toFormItem :: (ToHttpApiData a, Functor f) => t -> f a -> f (t, [Text]) Source #

Encodes fields using WH.toQueryParam

_emptyToNothing :: Maybe String -> Maybe String Source #

Collapse (Just "") to Nothing

_memptyToNothing :: (Monoid a, Eq a) => Maybe a -> Maybe a Source #

Collapse (Just mempty) to Nothing

DateTime Formatting

newtype DateTime Source #

Constructors

DateTime 

Fields

Instances

Eq DateTime Source # 
Data DateTime Source # 

Methods

gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> DateTime -> c DateTime #

gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c DateTime #

toConstr :: DateTime -> Constr #

dataTypeOf :: DateTime -> DataType #

dataCast1 :: Typeable (* -> *) t => (forall d. Data d => c (t d)) -> Maybe (c DateTime) #

dataCast2 :: Typeable (* -> * -> *) t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c DateTime) #

gmapT :: (forall b. Data b => b -> b) -> DateTime -> DateTime #

gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> DateTime -> r #

gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> DateTime -> r #

gmapQ :: (forall d. Data d => d -> u) -> DateTime -> [u] #

gmapQi :: Int -> (forall d. Data d => d -> u) -> DateTime -> u #

gmapM :: Monad m => (forall d. Data d => d -> m d) -> DateTime -> m DateTime #

gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> DateTime -> m DateTime #

gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> DateTime -> m DateTime #

Ord DateTime Source # 
Show DateTime Source # 
ToJSON DateTime Source # 
FromJSON DateTime Source # 
NFData DateTime Source # 

Methods

rnf :: DateTime -> () #

ToHttpApiData DateTime Source # 
FromHttpApiData DateTime Source # 
FormatTime DateTime Source # 
ParseTime DateTime Source # 
MimeRender MimeMultipartFormData DateTime Source # 

_readDateTime :: (ParseTime t, Monad m, Alternative m) => String -> m t Source #

_parseISO8601

_showDateTime :: (t ~ UTCTime, FormatTime t) => t -> String Source #

TI.formatISO8601Millis

_parseISO8601 :: (ParseTime t, Monad m, Alternative m) => String -> m t Source #

parse an ISO8601 date-time string

Date Formatting

newtype Date Source #

Constructors

Date 

Fields

Instances

Enum Date Source # 

Methods

succ :: Date -> Date #

pred :: Date -> Date #

toEnum :: Int -> Date #

fromEnum :: Date -> Int #

enumFrom :: Date -> [Date] #

enumFromThen :: Date -> Date -> [Date] #

enumFromTo :: Date -> Date -> [Date] #

enumFromThenTo :: Date -> Date -> Date -> [Date] #

Eq Date Source # 

Methods

(==) :: Date -> Date -> Bool #

(/=) :: Date -> Date -> Bool #

Data Date Source # 

Methods

gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Date -> c Date #

gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c Date #

toConstr :: Date -> Constr #

dataTypeOf :: Date -> DataType #

dataCast1 :: Typeable (* -> *) t => (forall d. Data d => c (t d)) -> Maybe (c Date) #

dataCast2 :: Typeable (* -> * -> *) t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c Date) #

gmapT :: (forall b. Data b => b -> b) -> Date -> Date #

gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Date -> r #

gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Date -> r #

gmapQ :: (forall d. Data d => d -> u) -> Date -> [u] #

gmapQi :: Int -> (forall d. Data d => d -> u) -> Date -> u #

gmapM :: Monad m => (forall d. Data d => d -> m d) -> Date -> m Date #

gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Date -> m Date #

gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Date -> m Date #

Ord Date Source # 

Methods

compare :: Date -> Date -> Ordering #

(<) :: Date -> Date -> Bool #

(<=) :: Date -> Date -> Bool #

(>) :: Date -> Date -> Bool #

(>=) :: Date -> Date -> Bool #

max :: Date -> Date -> Date #

min :: Date -> Date -> Date #

Show Date Source # 

Methods

showsPrec :: Int -> Date -> ShowS #

show :: Date -> String #

showList :: [Date] -> ShowS #

Ix Date Source # 

Methods

range :: (Date, Date) -> [Date] #

index :: (Date, Date) -> Date -> Int #

unsafeIndex :: (Date, Date) -> Date -> Int

inRange :: (Date, Date) -> Date -> Bool #

rangeSize :: (Date, Date) -> Int #

unsafeRangeSize :: (Date, Date) -> Int

ToJSON Date Source # 
FromJSON Date Source # 
NFData Date Source # 

Methods

rnf :: Date -> () #

ToHttpApiData Date Source # 
FromHttpApiData Date Source # 
FormatTime Date Source # 
ParseTime Date Source # 

Methods

buildTime :: TimeLocale -> [(Char, String)] -> Maybe Date #

MimeRender MimeMultipartFormData Date Source # 

_readDate :: (ParseTime t, Monad m) => String -> m t Source #

TI.parseTimeM True TI.defaultTimeLocale "%Y-%m-%d"

_showDate :: FormatTime t => t -> String Source #

TI.formatTime TI.defaultTimeLocale "%Y-%m-%d"

Byte/Binary Formatting

newtype ByteArray Source #

base64 encoded characters

Constructors

ByteArray 

Instances

Eq ByteArray Source # 
Data ByteArray Source # 

Methods

gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> ByteArray -> c ByteArray #

gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c ByteArray #

toConstr :: ByteArray -> Constr #

dataTypeOf :: ByteArray -> DataType #

dataCast1 :: Typeable (* -> *) t => (forall d. Data d => c (t d)) -> Maybe (c ByteArray) #

dataCast2 :: Typeable (* -> * -> *) t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c ByteArray) #

gmapT :: (forall b. Data b => b -> b) -> ByteArray -> ByteArray #

gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> ByteArray -> r #

gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> ByteArray -> r #

gmapQ :: (forall d. Data d => d -> u) -> ByteArray -> [u] #

gmapQi :: Int -> (forall d. Data d => d -> u) -> ByteArray -> u #

gmapM :: Monad m => (forall d. Data d => d -> m d) -> ByteArray -> m ByteArray #

gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> ByteArray -> m ByteArray #

gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> ByteArray -> m ByteArray #

Ord ByteArray Source # 
Show ByteArray Source # 
ToJSON ByteArray Source # 
FromJSON ByteArray Source # 
NFData ByteArray Source # 

Methods

rnf :: ByteArray -> () #

ToHttpApiData ByteArray Source # 
FromHttpApiData ByteArray Source # 
MimeRender MimeMultipartFormData ByteArray Source # 

_readByteArray :: Monad m => Text -> m ByteArray Source #

read base64 encoded characters

_showByteArray :: ByteArray -> Text Source #

show base64 encoded characters

newtype Binary Source #

any sequence of octets

Constructors

Binary 

Fields

Instances

Eq Binary Source # 

Methods

(==) :: Binary -> Binary -> Bool #

(/=) :: Binary -> Binary -> Bool #

Data Binary Source # 

Methods

gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Binary -> c Binary #

gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c Binary #

toConstr :: Binary -> Constr #

dataTypeOf :: Binary -> DataType #

dataCast1 :: Typeable (* -> *) t => (forall d. Data d => c (t d)) -> Maybe (c Binary) #

dataCast2 :: Typeable (* -> * -> *) t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c Binary) #

gmapT :: (forall b. Data b => b -> b) -> Binary -> Binary #

gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Binary -> r #

gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Binary -> r #

gmapQ :: (forall d. Data d => d -> u) -> Binary -> [u] #

gmapQi :: Int -> (forall d. Data d => d -> u) -> Binary -> u #

gmapM :: Monad m => (forall d. Data d => d -> m d) -> Binary -> m Binary #

gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Binary -> m Binary #

gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Binary -> m Binary #

Ord Binary Source # 
Show Binary Source # 
ToJSON Binary Source # 
FromJSON Binary Source # 
NFData Binary Source # 

Methods

rnf :: Binary -> () #

ToHttpApiData Binary Source # 
FromHttpApiData Binary Source # 
MimeRender MimeMultipartFormData Binary Source # 

Lens Type Aliases

type Lens_' s a = Lens_ s s a a Source #

type Lens_ s t a b = forall f. Functor f => (a -> f b) -> s -> f t Source #

\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-Logging.html b/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-Logging.html index b99e0a66fba..dec96646845 100644 --- a/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-Logging.html +++ b/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-Logging.html @@ -1,4 +1,4 @@ SwaggerPetstore.Logging

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Safe HaskellNone
LanguageHaskell2010

SwaggerPetstore.Logging

Description

Katip Logging functions

Type Aliases (for compatability)

type LogExecWithContext = forall m. MonadIO m => LogContext -> LogExec m Source #

Runs a Katip logging block with the Log environment

type LogExec m = forall a. KatipT m a -> m a Source #

A Katip logging block

type LogContext = LogEnv Source #

A Katip Log environment

type LogLevel = Severity Source #

A Katip Log severity

default logger

initLogContext :: IO LogContext Source #

the default log environment

runDefaultLogExecWithContext :: LogExecWithContext Source #

Runs a Katip logging block with the Log environment

stdout logger

stdoutLoggingExec :: LogExecWithContext Source #

Runs a Katip logging block with the Log environment

stdoutLoggingContext :: LogContext -> IO LogContext Source #

A Katip Log environment which targets stdout

stderr logger

stderrLoggingExec :: LogExecWithContext Source #

Runs a Katip logging block with the Log environment

stderrLoggingContext :: LogContext -> IO LogContext Source #

A Katip Log environment which targets stderr

Null logger

runNullLogExec :: LogExecWithContext Source #

Disables Katip logging

Log Msg

_log :: (Applicative m, Katip m) => Text -> LogLevel -> Text -> m () Source #

Log a katip message

Log Exceptions

logExceptions :: (Katip m, MonadCatch m, Applicative m) => Text -> m a -> m a Source #

re-throws exceptions after logging them

Log Level

\ No newline at end of file +

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Safe HaskellNone
LanguageHaskell2010

SwaggerPetstore.Logging

Description

Katip Logging functions

Type Aliases (for compatability)

type LogExecWithContext = forall m. MonadIO m => LogContext -> LogExec m Source #

Runs a Katip logging block with the Log environment

type LogExec m = forall a. KatipT m a -> m a Source #

A Katip logging block

type LogContext = LogEnv Source #

A Katip Log environment

type LogLevel = Severity Source #

A Katip Log severity

default logger

initLogContext :: IO LogContext Source #

the default log environment

runDefaultLogExecWithContext :: LogExecWithContext Source #

Runs a Katip logging block with the Log environment

stdout logger

stdoutLoggingExec :: LogExecWithContext Source #

Runs a Katip logging block with the Log environment

stdoutLoggingContext :: LogContext -> IO LogContext Source #

A Katip Log environment which targets stdout

stderr logger

stderrLoggingExec :: LogExecWithContext Source #

Runs a Katip logging block with the Log environment

stderrLoggingContext :: LogContext -> IO LogContext Source #

A Katip Log environment which targets stderr

Null logger

runNullLogExec :: LogExecWithContext Source #

Disables Katip logging

Log Msg

_log :: (Applicative m, Katip m) => Text -> LogLevel -> Text -> m () Source #

Log a katip message

Log Exceptions

logExceptions :: (Katip m, MonadCatch m, Applicative m) => Text -> m a -> m a Source #

re-throws exceptions after logging them

Log Level

\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-MimeTypes.html b/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-MimeTypes.html index c63828e7d60..fc9c2071f85 100644 --- a/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-MimeTypes.html +++ b/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-MimeTypes.html @@ -1,4 +1,4 @@ SwaggerPetstore.MimeTypes

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Safe HaskellNone
LanguageHaskell2010

SwaggerPetstore.MimeTypes

Description

 

Consumes Class

Produces Class

class MimeType mtype => Produces req mtype Source #

Instances

Produces UpdateUser MimeXML Source #
application/xml
Produces UpdateUser MimeJSON Source #
application/json
Produces LogoutUser MimeXML Source #
application/xml
Produces LogoutUser MimeJSON Source #
application/json
Produces LoginUser MimeXML Source #
application/xml
Produces LoginUser MimeJSON Source #
application/json
Produces GetUserByName MimeXML Source #
application/xml
Produces GetUserByName MimeJSON Source #
application/json
Produces DeleteUser MimeXML Source #
application/xml
Produces DeleteUser MimeJSON Source #
application/json
Produces CreateUsersWithListInput MimeXML Source #
application/xml
Produces CreateUsersWithListInput MimeJSON Source #
application/json
Produces CreateUsersWithArrayInput MimeXML Source #
application/xml
Produces CreateUsersWithArrayInput MimeJSON Source #
application/json
Produces CreateUser MimeXML Source #
application/xml
Produces CreateUser MimeJSON Source #
application/json
Produces PlaceOrder MimeXML Source #
application/xml
Produces PlaceOrder MimeJSON Source #
application/json
Produces GetOrderById MimeXML Source #
application/xml
Produces GetOrderById MimeJSON Source #
application/json
Produces GetInventory MimeJSON Source #
application/json
Produces DeleteOrder MimeXML Source #
application/xml
Produces DeleteOrder MimeJSON Source #
application/json
Produces UploadFile MimeJSON Source #
application/json
Produces UpdatePetWithForm MimeXML Source #
application/xml
Produces UpdatePetWithForm MimeJSON Source #
application/json
Produces UpdatePet MimeXML Source #
application/xml
Produces UpdatePet MimeJSON Source #
application/json
Produces GetPetById MimeXML Source #
application/xml
Produces GetPetById MimeJSON Source #
application/json
Produces FindPetsByTags MimeXML Source #
application/xml
Produces FindPetsByTags MimeJSON Source #
application/json
Produces FindPetsByStatus MimeXML Source #
application/xml
Produces FindPetsByStatus MimeJSON Source #
application/json
Produces DeletePet MimeXML Source #
application/xml
Produces DeletePet MimeJSON Source #
application/json
Produces AddPet MimeXML Source #
application/xml
Produces AddPet MimeJSON Source #
application/json
Produces TestClassname MimeJSON Source #
application/json
Produces TestEnumParameters MimeAny Source #
*/*
Produces TestEndpointParameters MimeXmlCharsetutf8 Source #
application/xml; charset=utf-8
Produces TestEndpointParameters MimeJsonCharsetutf8 Source #
application/json; charset=utf-8
Produces TestClientModel MimeJSON Source #
application/json
Produces TestSpecialTags MimeJSON Source #
application/json

Default Mime Types

data MimeJSON Source #

Constructors

MimeJSON 

Instances

MimeType MimeJSON Source #
application/json; charset=utf-8
FromJSON a => MimeUnrender MimeJSON a Source #
A.eitherDecode
ToJSON a => MimeRender MimeJSON a Source #

encode

Produces UpdateUser MimeJSON Source #
application/json
Produces LogoutUser MimeJSON Source #
application/json
Produces LoginUser MimeJSON Source #
application/json
Produces GetUserByName MimeJSON Source #
application/json
Produces DeleteUser MimeJSON Source #
application/json
Produces CreateUsersWithListInput MimeJSON Source #
application/json
Produces CreateUsersWithArrayInput MimeJSON Source #
application/json
Produces CreateUser MimeJSON Source #
application/json
Produces PlaceOrder MimeJSON Source #
application/json
Produces GetOrderById MimeJSON Source #
application/json
Produces GetInventory MimeJSON Source #
application/json
Produces DeleteOrder MimeJSON Source #
application/json
Produces UploadFile MimeJSON Source #
application/json
Produces UpdatePetWithForm MimeJSON Source #
application/json
Produces UpdatePet MimeJSON Source #
application/json
Produces GetPetById MimeJSON Source #
application/json
Produces FindPetsByTags MimeJSON Source #
application/json
Produces FindPetsByStatus MimeJSON Source #
application/json
Produces DeletePet MimeJSON Source #
application/json
Produces AddPet MimeJSON Source #
application/json
Produces TestClassname MimeJSON Source #
application/json
Produces TestClientModel MimeJSON Source #
application/json
Produces TestSpecialTags MimeJSON Source #
application/json
Consumes UpdatePet MimeJSON Source #
application/json
Consumes AddPet MimeJSON Source #
application/json
Consumes TestClassname MimeJSON Source #
application/json
Consumes TestJsonFormData MimeJSON Source #
application/json
Consumes TestClientModel MimeJSON Source #
application/json
Consumes TestSpecialTags MimeJSON Source #
application/json

data MimePlainText Source #

Constructors

MimePlainText 

Instances

MimeType MimePlainText Source #
text/plain; charset=utf-8
MimeUnrender MimePlainText ByteString Source #
P.Right . P.id
MimeUnrender MimePlainText String Source #
P.Right . BCL.unpack
MimeUnrender MimePlainText Text Source #
P.left P.show . TL.decodeUtf8'
MimeRender MimePlainText ByteString Source #
P.id
MimeRender MimePlainText String Source #
BCL.pack
MimeRender MimePlainText Text Source #
BL.fromStrict . T.encodeUtf8

data MimeMultipartFormData Source #

Constructors

MimeMultipartFormData 

Instances

MimeType MimeMultipartFormData Source #
multipart/form-data
MimeRender MimeMultipartFormData Bool Source # 
MimeRender MimeMultipartFormData Char Source # 
MimeRender MimeMultipartFormData Double Source # 
MimeRender MimeMultipartFormData Float Source # 
MimeRender MimeMultipartFormData Int Source # 
MimeRender MimeMultipartFormData Integer Source # 
MimeRender MimeMultipartFormData ByteString Source # 
MimeRender MimeMultipartFormData String Source # 
MimeRender MimeMultipartFormData Text Source # 
MimeRender MimeMultipartFormData Binary Source # 
MimeRender MimeMultipartFormData ByteArray Source # 
MimeRender MimeMultipartFormData Date Source # 
MimeRender MimeMultipartFormData DateTime Source # 
Consumes UploadFile MimeMultipartFormData Source #
multipart/form-data

data MimeOctetStream Source #

Constructors

MimeOctetStream 

Instances

MimeType MimeOctetStream Source #
application/octet-stream
MimeUnrender MimeOctetStream ByteString Source #
P.Right . P.id
MimeUnrender MimeOctetStream String Source #
P.Right . BCL.unpack
MimeUnrender MimeOctetStream Text Source #
P.left P.show . T.decodeUtf8' . BL.toStrict
MimeRender MimeOctetStream ByteString Source #
P.id
MimeRender MimeOctetStream String Source #
BCL.pack
MimeRender MimeOctetStream Text Source #
BL.fromStrict . T.encodeUtf8

MimeType Class

class Typeable mtype => MimeType mtype where Source #

Minimal complete definition

mimeType | mimeTypes

Instances

MimeType MimeAny Source #
"*/*"
MimeType MimeNoContent Source # 
MimeType MimeOctetStream Source #
application/octet-stream
MimeType MimeMultipartFormData Source #
multipart/form-data
MimeType MimeFormUrlEncoded Source #
application/x-www-form-urlencoded
MimeType MimePlainText Source #
text/plain; charset=utf-8
MimeType MimeXML Source #
application/xml; charset=utf-8
MimeType MimeJSON Source #
application/json; charset=utf-8
MimeType MimeXmlCharsetutf8 Source #
application/xml; charset=utf-8
MimeType MimeJsonCharsetutf8 Source #
application/json; charset=utf-8

MimeRender Class

class MimeType mtype => MimeRender mtype x where Source #

Minimal complete definition

mimeRender

Methods

mimeRender :: Proxy mtype -> x -> ByteString Source #

mimeRender' :: mtype -> x -> ByteString Source #

Instances

MimeRender MimeNoContent NoContent Source #
P.Right . P.const NoContent
MimeRender MimeOctetStream ByteString Source #
P.id
MimeRender MimeOctetStream String Source #
BCL.pack
MimeRender MimeOctetStream Text Source #
BL.fromStrict . T.encodeUtf8
MimeRender MimeMultipartFormData Bool Source # 
MimeRender MimeMultipartFormData Char Source # 
MimeRender MimeMultipartFormData Double Source # 
MimeRender MimeMultipartFormData Float Source # 
MimeRender MimeMultipartFormData Int Source # 
MimeRender MimeMultipartFormData Integer Source # 
MimeRender MimeMultipartFormData ByteString Source # 
MimeRender MimeMultipartFormData String Source # 
MimeRender MimeMultipartFormData Text Source # 
MimeRender MimeMultipartFormData Binary Source # 
MimeRender MimeMultipartFormData ByteArray Source # 
MimeRender MimeMultipartFormData Date Source # 
MimeRender MimeMultipartFormData DateTime Source # 
ToForm a => MimeRender MimeFormUrlEncoded a Source #
WH.urlEncodeAsForm
MimeRender MimePlainText ByteString Source #
P.id
MimeRender MimePlainText String Source #
BCL.pack
MimeRender MimePlainText Text Source #
BL.fromStrict . T.encodeUtf8
ToJSON a => MimeRender MimeJSON a Source #

encode

ToJSON a => MimeRender MimeJsonCharsetutf8 a Source # 

MimeUnrender Class

class MimeType mtype => MimeUnrender mtype o where Source #

Minimal complete definition

mimeUnrender

Instances

MimeUnrender MimeNoContent NoContent Source #
P.Right . P.const NoContent
MimeUnrender MimeOctetStream ByteString Source #
P.Right . P.id
MimeUnrender MimeOctetStream String Source #
P.Right . BCL.unpack
MimeUnrender MimeOctetStream Text Source #
P.left P.show . T.decodeUtf8' . BL.toStrict
FromForm a => MimeUnrender MimeFormUrlEncoded a Source #
P.left T.unpack . WH.urlDecodeAsForm
MimeUnrender MimePlainText ByteString Source #
P.Right . P.id
MimeUnrender MimePlainText String Source #
P.Right . BCL.unpack
MimeUnrender MimePlainText Text Source #
P.left P.show . TL.decodeUtf8'
FromJSON a => MimeUnrender MimeJSON a Source #
A.eitherDecode
FromJSON a => MimeUnrender MimeJsonCharsetutf8 a Source # 
\ No newline at end of file +

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Safe HaskellNone
LanguageHaskell2010

SwaggerPetstore.MimeTypes

Description

 

ContentType MimeType

data ContentType a Source #

Constructors

MimeType a => ContentType 

Fields

Accept MimeType

data Accept a Source #

Constructors

MimeType a => Accept 

Fields

Consumes Class

Produces Class

class MimeType mtype => Produces req mtype Source #

Instances

Produces UpdateUser MimeXML Source #
application/xml
Produces UpdateUser MimeJSON Source #
application/json
Produces LogoutUser MimeXML Source #
application/xml
Produces LogoutUser MimeJSON Source #
application/json
Produces LoginUser MimeXML Source #
application/xml
Produces LoginUser MimeJSON Source #
application/json
Produces GetUserByName MimeXML Source #
application/xml
Produces GetUserByName MimeJSON Source #
application/json
Produces DeleteUser MimeXML Source #
application/xml
Produces DeleteUser MimeJSON Source #
application/json
Produces CreateUsersWithListInput MimeXML Source #
application/xml
Produces CreateUsersWithListInput MimeJSON Source #
application/json
Produces CreateUsersWithArrayInput MimeXML Source #
application/xml
Produces CreateUsersWithArrayInput MimeJSON Source #
application/json
Produces CreateUser MimeXML Source #
application/xml
Produces CreateUser MimeJSON Source #
application/json
Produces PlaceOrder MimeXML Source #
application/xml
Produces PlaceOrder MimeJSON Source #
application/json
Produces GetOrderById MimeXML Source #
application/xml
Produces GetOrderById MimeJSON Source #
application/json
Produces GetInventory MimeJSON Source #
application/json
Produces DeleteOrder MimeXML Source #
application/xml
Produces DeleteOrder MimeJSON Source #
application/json
Produces UploadFile MimeJSON Source #
application/json
Produces UpdatePetWithForm MimeXML Source #
application/xml
Produces UpdatePetWithForm MimeJSON Source #
application/json
Produces UpdatePet MimeXML Source #
application/xml
Produces UpdatePet MimeJSON Source #
application/json
Produces GetPetById MimeXML Source #
application/xml
Produces GetPetById MimeJSON Source #
application/json
Produces FindPetsByTags MimeXML Source #
application/xml
Produces FindPetsByTags MimeJSON Source #
application/json
Produces FindPetsByStatus MimeXML Source #
application/xml
Produces FindPetsByStatus MimeJSON Source #
application/json
Produces DeletePet MimeXML Source #
application/xml
Produces DeletePet MimeJSON Source #
application/json
Produces AddPet MimeXML Source #
application/xml
Produces AddPet MimeJSON Source #
application/json
Produces TestClassname MimeJSON Source #
application/json
Produces TestEnumParameters MimeAny Source #
*/*
Produces TestEndpointParameters MimeXmlCharsetutf8 Source #
application/xml; charset=utf-8
Produces TestEndpointParameters MimeJsonCharsetutf8 Source #
application/json; charset=utf-8
Produces TestClientModel MimeJSON Source #
application/json
Produces TestSpecialTags MimeJSON Source #
application/json

Default Mime Types

data MimeJSON Source #

Constructors

MimeJSON 

Instances

MimeType MimeJSON Source #
application/json; charset=utf-8
FromJSON a => MimeUnrender MimeJSON a Source #
A.eitherDecode
ToJSON a => MimeRender MimeJSON a Source #

encode

Produces UpdateUser MimeJSON Source #
application/json
Produces LogoutUser MimeJSON Source #
application/json
Produces LoginUser MimeJSON Source #
application/json
Produces GetUserByName MimeJSON Source #
application/json
Produces DeleteUser MimeJSON Source #
application/json
Produces CreateUsersWithListInput MimeJSON Source #
application/json
Produces CreateUsersWithArrayInput MimeJSON Source #
application/json
Produces CreateUser MimeJSON Source #
application/json
Produces PlaceOrder MimeJSON Source #
application/json
Produces GetOrderById MimeJSON Source #
application/json
Produces GetInventory MimeJSON Source #
application/json
Produces DeleteOrder MimeJSON Source #
application/json
Produces UploadFile MimeJSON Source #
application/json
Produces UpdatePetWithForm MimeJSON Source #
application/json
Produces UpdatePet MimeJSON Source #
application/json
Produces GetPetById MimeJSON Source #
application/json
Produces FindPetsByTags MimeJSON Source #
application/json
Produces FindPetsByStatus MimeJSON Source #
application/json
Produces DeletePet MimeJSON Source #
application/json
Produces AddPet MimeJSON Source #
application/json
Produces TestClassname MimeJSON Source #
application/json
Produces TestClientModel MimeJSON Source #
application/json
Produces TestSpecialTags MimeJSON Source #
application/json
Consumes UpdatePet MimeJSON Source #
application/json
Consumes AddPet MimeJSON Source #
application/json
Consumes TestClassname MimeJSON Source #
application/json
Consumes TestJsonFormData MimeJSON Source #
application/json
Consumes TestInlineAdditionalProperties MimeJSON Source #
application/json
Consumes TestClientModel MimeJSON Source #
application/json
Consumes TestSpecialTags MimeJSON Source #
application/json

data MimePlainText Source #

Constructors

MimePlainText 

Instances

MimeType MimePlainText Source #
text/plain; charset=utf-8
MimeUnrender MimePlainText ByteString Source #
P.Right . P.id
MimeUnrender MimePlainText String Source #
P.Right . BCL.unpack
MimeUnrender MimePlainText Text Source #
P.left P.show . TL.decodeUtf8'
MimeRender MimePlainText ByteString Source #
P.id
MimeRender MimePlainText String Source #
BCL.pack
MimeRender MimePlainText Text Source #
BL.fromStrict . T.encodeUtf8

data MimeMultipartFormData Source #

Constructors

MimeMultipartFormData 

Instances

MimeType MimeMultipartFormData Source #
multipart/form-data
MimeRender MimeMultipartFormData Bool Source # 
MimeRender MimeMultipartFormData Char Source # 
MimeRender MimeMultipartFormData Double Source # 
MimeRender MimeMultipartFormData Float Source # 
MimeRender MimeMultipartFormData Int Source # 
MimeRender MimeMultipartFormData Integer Source # 
MimeRender MimeMultipartFormData ByteString Source # 
MimeRender MimeMultipartFormData String Source # 
MimeRender MimeMultipartFormData Text Source # 
MimeRender MimeMultipartFormData Binary Source # 
MimeRender MimeMultipartFormData ByteArray Source # 
MimeRender MimeMultipartFormData Date Source # 
MimeRender MimeMultipartFormData DateTime Source # 
MimeRender MimeMultipartFormData OuterEnum Source # 
MimeRender MimeMultipartFormData EnumClass Source # 
MimeRender MimeMultipartFormData E'Status2 Source # 
MimeRender MimeMultipartFormData E'Status Source # 
MimeRender MimeMultipartFormData E'JustSymbol Source # 
MimeRender MimeMultipartFormData E'Inner2 Source # 
MimeRender MimeMultipartFormData E'Inner Source # 
MimeRender MimeMultipartFormData E'EnumString Source # 
MimeRender MimeMultipartFormData E'EnumQueryInteger Source # 
MimeRender MimeMultipartFormData E'EnumNumber Source # 
MimeRender MimeMultipartFormData E'EnumInteger Source # 
MimeRender MimeMultipartFormData E'EnumFormString Source # 
MimeRender MimeMultipartFormData E'ArrayEnum Source # 
Consumes UploadFile MimeMultipartFormData Source #
multipart/form-data

data MimeOctetStream Source #

Constructors

MimeOctetStream 

Instances

MimeType MimeOctetStream Source #
application/octet-stream
MimeUnrender MimeOctetStream ByteString Source #
P.Right . P.id
MimeUnrender MimeOctetStream String Source #
P.Right . BCL.unpack
MimeUnrender MimeOctetStream Text Source #
P.left P.show . T.decodeUtf8' . BL.toStrict
MimeRender MimeOctetStream ByteString Source #
P.id
MimeRender MimeOctetStream String Source #
BCL.pack
MimeRender MimeOctetStream Text Source #
BL.fromStrict . T.encodeUtf8

MimeType Class

class Typeable mtype => MimeType mtype where Source #

Minimal complete definition

mimeType | mimeTypes

Instances

MimeType MimeAny Source #
"*/*"
MimeType MimeNoContent Source # 
MimeType MimeOctetStream Source #
application/octet-stream
MimeType MimeMultipartFormData Source #
multipart/form-data
MimeType MimeFormUrlEncoded Source #
application/x-www-form-urlencoded
MimeType MimePlainText Source #
text/plain; charset=utf-8
MimeType MimeXML Source #
application/xml; charset=utf-8
MimeType MimeJSON Source #
application/json; charset=utf-8
MimeType MimeXmlCharsetutf8 Source #
application/xml; charset=utf-8
MimeType MimeJsonCharsetutf8 Source #
application/json; charset=utf-8

MimeRender Class

class MimeType mtype => MimeRender mtype x where Source #

Minimal complete definition

mimeRender

Methods

mimeRender :: Proxy mtype -> x -> ByteString Source #

mimeRender' :: mtype -> x -> ByteString Source #

Instances

MimeRender MimeNoContent NoContent Source #
P.Right . P.const NoContent
MimeRender MimeOctetStream ByteString Source #
P.id
MimeRender MimeOctetStream String Source #
BCL.pack
MimeRender MimeOctetStream Text Source #
BL.fromStrict . T.encodeUtf8
MimeRender MimeMultipartFormData Bool Source # 
MimeRender MimeMultipartFormData Char Source # 
MimeRender MimeMultipartFormData Double Source # 
MimeRender MimeMultipartFormData Float Source # 
MimeRender MimeMultipartFormData Int Source # 
MimeRender MimeMultipartFormData Integer Source # 
MimeRender MimeMultipartFormData ByteString Source # 
MimeRender MimeMultipartFormData String Source # 
MimeRender MimeMultipartFormData Text Source # 
MimeRender MimeMultipartFormData Binary Source # 
MimeRender MimeMultipartFormData ByteArray Source # 
MimeRender MimeMultipartFormData Date Source # 
MimeRender MimeMultipartFormData DateTime Source # 
MimeRender MimeMultipartFormData OuterEnum Source # 
MimeRender MimeMultipartFormData EnumClass Source # 
MimeRender MimeMultipartFormData E'Status2 Source # 
MimeRender MimeMultipartFormData E'Status Source # 
MimeRender MimeMultipartFormData E'JustSymbol Source # 
MimeRender MimeMultipartFormData E'Inner2 Source # 
MimeRender MimeMultipartFormData E'Inner Source # 
MimeRender MimeMultipartFormData E'EnumString Source # 
MimeRender MimeMultipartFormData E'EnumQueryInteger Source # 
MimeRender MimeMultipartFormData E'EnumNumber Source # 
MimeRender MimeMultipartFormData E'EnumInteger Source # 
MimeRender MimeMultipartFormData E'EnumFormString Source # 
MimeRender MimeMultipartFormData E'ArrayEnum Source # 
ToForm a => MimeRender MimeFormUrlEncoded a Source #
WH.urlEncodeAsForm
MimeRender MimePlainText ByteString Source #
P.id
MimeRender MimePlainText String Source #
BCL.pack
MimeRender MimePlainText Text Source #
BL.fromStrict . T.encodeUtf8
ToJSON a => MimeRender MimeJSON a Source #

encode

ToJSON a => MimeRender MimeJsonCharsetutf8 a Source # 

MimeUnrender Class

class MimeType mtype => MimeUnrender mtype o where Source #

Minimal complete definition

mimeUnrender

Instances

MimeUnrender MimeNoContent NoContent Source #
P.Right . P.const NoContent
MimeUnrender MimeOctetStream ByteString Source #
P.Right . P.id
MimeUnrender MimeOctetStream String Source #
P.Right . BCL.unpack
MimeUnrender MimeOctetStream Text Source #
P.left P.show . T.decodeUtf8' . BL.toStrict
FromForm a => MimeUnrender MimeFormUrlEncoded a Source #
P.left T.unpack . WH.urlDecodeAsForm
MimeUnrender MimePlainText ByteString Source #
P.Right . P.id
MimeUnrender MimePlainText String Source #
P.Right . BCL.unpack
MimeUnrender MimePlainText Text Source #
P.left P.show . TL.decodeUtf8'
FromJSON a => MimeUnrender MimeJSON a Source #
A.eitherDecode
FromJSON a => MimeUnrender MimeJsonCharsetutf8 a Source # 
\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-Model.html b/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-Model.html index ebfe14e31db..9769727f502 100644 --- a/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-Model.html +++ b/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-Model.html @@ -1,8 +1,10 @@ SwaggerPetstore.Model

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Safe HaskellNone
LanguageHaskell2010

SwaggerPetstore.Model

Description

 

Synopsis

Models

AdditionalPropertiesClass

mkAdditionalPropertiesClass :: AdditionalPropertiesClass Source #

Construct a value of type AdditionalPropertiesClass (by applying it's required fields, if any)

Animal

data Animal Source #

Animal

Constructors

Animal 

Fields

mkAnimal Source #

Arguments

:: Text

animalClassName

-> Animal 

Construct a value of type Animal (by applying it's required fields, if any)

AnimalFarm

mkAnimalFarm :: AnimalFarm Source #

Construct a value of type AnimalFarm (by applying it's required fields, if any)

ApiResponse

mkApiResponse :: ApiResponse Source #

Construct a value of type ApiResponse (by applying it's required fields, if any)

ArrayOfArrayOfNumberOnly

mkArrayOfArrayOfNumberOnly :: ArrayOfArrayOfNumberOnly Source #

Construct a value of type ArrayOfArrayOfNumberOnly (by applying it's required fields, if any)

ArrayOfNumberOnly

mkArrayOfNumberOnly :: ArrayOfNumberOnly Source #

Construct a value of type ArrayOfNumberOnly (by applying it's required fields, if any)

ArrayTest

mkArrayTest :: ArrayTest Source #

Construct a value of type ArrayTest (by applying it's required fields, if any)

Capitalization

mkCapitalization :: Capitalization Source #

Construct a value of type Capitalization (by applying it's required fields, if any)

Category

mkCategory :: Category Source #

Construct a value of type Category (by applying it's required fields, if any)

ClassModel

data ClassModel Source #

ClassModel - Model for testing model with "_class" property

Constructors

ClassModel 

Fields

mkClassModel :: ClassModel Source #

Construct a value of type ClassModel (by applying it's required fields, if any)

Client

data Client Source #

Client

Constructors

Client 

Fields

Instances

Eq Client Source # 

Methods

(==) :: Client -> Client -> Bool #

(/=) :: Client -> Client -> Bool #

Show Client Source # 
ToJSON Client Source #

ToJSON Client

FromJSON Client Source #

FromJSON Client

HasBodyParam TestClassname Client Source #

Body Param "body" - client model

Methods

setBodyParam :: (Consumes TestClassname contentType, MimeRender contentType Client) => SwaggerPetstoreRequest TestClassname contentType res -> Client -> SwaggerPetstoreRequest TestClassname contentType res Source #

HasBodyParam TestClientModel Client Source #

Body Param "body" - client model

HasBodyParam TestSpecialTags Client Source #

Body Param "body" - client model

mkClient :: Client Source #

Construct a value of type Client (by applying it's required fields, if any)

EnumArrays

mkEnumArrays :: EnumArrays Source #

Construct a value of type EnumArrays (by applying it's required fields, if any)

EnumClass

mkEnumClass :: EnumClass Source #

Construct a value of type EnumClass (by applying it's required fields, if any)

EnumTest

mkEnumTest :: EnumTest Source #

Construct a value of type EnumTest (by applying it's required fields, if any)

FormatTest

mkFormatTest Source #

Construct a value of type FormatTest (by applying it's required fields, if any)

HasOnlyReadOnly

mkHasOnlyReadOnly :: HasOnlyReadOnly Source #

Construct a value of type HasOnlyReadOnly (by applying it's required fields, if any)

MapTest

data MapTest Source #

MapTest

Constructors

MapTest 

Fields

mkMapTest :: MapTest Source #

Construct a value of type MapTest (by applying it's required fields, if any)

MixedPropertiesAndAdditionalPropertiesClass

data MixedPropertiesAndAdditionalPropertiesClass Source #

MixedPropertiesAndAdditionalPropertiesClass

Model200Response

mkModel200Response :: Model200Response Source #

Construct a value of type Model200Response (by applying it's required fields, if any)

ModelList

mkModelList :: ModelList Source #

Construct a value of type ModelList (by applying it's required fields, if any)

ModelReturn

mkModelReturn :: ModelReturn Source #

Construct a value of type ModelReturn (by applying it's required fields, if any)

Name

data Name Source #

Name - Model for testing model name same as property name

Constructors

Name 

Fields

Instances

mkName Source #

Arguments

:: Int

nameName

-> Name 

Construct a value of type Name (by applying it's required fields, if any)

NumberOnly

mkNumberOnly :: NumberOnly Source #

Construct a value of type NumberOnly (by applying it's required fields, if any)

Order

data Order Source #

Order

Constructors

Order 

Fields

Instances

Eq Order Source # 

Methods

(==) :: Order -> Order -> Bool #

(/=) :: Order -> Order -> Bool #

Show Order Source # 

Methods

showsPrec :: Int -> Order -> ShowS #

show :: Order -> String #

showList :: [Order] -> ShowS #

ToJSON Order Source #

ToJSON Order

FromJSON Order Source #

FromJSON Order

HasBodyParam PlaceOrder Order Source #

Body Param "body" - order placed for purchasing the pet

Methods

setBodyParam :: (Consumes PlaceOrder contentType, MimeRender contentType Order) => SwaggerPetstoreRequest PlaceOrder contentType res -> Order -> SwaggerPetstoreRequest PlaceOrder contentType res Source #

mkOrder :: Order Source #

Construct a value of type Order (by applying it's required fields, if any)

OuterBoolean

OuterComposite

mkOuterComposite :: OuterComposite Source #

Construct a value of type OuterComposite (by applying it's required fields, if any)

OuterEnum

mkOuterEnum :: OuterEnum Source #

Construct a value of type OuterEnum (by applying it's required fields, if any)

OuterNumber

OuterString

Pet

data Pet Source #

Pet

Constructors

Pet 

Fields

Instances

Eq Pet Source # 

Methods

(==) :: Pet -> Pet -> Bool #

(/=) :: Pet -> Pet -> Bool #

Show Pet Source # 

Methods

showsPrec :: Int -> Pet -> ShowS #

show :: Pet -> String #

showList :: [Pet] -> ShowS #

ToJSON Pet Source #

ToJSON Pet

FromJSON Pet Source #

FromJSON Pet

HasBodyParam UpdatePet Pet Source #

Body Param "body" - Pet object that needs to be added to the store

Methods

setBodyParam :: (Consumes UpdatePet contentType, MimeRender contentType Pet) => SwaggerPetstoreRequest UpdatePet contentType res -> Pet -> SwaggerPetstoreRequest UpdatePet contentType res Source #

HasBodyParam AddPet Pet Source #

Body Param "body" - Pet object that needs to be added to the store

Methods

setBodyParam :: (Consumes AddPet contentType, MimeRender contentType Pet) => SwaggerPetstoreRequest AddPet contentType res -> Pet -> SwaggerPetstoreRequest AddPet contentType res Source #

mkPet Source #

Arguments

:: Text

petName

-> [Text]

petPhotoUrls

-> Pet 

Construct a value of type Pet (by applying it's required fields, if any)

ReadOnlyFirst

mkReadOnlyFirst :: ReadOnlyFirst Source #

Construct a value of type ReadOnlyFirst (by applying it's required fields, if any)

SpecialModelName

mkSpecialModelName :: SpecialModelName Source #

Construct a value of type SpecialModelName (by applying it's required fields, if any)

Tag

data Tag Source #

Tag

Constructors

Tag 

Fields

Instances

Eq Tag Source # 

Methods

(==) :: Tag -> Tag -> Bool #

(/=) :: Tag -> Tag -> Bool #

Show Tag Source # 

Methods

showsPrec :: Int -> Tag -> ShowS #

show :: Tag -> String #

showList :: [Tag] -> ShowS #

ToJSON Tag Source #

ToJSON Tag

FromJSON Tag Source #

FromJSON Tag

mkTag :: Tag Source #

Construct a value of type Tag (by applying it's required fields, if any)

User

data User Source #

User

Constructors

User 

Fields

Instances

Eq User Source # 

Methods

(==) :: User -> User -> Bool #

(/=) :: User -> User -> Bool #

Show User Source # 

Methods

showsPrec :: Int -> User -> ShowS #

show :: User -> String #

showList :: [User] -> ShowS #

ToJSON User Source #

ToJSON User

FromJSON User Source #

FromJSON User

HasBodyParam UpdateUser User Source #

Body Param "body" - Updated user object

Methods

setBodyParam :: (Consumes UpdateUser contentType, MimeRender contentType User) => SwaggerPetstoreRequest UpdateUser contentType res -> User -> SwaggerPetstoreRequest UpdateUser contentType res Source #

HasBodyParam CreateUser User Source #

Body Param "body" - Created user object

Methods

setBodyParam :: (Consumes CreateUser contentType, MimeRender contentType User) => SwaggerPetstoreRequest CreateUser contentType res -> User -> SwaggerPetstoreRequest CreateUser contentType res Source #

mkUser :: User Source #

Construct a value of type User (by applying it's required fields, if any)

Cat

data Cat Source #

Cat

Constructors

Cat 

Fields

Instances

Eq Cat Source # 

Methods

(==) :: Cat -> Cat -> Bool #

(/=) :: Cat -> Cat -> Bool #

Show Cat Source # 

Methods

showsPrec :: Int -> Cat -> ShowS #

show :: Cat -> String #

showList :: [Cat] -> ShowS #

ToJSON Cat Source #

ToJSON Cat

FromJSON Cat Source #

FromJSON Cat

mkCat Source #

Arguments

:: Text

catClassName

-> Cat 

Construct a value of type Cat (by applying it's required fields, if any)

Dog

data Dog Source #

Dog

Constructors

Dog 

Fields

Instances

Eq Dog Source # 

Methods

(==) :: Dog -> Dog -> Bool #

(/=) :: Dog -> Dog -> Bool #

Show Dog Source # 

Methods

showsPrec :: Int -> Dog -> ShowS #

show :: Dog -> String #

showList :: [Dog] -> ShowS #

ToJSON Dog Source #

ToJSON Dog

FromJSON Dog Source #

FromJSON Dog

mkDog Source #

Arguments

:: Text

dogClassName

-> Dog 

Construct a value of type Dog (by applying it's required fields, if any)

\ No newline at end of file +

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Safe HaskellNone
LanguageHaskell2010

SwaggerPetstore.Model

Description

 

Synopsis

Models

AdditionalPropertiesClass

mkAdditionalPropertiesClass :: AdditionalPropertiesClass Source #

Construct a value of type AdditionalPropertiesClass (by applying it's required fields, if any)

Animal

data Animal Source #

Animal

Constructors

Animal 

Fields

mkAnimal Source #

Arguments

:: Text

animalClassName

-> Animal 

Construct a value of type Animal (by applying it's required fields, if any)

AnimalFarm

mkAnimalFarm :: AnimalFarm Source #

Construct a value of type AnimalFarm (by applying it's required fields, if any)

ApiResponse

mkApiResponse :: ApiResponse Source #

Construct a value of type ApiResponse (by applying it's required fields, if any)

ArrayOfArrayOfNumberOnly

mkArrayOfArrayOfNumberOnly :: ArrayOfArrayOfNumberOnly Source #

Construct a value of type ArrayOfArrayOfNumberOnly (by applying it's required fields, if any)

ArrayOfNumberOnly

mkArrayOfNumberOnly :: ArrayOfNumberOnly Source #

Construct a value of type ArrayOfNumberOnly (by applying it's required fields, if any)

ArrayTest

mkArrayTest :: ArrayTest Source #

Construct a value of type ArrayTest (by applying it's required fields, if any)

Capitalization

mkCapitalization :: Capitalization Source #

Construct a value of type Capitalization (by applying it's required fields, if any)

Category

mkCategory :: Category Source #

Construct a value of type Category (by applying it's required fields, if any)

ClassModel

data ClassModel Source #

ClassModel + Model for testing model with "_class" property

Constructors

ClassModel 

Fields

mkClassModel :: ClassModel Source #

Construct a value of type ClassModel (by applying it's required fields, if any)

Client

data Client Source #

Client

Constructors

Client 

Fields

Instances

Eq Client Source # 

Methods

(==) :: Client -> Client -> Bool #

(/=) :: Client -> Client -> Bool #

Show Client Source # 
ToJSON Client Source #

ToJSON Client

FromJSON Client Source #

FromJSON Client

HasBodyParam TestClassname Client Source #

Body Param "body" - client model

Methods

setBodyParam :: (Consumes TestClassname contentType, MimeRender contentType Client) => SwaggerPetstoreRequest TestClassname contentType res accept -> Client -> SwaggerPetstoreRequest TestClassname contentType res accept Source #

HasBodyParam TestClientModel Client Source #

Body Param "body" - client model

Methods

setBodyParam :: (Consumes TestClientModel contentType, MimeRender contentType Client) => SwaggerPetstoreRequest TestClientModel contentType res accept -> Client -> SwaggerPetstoreRequest TestClientModel contentType res accept Source #

HasBodyParam TestSpecialTags Client Source #

Body Param "body" - client model

Methods

setBodyParam :: (Consumes TestSpecialTags contentType, MimeRender contentType Client) => SwaggerPetstoreRequest TestSpecialTags contentType res accept -> Client -> SwaggerPetstoreRequest TestSpecialTags contentType res accept Source #

mkClient :: Client Source #

Construct a value of type Client (by applying it's required fields, if any)

EnumArrays

mkEnumArrays :: EnumArrays Source #

Construct a value of type EnumArrays (by applying it's required fields, if any)

EnumTest

mkEnumTest :: EnumTest Source #

Construct a value of type EnumTest (by applying it's required fields, if any)

FormatTest

mkFormatTest Source #

Construct a value of type FormatTest (by applying it's required fields, if any)

HasOnlyReadOnly

mkHasOnlyReadOnly :: HasOnlyReadOnly Source #

Construct a value of type HasOnlyReadOnly (by applying it's required fields, if any)

MapTest

data MapTest Source #

MapTest

Constructors

MapTest 

Fields

mkMapTest :: MapTest Source #

Construct a value of type MapTest (by applying it's required fields, if any)

MixedPropertiesAndAdditionalPropertiesClass

data MixedPropertiesAndAdditionalPropertiesClass Source #

MixedPropertiesAndAdditionalPropertiesClass

Model200Response

mkModel200Response :: Model200Response Source #

Construct a value of type Model200Response (by applying it's required fields, if any)

ModelList

mkModelList :: ModelList Source #

Construct a value of type ModelList (by applying it's required fields, if any)

ModelReturn

mkModelReturn :: ModelReturn Source #

Construct a value of type ModelReturn (by applying it's required fields, if any)

Name

data Name Source #

Name + Model for testing model name same as property name

Constructors

Name 

Fields

Instances

mkName Source #

Arguments

:: Int

nameName

-> Name 

Construct a value of type Name (by applying it's required fields, if any)

NumberOnly

mkNumberOnly :: NumberOnly Source #

Construct a value of type NumberOnly (by applying it's required fields, if any)

Order

data Order Source #

Order

Constructors

Order 

Fields

Instances

Eq Order Source # 

Methods

(==) :: Order -> Order -> Bool #

(/=) :: Order -> Order -> Bool #

Show Order Source # 

Methods

showsPrec :: Int -> Order -> ShowS #

show :: Order -> String #

showList :: [Order] -> ShowS #

ToJSON Order Source #

ToJSON Order

FromJSON Order Source #

FromJSON Order

HasBodyParam PlaceOrder Order Source #

Body Param "body" - order placed for purchasing the pet

Methods

setBodyParam :: (Consumes PlaceOrder contentType, MimeRender contentType Order) => SwaggerPetstoreRequest PlaceOrder contentType res accept -> Order -> SwaggerPetstoreRequest PlaceOrder contentType res accept Source #

mkOrder :: Order Source #

Construct a value of type Order (by applying it's required fields, if any)

OuterBoolean

newtype OuterBoolean Source #

OuterBoolean

Constructors

OuterBoolean 

Fields

OuterComposite

mkOuterComposite :: OuterComposite Source #

Construct a value of type OuterComposite (by applying it's required fields, if any)

OuterNumber

OuterString

Pet

data Pet Source #

Pet

Constructors

Pet 

Fields

Instances

Eq Pet Source # 

Methods

(==) :: Pet -> Pet -> Bool #

(/=) :: Pet -> Pet -> Bool #

Show Pet Source # 

Methods

showsPrec :: Int -> Pet -> ShowS #

show :: Pet -> String #

showList :: [Pet] -> ShowS #

ToJSON Pet Source #

ToJSON Pet

FromJSON Pet Source #

FromJSON Pet

HasBodyParam UpdatePet Pet Source #

Body Param "body" - Pet object that needs to be added to the store

Methods

setBodyParam :: (Consumes UpdatePet contentType, MimeRender contentType Pet) => SwaggerPetstoreRequest UpdatePet contentType res accept -> Pet -> SwaggerPetstoreRequest UpdatePet contentType res accept Source #

HasBodyParam AddPet Pet Source #

Body Param "body" - Pet object that needs to be added to the store

Methods

setBodyParam :: (Consumes AddPet contentType, MimeRender contentType Pet) => SwaggerPetstoreRequest AddPet contentType res accept -> Pet -> SwaggerPetstoreRequest AddPet contentType res accept Source #

mkPet Source #

Arguments

:: Text

petName

-> [Text]

petPhotoUrls

-> Pet 

Construct a value of type Pet (by applying it's required fields, if any)

ReadOnlyFirst

mkReadOnlyFirst :: ReadOnlyFirst Source #

Construct a value of type ReadOnlyFirst (by applying it's required fields, if any)

SpecialModelName

mkSpecialModelName :: SpecialModelName Source #

Construct a value of type SpecialModelName (by applying it's required fields, if any)

Tag

data Tag Source #

Tag

Constructors

Tag 

Fields

Instances

Eq Tag Source # 

Methods

(==) :: Tag -> Tag -> Bool #

(/=) :: Tag -> Tag -> Bool #

Show Tag Source # 

Methods

showsPrec :: Int -> Tag -> ShowS #

show :: Tag -> String #

showList :: [Tag] -> ShowS #

ToJSON Tag Source #

ToJSON Tag

FromJSON Tag Source #

FromJSON Tag

mkTag :: Tag Source #

Construct a value of type Tag (by applying it's required fields, if any)

User

data User Source #

User

Constructors

User 

Fields

Instances

Eq User Source # 

Methods

(==) :: User -> User -> Bool #

(/=) :: User -> User -> Bool #

Show User Source # 

Methods

showsPrec :: Int -> User -> ShowS #

show :: User -> String #

showList :: [User] -> ShowS #

ToJSON User Source #

ToJSON User

FromJSON User Source #

FromJSON User

HasBodyParam UpdateUser User Source #

Body Param "body" - Updated user object

Methods

setBodyParam :: (Consumes UpdateUser contentType, MimeRender contentType User) => SwaggerPetstoreRequest UpdateUser contentType res accept -> User -> SwaggerPetstoreRequest UpdateUser contentType res accept Source #

HasBodyParam CreateUser User Source #

Body Param "body" - Created user object

Methods

setBodyParam :: (Consumes CreateUser contentType, MimeRender contentType User) => SwaggerPetstoreRequest CreateUser contentType res accept -> User -> SwaggerPetstoreRequest CreateUser contentType res accept Source #

mkUser :: User Source #

Construct a value of type User (by applying it's required fields, if any)

Cat

data Cat Source #

Cat

Constructors

Cat 

Fields

Instances

Eq Cat Source # 

Methods

(==) :: Cat -> Cat -> Bool #

(/=) :: Cat -> Cat -> Bool #

Show Cat Source # 

Methods

showsPrec :: Int -> Cat -> ShowS #

show :: Cat -> String #

showList :: [Cat] -> ShowS #

ToJSON Cat Source #

ToJSON Cat

FromJSON Cat Source #

FromJSON Cat

mkCat Source #

Arguments

:: Text

catClassName

-> Cat 

Construct a value of type Cat (by applying it's required fields, if any)

Dog

data Dog Source #

Dog

Constructors

Dog 

Fields

Instances

Eq Dog Source # 

Methods

(==) :: Dog -> Dog -> Bool #

(/=) :: Dog -> Dog -> Bool #

Show Dog Source # 

Methods

showsPrec :: Int -> Dog -> ShowS #

show :: Dog -> String #

showList :: [Dog] -> ShowS #

ToJSON Dog Source #

ToJSON Dog

FromJSON Dog Source #

FromJSON Dog

mkDog Source #

Arguments

:: Text

dogClassName

-> Dog 

Construct a value of type Dog (by applying it's required fields, if any)

Enums

E'ArrayEnum

data E'ArrayEnum Source #

Enum of Text

Constructors

E'ArrayEnum'Fish
"fish"
E'ArrayEnum'Crab
"crab"

Instances

Bounded E'ArrayEnum Source # 
Enum E'ArrayEnum Source # 
Eq E'ArrayEnum Source # 
Ord E'ArrayEnum Source # 
Show E'ArrayEnum Source # 
ToJSON E'ArrayEnum Source # 
FromJSON E'ArrayEnum Source # 
ToHttpApiData E'ArrayEnum Source # 
FromHttpApiData E'ArrayEnum Source # 
MimeRender MimeMultipartFormData E'ArrayEnum Source # 

E'EnumFormString

data E'EnumFormString Source #

Enum of Text

Instances

Bounded E'EnumFormString Source # 
Enum E'EnumFormString Source # 
Eq E'EnumFormString Source # 
Ord E'EnumFormString Source # 
Show E'EnumFormString Source # 
ToJSON E'EnumFormString Source # 
FromJSON E'EnumFormString Source # 
ToHttpApiData E'EnumFormString Source # 
FromHttpApiData E'EnumFormString Source # 
MimeRender MimeMultipartFormData E'EnumFormString Source # 

E'EnumInteger

data E'EnumInteger Source #

Enum of Int

Instances

Bounded E'EnumInteger Source # 
Enum E'EnumInteger Source # 
Eq E'EnumInteger Source # 
Ord E'EnumInteger Source # 
Show E'EnumInteger Source # 
ToJSON E'EnumInteger Source # 
FromJSON E'EnumInteger Source # 
ToHttpApiData E'EnumInteger Source # 
FromHttpApiData E'EnumInteger Source # 
MimeRender MimeMultipartFormData E'EnumInteger Source # 

E'EnumNumber

data E'EnumNumber Source #

Enum of Double

Instances

Bounded E'EnumNumber Source # 
Enum E'EnumNumber Source # 
Eq E'EnumNumber Source # 
Ord E'EnumNumber Source # 
Show E'EnumNumber Source # 
ToJSON E'EnumNumber Source # 
FromJSON E'EnumNumber Source # 
ToHttpApiData E'EnumNumber Source # 
FromHttpApiData E'EnumNumber Source # 
MimeRender MimeMultipartFormData E'EnumNumber Source # 

E'EnumQueryInteger

data E'EnumQueryInteger Source #

Enum of Int

Instances

Bounded E'EnumQueryInteger Source # 
Enum E'EnumQueryInteger Source # 
Eq E'EnumQueryInteger Source # 
Ord E'EnumQueryInteger Source # 
Show E'EnumQueryInteger Source # 
ToJSON E'EnumQueryInteger Source # 
FromJSON E'EnumQueryInteger Source # 
ToHttpApiData E'EnumQueryInteger Source # 
FromHttpApiData E'EnumQueryInteger Source # 
MimeRender MimeMultipartFormData E'EnumQueryInteger Source # 

E'EnumString

data E'EnumString Source #

Enum of Text

Instances

Bounded E'EnumString Source # 
Enum E'EnumString Source # 
Eq E'EnumString Source # 
Ord E'EnumString Source # 
Show E'EnumString Source # 
ToJSON E'EnumString Source # 
FromJSON E'EnumString Source # 
ToHttpApiData E'EnumString Source # 
FromHttpApiData E'EnumString Source # 
MimeRender MimeMultipartFormData E'EnumString Source # 

E'Inner

data E'Inner Source #

Enum of Text

Instances

Bounded E'Inner Source # 
Enum E'Inner Source # 
Eq E'Inner Source # 

Methods

(==) :: E'Inner -> E'Inner -> Bool #

(/=) :: E'Inner -> E'Inner -> Bool #

Ord E'Inner Source # 
Show E'Inner Source # 
ToJSON E'Inner Source # 
FromJSON E'Inner Source # 
ToHttpApiData E'Inner Source # 
FromHttpApiData E'Inner Source # 
MimeRender MimeMultipartFormData E'Inner Source # 

E'Inner2

data E'Inner2 Source #

Enum of Text

Instances

Bounded E'Inner2 Source # 
Enum E'Inner2 Source # 
Eq E'Inner2 Source # 
Ord E'Inner2 Source # 
Show E'Inner2 Source # 
ToJSON E'Inner2 Source # 
FromJSON E'Inner2 Source # 
ToHttpApiData E'Inner2 Source # 
FromHttpApiData E'Inner2 Source # 
MimeRender MimeMultipartFormData E'Inner2 Source # 

E'JustSymbol

data E'JustSymbol Source #

Enum of Text

Instances

Bounded E'JustSymbol Source # 
Enum E'JustSymbol Source # 
Eq E'JustSymbol Source # 
Ord E'JustSymbol Source # 
Show E'JustSymbol Source # 
ToJSON E'JustSymbol Source # 
FromJSON E'JustSymbol Source # 
ToHttpApiData E'JustSymbol Source # 
FromHttpApiData E'JustSymbol Source # 
MimeRender MimeMultipartFormData E'JustSymbol Source # 

E'Status

data E'Status Source #

Enum of Text . + Order Status

Constructors

E'Status'Placed
"placed"
E'Status'Approved
"approved"
E'Status'Delivered
"delivered"

Instances

Bounded E'Status Source # 
Enum E'Status Source # 
Eq E'Status Source # 
Ord E'Status Source # 
Show E'Status Source # 
ToJSON E'Status Source # 
FromJSON E'Status Source # 
ToHttpApiData E'Status Source # 
FromHttpApiData E'Status Source # 
MimeRender MimeMultipartFormData E'Status Source # 

E'Status2

data E'Status2 Source #

Enum of Text . + pet status in the store

Constructors

E'Status2'Available
"available"
E'Status2'Pending
"pending"
E'Status2'Sold
"sold"

Instances

Bounded E'Status2 Source # 
Enum E'Status2 Source # 
Eq E'Status2 Source # 
Ord E'Status2 Source # 
Show E'Status2 Source # 
ToJSON E'Status2 Source # 
FromJSON E'Status2 Source # 
ToHttpApiData E'Status2 Source # 
FromHttpApiData E'Status2 Source # 
MimeRender MimeMultipartFormData E'Status2 Source # 

EnumClass

data EnumClass Source #

Enum of Text

Constructors

EnumClass'_abc
"_abc"
EnumClass'_efg
"-efg"
EnumClass'_xyz
"(xyz)"

Instances

Bounded EnumClass Source # 
Enum EnumClass Source # 
Eq EnumClass Source # 
Ord EnumClass Source # 
Show EnumClass Source # 
ToJSON EnumClass Source # 
FromJSON EnumClass Source # 
ToHttpApiData EnumClass Source # 
FromHttpApiData EnumClass Source # 
MimeRender MimeMultipartFormData EnumClass Source # 

OuterEnum

data OuterEnum Source #

Enum of Text

Constructors

OuterEnum'Placed
"placed"
OuterEnum'Approved
"approved"
OuterEnum'Delivered
"delivered"

Instances

Bounded OuterEnum Source # 
Enum OuterEnum Source # 
Eq OuterEnum Source # 
Ord OuterEnum Source # 
Show OuterEnum Source # 
ToJSON OuterEnum Source # 
FromJSON OuterEnum Source # 
ToHttpApiData OuterEnum Source # 
FromHttpApiData OuterEnum Source # 
MimeRender MimeMultipartFormData OuterEnum Source # 
\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-ModelLens.html b/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-ModelLens.html index 57c81e18d67..bdcb9960694 100644 --- a/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-ModelLens.html +++ b/samples/client/petstore/haskell-http-client/docs/SwaggerPetstore-ModelLens.html @@ -1,4 +1,4 @@ SwaggerPetstore.ModelLens

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Safe HaskellNone
LanguageHaskell2010

SwaggerPetstore.ModelLens

Description

 

Synopsis

AdditionalPropertiesClass

Animal

AnimalFarm

ApiResponse

ArrayOfArrayOfNumberOnly

ArrayOfNumberOnly

ArrayTest

Capitalization

Category

ClassModel

Client

EnumArrays

EnumClass

EnumTest

FormatTest

HasOnlyReadOnly

MapTest

MixedPropertiesAndAdditionalPropertiesClass

Model200Response

ModelList

ModelReturn

Name

NumberOnly

Order

OuterBoolean

OuterComposite

OuterEnum

OuterNumber

OuterString

Pet

ReadOnlyFirst

SpecialModelName

Tag

User

Cat

Dog

\ No newline at end of file +

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Safe HaskellNone
LanguageHaskell2010

SwaggerPetstore.ModelLens

Description

 

Synopsis

AdditionalPropertiesClass

Animal

AnimalFarm

ApiResponse

ArrayOfArrayOfNumberOnly

ArrayOfNumberOnly

ArrayTest

Capitalization

Category

ClassModel

Client

EnumArrays

EnumClass

EnumTest

FormatTest

HasOnlyReadOnly

MapTest

MixedPropertiesAndAdditionalPropertiesClass

Model200Response

ModelList

ModelReturn

Name

NumberOnly

Order

OuterBoolean

OuterComposite

OuterEnum

OuterNumber

OuterString

Pet

ReadOnlyFirst

SpecialModelName

Tag

User

Cat

Dog

\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/doc-index-A.html b/samples/client/petstore/haskell-http-client/docs/doc-index-A.html index b783b0ca86c..2e1879784ba 100644 --- a/samples/client/petstore/haskell-http-client/docs/doc-index-A.html +++ b/samples/client/petstore/haskell-http-client/docs/doc-index-A.html @@ -1,4 +1,4 @@ swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client (Index - A)

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index - A

addAuthMethodSwaggerPetstore.Core, SwaggerPetstore
addFormSwaggerPetstore.Core, SwaggerPetstore
AdditionalMetadata 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
AdditionalPropertiesClass 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
additionalPropertiesClassMapOfMapPropertySwaggerPetstore.Model, SwaggerPetstore
additionalPropertiesClassMapOfMapPropertyLSwaggerPetstore.ModelLens, SwaggerPetstore
additionalPropertiesClassMapPropertySwaggerPetstore.Model, SwaggerPetstore
additionalPropertiesClassMapPropertyLSwaggerPetstore.ModelLens, SwaggerPetstore
AddPetSwaggerPetstore.API, SwaggerPetstore
addPetSwaggerPetstore.API, SwaggerPetstore
Animal 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
animalClassNameSwaggerPetstore.Model, SwaggerPetstore
animalClassNameLSwaggerPetstore.ModelLens, SwaggerPetstore
animalColorSwaggerPetstore.Model, SwaggerPetstore
animalColorLSwaggerPetstore.ModelLens, SwaggerPetstore
AnimalFarm 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
AnyAuthMethod 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
ApiKey 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ApiResponse 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
apiResponseCodeSwaggerPetstore.Model, SwaggerPetstore
apiResponseCodeLSwaggerPetstore.ModelLens, SwaggerPetstore
apiResponseMessageSwaggerPetstore.Model, SwaggerPetstore
apiResponseMessageLSwaggerPetstore.ModelLens, SwaggerPetstore
apiResponseTypeSwaggerPetstore.Model, SwaggerPetstore
apiResponseTypeLSwaggerPetstore.ModelLens, SwaggerPetstore
applyAuthMethodSwaggerPetstore.Core, SwaggerPetstore
applyOptionalParamSwaggerPetstore.Core, SwaggerPetstore
ArrayOfArrayOfNumberOnly 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
arrayOfArrayOfNumberOnlyArrayArrayNumberSwaggerPetstore.Model, SwaggerPetstore
arrayOfArrayOfNumberOnlyArrayArrayNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
ArrayOfNumberOnly 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
arrayOfNumberOnlyArrayNumberSwaggerPetstore.Model, SwaggerPetstore
arrayOfNumberOnlyArrayNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
ArrayTest 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
arrayTestArrayArrayOfIntegerSwaggerPetstore.Model, SwaggerPetstore
arrayTestArrayArrayOfIntegerLSwaggerPetstore.ModelLens, SwaggerPetstore
arrayTestArrayArrayOfModelSwaggerPetstore.Model, SwaggerPetstore
arrayTestArrayArrayOfModelLSwaggerPetstore.ModelLens, SwaggerPetstore
arrayTestArrayOfStringSwaggerPetstore.Model, SwaggerPetstore
arrayTestArrayOfStringLSwaggerPetstore.ModelLens, SwaggerPetstore
AuthApiKeyApiKey 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
AuthApiKeyApiKeyQuery 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
AuthBasicHttpBasicTest 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
AuthMethodSwaggerPetstore.Core, SwaggerPetstore
AuthOAuthPetstoreAuth 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
\ No newline at end of file +

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index - A

Accept 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
addAuthMethodSwaggerPetstore.Core, SwaggerPetstore
addFormSwaggerPetstore.Core, SwaggerPetstore
AdditionalMetadata 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
AdditionalPropertiesClass 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
additionalPropertiesClassMapOfMapPropertySwaggerPetstore.Model, SwaggerPetstore
additionalPropertiesClassMapOfMapPropertyLSwaggerPetstore.ModelLens, SwaggerPetstore
additionalPropertiesClassMapPropertySwaggerPetstore.Model, SwaggerPetstore
additionalPropertiesClassMapPropertyLSwaggerPetstore.ModelLens, SwaggerPetstore
AddPetSwaggerPetstore.API, SwaggerPetstore
addPetSwaggerPetstore.API, SwaggerPetstore
Animal 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
animalClassNameSwaggerPetstore.Model, SwaggerPetstore
animalClassNameLSwaggerPetstore.ModelLens, SwaggerPetstore
animalColorSwaggerPetstore.Model, SwaggerPetstore
animalColorLSwaggerPetstore.ModelLens, SwaggerPetstore
AnimalFarm 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
AnyAuthMethod 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
ApiKey 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ApiResponse 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
apiResponseCodeSwaggerPetstore.Model, SwaggerPetstore
apiResponseCodeLSwaggerPetstore.ModelLens, SwaggerPetstore
apiResponseMessageSwaggerPetstore.Model, SwaggerPetstore
apiResponseMessageLSwaggerPetstore.ModelLens, SwaggerPetstore
apiResponseTypeSwaggerPetstore.Model, SwaggerPetstore
apiResponseTypeLSwaggerPetstore.ModelLens, SwaggerPetstore
applyAuthMethodSwaggerPetstore.Core, SwaggerPetstore
applyOptionalParamSwaggerPetstore.Core, SwaggerPetstore
ArrayOfArrayOfNumberOnly 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
arrayOfArrayOfNumberOnlyArrayArrayNumberSwaggerPetstore.Model, SwaggerPetstore
arrayOfArrayOfNumberOnlyArrayArrayNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
ArrayOfNumberOnly 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
arrayOfNumberOnlyArrayNumberSwaggerPetstore.Model, SwaggerPetstore
arrayOfNumberOnlyArrayNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
ArrayTest 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
arrayTestArrayArrayOfIntegerSwaggerPetstore.Model, SwaggerPetstore
arrayTestArrayArrayOfIntegerLSwaggerPetstore.ModelLens, SwaggerPetstore
arrayTestArrayArrayOfModelSwaggerPetstore.Model, SwaggerPetstore
arrayTestArrayArrayOfModelLSwaggerPetstore.ModelLens, SwaggerPetstore
arrayTestArrayOfStringSwaggerPetstore.Model, SwaggerPetstore
arrayTestArrayOfStringLSwaggerPetstore.ModelLens, SwaggerPetstore
AuthApiKeyApiKey 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
AuthApiKeyApiKeyQuery 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
AuthBasicHttpBasicTest 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
AuthMethodSwaggerPetstore.Core, SwaggerPetstore
AuthMethodException 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
AuthOAuthPetstoreAuth 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/doc-index-All.html b/samples/client/petstore/haskell-http-client/docs/doc-index-All.html index b7e2456a6ab..4d1f9ec4fc4 100644 --- a/samples/client/petstore/haskell-http-client/docs/doc-index-All.html +++ b/samples/client/petstore/haskell-http-client/docs/doc-index-All.html @@ -1,4 +1,4 @@ swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client (Index)

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index

-&-SwaggerPetstore.Core, SwaggerPetstore
addAuthMethodSwaggerPetstore.Core, SwaggerPetstore
addFormSwaggerPetstore.Core, SwaggerPetstore
AdditionalMetadata 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
AdditionalPropertiesClass 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
additionalPropertiesClassMapOfMapPropertySwaggerPetstore.Model, SwaggerPetstore
additionalPropertiesClassMapOfMapPropertyLSwaggerPetstore.ModelLens, SwaggerPetstore
additionalPropertiesClassMapPropertySwaggerPetstore.Model, SwaggerPetstore
additionalPropertiesClassMapPropertyLSwaggerPetstore.ModelLens, SwaggerPetstore
AddPetSwaggerPetstore.API, SwaggerPetstore
addPetSwaggerPetstore.API, SwaggerPetstore
Animal 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
animalClassNameSwaggerPetstore.Model, SwaggerPetstore
animalClassNameLSwaggerPetstore.ModelLens, SwaggerPetstore
animalColorSwaggerPetstore.Model, SwaggerPetstore
animalColorLSwaggerPetstore.ModelLens, SwaggerPetstore
AnimalFarm 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
AnyAuthMethod 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
ApiKey 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ApiResponse 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
apiResponseCodeSwaggerPetstore.Model, SwaggerPetstore
apiResponseCodeLSwaggerPetstore.ModelLens, SwaggerPetstore
apiResponseMessageSwaggerPetstore.Model, SwaggerPetstore
apiResponseMessageLSwaggerPetstore.ModelLens, SwaggerPetstore
apiResponseTypeSwaggerPetstore.Model, SwaggerPetstore
apiResponseTypeLSwaggerPetstore.ModelLens, SwaggerPetstore
applyAuthMethodSwaggerPetstore.Core, SwaggerPetstore
applyOptionalParamSwaggerPetstore.Core, SwaggerPetstore
ArrayOfArrayOfNumberOnly 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
arrayOfArrayOfNumberOnlyArrayArrayNumberSwaggerPetstore.Model, SwaggerPetstore
arrayOfArrayOfNumberOnlyArrayArrayNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
ArrayOfNumberOnly 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
arrayOfNumberOnlyArrayNumberSwaggerPetstore.Model, SwaggerPetstore
arrayOfNumberOnlyArrayNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
ArrayTest 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
arrayTestArrayArrayOfIntegerSwaggerPetstore.Model, SwaggerPetstore
arrayTestArrayArrayOfIntegerLSwaggerPetstore.ModelLens, SwaggerPetstore
arrayTestArrayArrayOfModelSwaggerPetstore.Model, SwaggerPetstore
arrayTestArrayArrayOfModelLSwaggerPetstore.ModelLens, SwaggerPetstore
arrayTestArrayOfStringSwaggerPetstore.Model, SwaggerPetstore
arrayTestArrayOfStringLSwaggerPetstore.ModelLens, SwaggerPetstore
AuthApiKeyApiKey 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
AuthApiKeyApiKeyQuery 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
AuthBasicHttpBasicTest 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
AuthMethodSwaggerPetstore.Core, SwaggerPetstore
AuthOAuthPetstoreAuth 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Binary 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
Body 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Byte 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ByteArray 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
Callback 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Capitalization 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
capitalizationAttNameSwaggerPetstore.Model, SwaggerPetstore
capitalizationAttNameLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationCapitalCamelSwaggerPetstore.Model, SwaggerPetstore
capitalizationCapitalCamelLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationCapitalSnakeSwaggerPetstore.Model, SwaggerPetstore
capitalizationCapitalSnakeLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationScaEthFlowPointsSwaggerPetstore.Model, SwaggerPetstore
capitalizationScaEthFlowPointsLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationSmallCamelSwaggerPetstore.Model, SwaggerPetstore
capitalizationSmallCamelLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationSmallSnakeSwaggerPetstore.Model, SwaggerPetstore
capitalizationSmallSnakeLSwaggerPetstore.ModelLens, SwaggerPetstore
Cat 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
catClassNameSwaggerPetstore.Model, SwaggerPetstore
catClassNameLSwaggerPetstore.ModelLens, SwaggerPetstore
catColorSwaggerPetstore.Model, SwaggerPetstore
catColorLSwaggerPetstore.ModelLens, SwaggerPetstore
catDeclawedSwaggerPetstore.Model, SwaggerPetstore
catDeclawedLSwaggerPetstore.ModelLens, SwaggerPetstore
Category 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
categoryIdSwaggerPetstore.Model, SwaggerPetstore
categoryIdLSwaggerPetstore.ModelLens, SwaggerPetstore
categoryNameSwaggerPetstore.Model, SwaggerPetstore
categoryNameLSwaggerPetstore.ModelLens, SwaggerPetstore
ClassModel 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
classModelClassSwaggerPetstore.Model, SwaggerPetstore
classModelClassLSwaggerPetstore.ModelLens, SwaggerPetstore
Client 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
clientClientSwaggerPetstore.Model, SwaggerPetstore
clientClientLSwaggerPetstore.ModelLens, SwaggerPetstore
CollectionFormatSwaggerPetstore.Core, SwaggerPetstore
CommaSeparatedSwaggerPetstore.Core, SwaggerPetstore
configAuthMethodsSwaggerPetstore.Core, SwaggerPetstore
configHostSwaggerPetstore.Core, SwaggerPetstore
configLogContextSwaggerPetstore.Core, SwaggerPetstore
configLogExecWithContextSwaggerPetstore.Core, SwaggerPetstore
configUserAgentSwaggerPetstore.Core, SwaggerPetstore
configValidateAuthMethodsSwaggerPetstore.Core, SwaggerPetstore
ConsumesSwaggerPetstore.MimeTypes, SwaggerPetstore
CreateUserSwaggerPetstore.API, SwaggerPetstore
createUserSwaggerPetstore.API, SwaggerPetstore
CreateUsersWithArrayInputSwaggerPetstore.API, SwaggerPetstore
createUsersWithArrayInputSwaggerPetstore.API, SwaggerPetstore
CreateUsersWithListInputSwaggerPetstore.API, SwaggerPetstore
createUsersWithListInputSwaggerPetstore.API, SwaggerPetstore
Date 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
DateTime 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
DeleteOrderSwaggerPetstore.API, SwaggerPetstore
deleteOrderSwaggerPetstore.API, SwaggerPetstore
DeletePetSwaggerPetstore.API, SwaggerPetstore
deletePetSwaggerPetstore.API, SwaggerPetstore
DeleteUserSwaggerPetstore.API, SwaggerPetstore
deleteUserSwaggerPetstore.API, SwaggerPetstore
dispatchInitUnsafeSwaggerPetstore.Client, SwaggerPetstore
dispatchLbsSwaggerPetstore.Client, SwaggerPetstore
dispatchLbsUnsafeSwaggerPetstore.Client, SwaggerPetstore
dispatchMimeSwaggerPetstore.Client, SwaggerPetstore
dispatchMime'SwaggerPetstore.Client, SwaggerPetstore
Dog 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
dogBreedSwaggerPetstore.Model, SwaggerPetstore
dogBreedLSwaggerPetstore.ModelLens, SwaggerPetstore
dogClassNameSwaggerPetstore.Model, SwaggerPetstore
dogClassNameLSwaggerPetstore.ModelLens, SwaggerPetstore
dogColorSwaggerPetstore.Model, SwaggerPetstore
dogColorLSwaggerPetstore.ModelLens, SwaggerPetstore
EnumArrays 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
enumArraysArrayEnumSwaggerPetstore.Model, SwaggerPetstore
enumArraysArrayEnumLSwaggerPetstore.ModelLens, SwaggerPetstore
enumArraysJustSymbolSwaggerPetstore.Model, SwaggerPetstore
enumArraysJustSymbolLSwaggerPetstore.ModelLens, SwaggerPetstore
EnumClass 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
EnumFormString 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumFormStringArray 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumHeaderString 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumHeaderStringArray 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumQueryDouble 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumQueryInteger 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumQueryString 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumQueryStringArray 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumTest 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
enumTestEnumIntegerSwaggerPetstore.Model, SwaggerPetstore
enumTestEnumIntegerLSwaggerPetstore.ModelLens, SwaggerPetstore
enumTestEnumNumberSwaggerPetstore.Model, SwaggerPetstore
enumTestEnumNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
enumTestEnumStringSwaggerPetstore.Model, SwaggerPetstore
enumTestEnumStringLSwaggerPetstore.ModelLens, SwaggerPetstore
enumTestOuterEnumSwaggerPetstore.Model, SwaggerPetstore
enumTestOuterEnumLSwaggerPetstore.ModelLens, SwaggerPetstore
FakeOuterBooleanSerializeSwaggerPetstore.API, SwaggerPetstore
fakeOuterBooleanSerializeSwaggerPetstore.API, SwaggerPetstore
FakeOuterCompositeSerializeSwaggerPetstore.API, SwaggerPetstore
fakeOuterCompositeSerializeSwaggerPetstore.API, SwaggerPetstore
FakeOuterNumberSerializeSwaggerPetstore.API, SwaggerPetstore
fakeOuterNumberSerializeSwaggerPetstore.API, SwaggerPetstore
FakeOuterStringSerializeSwaggerPetstore.API, SwaggerPetstore
fakeOuterStringSerializeSwaggerPetstore.API, SwaggerPetstore
File 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
FindPetsByStatusSwaggerPetstore.API, SwaggerPetstore
findPetsByStatusSwaggerPetstore.API, SwaggerPetstore
FindPetsByTagsSwaggerPetstore.API, SwaggerPetstore
findPetsByTagsSwaggerPetstore.API, SwaggerPetstore
FormatTest 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
formatTestBinarySwaggerPetstore.Model, SwaggerPetstore
formatTestBinaryLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestByteSwaggerPetstore.Model, SwaggerPetstore
formatTestByteLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestDateSwaggerPetstore.Model, SwaggerPetstore
formatTestDateLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestDateTimeSwaggerPetstore.Model, SwaggerPetstore
formatTestDateTimeLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestDoubleSwaggerPetstore.Model, SwaggerPetstore
formatTestDoubleLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestFloatSwaggerPetstore.Model, SwaggerPetstore
formatTestFloatLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestInt32SwaggerPetstore.Model, SwaggerPetstore
formatTestInt32LSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestInt64SwaggerPetstore.Model, SwaggerPetstore
formatTestInt64LSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestIntegerSwaggerPetstore.Model, SwaggerPetstore
formatTestIntegerLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestNumberSwaggerPetstore.Model, SwaggerPetstore
formatTestNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestPasswordSwaggerPetstore.Model, SwaggerPetstore
formatTestPasswordLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestStringSwaggerPetstore.Model, SwaggerPetstore
formatTestStringLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestUuidSwaggerPetstore.Model, SwaggerPetstore
formatTestUuidLSwaggerPetstore.ModelLens, SwaggerPetstore
GetInventorySwaggerPetstore.API, SwaggerPetstore
getInventorySwaggerPetstore.API, SwaggerPetstore
GetOrderByIdSwaggerPetstore.API, SwaggerPetstore
getOrderByIdSwaggerPetstore.API, SwaggerPetstore
GetPetByIdSwaggerPetstore.API, SwaggerPetstore
getPetByIdSwaggerPetstore.API, SwaggerPetstore
GetUserByNameSwaggerPetstore.API, SwaggerPetstore
getUserByNameSwaggerPetstore.API, SwaggerPetstore
HasBodyParamSwaggerPetstore.Core, SwaggerPetstore
HasOnlyReadOnly 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
hasOnlyReadOnlyBarSwaggerPetstore.Model, SwaggerPetstore
hasOnlyReadOnlyBarLSwaggerPetstore.ModelLens, SwaggerPetstore
hasOnlyReadOnlyFooSwaggerPetstore.Model, SwaggerPetstore
hasOnlyReadOnlyFooLSwaggerPetstore.ModelLens, SwaggerPetstore
HasOptionalParamSwaggerPetstore.Core, SwaggerPetstore
initLogContextSwaggerPetstore.Logging, SwaggerPetstore
InitRequest 
1 (Type/Class)SwaggerPetstore.Client, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Client, SwaggerPetstore
Int32 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Int64 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Lens_SwaggerPetstore.Core, SwaggerPetstore
Lens_'SwaggerPetstore.Core, SwaggerPetstore
levelDebugSwaggerPetstore.Logging, SwaggerPetstore
levelErrorSwaggerPetstore.Logging, SwaggerPetstore
levelInfoSwaggerPetstore.Logging, SwaggerPetstore
LogContextSwaggerPetstore.Logging, SwaggerPetstore
logExceptionsSwaggerPetstore.Logging, SwaggerPetstore
LogExecSwaggerPetstore.Logging, SwaggerPetstore
LogExecWithContextSwaggerPetstore.Logging, SwaggerPetstore
LoginUserSwaggerPetstore.API, SwaggerPetstore
loginUserSwaggerPetstore.API, SwaggerPetstore
LogLevelSwaggerPetstore.Logging, SwaggerPetstore
LogoutUserSwaggerPetstore.API, SwaggerPetstore
logoutUserSwaggerPetstore.API, SwaggerPetstore
MapTest 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
mapTestMapMapOfStringSwaggerPetstore.Model, SwaggerPetstore
mapTestMapMapOfStringLSwaggerPetstore.ModelLens, SwaggerPetstore
mapTestMapOfEnumStringSwaggerPetstore.Model, SwaggerPetstore
mapTestMapOfEnumStringLSwaggerPetstore.ModelLens, SwaggerPetstore
MimeAny 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeError 
1 (Type/Class)SwaggerPetstore.Client, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Client, SwaggerPetstore
mimeErrorSwaggerPetstore.Client, SwaggerPetstore
mimeErrorResponseSwaggerPetstore.Client, SwaggerPetstore
MimeFormUrlEncoded 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeJSON 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeJsonCharsetutf8 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
MimeMultipartFormData 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeNoContent 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeOctetStream 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimePlainText 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeRenderSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeRenderSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeRender'SwaggerPetstore.MimeTypes, SwaggerPetstore
mimeRenderDefaultMultipartFormDataSwaggerPetstore.MimeTypes, SwaggerPetstore
MimeResult 
1 (Type/Class)SwaggerPetstore.Client, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Client, SwaggerPetstore
mimeResultSwaggerPetstore.Client, SwaggerPetstore
mimeResultResponseSwaggerPetstore.Client, SwaggerPetstore
MimeTypeSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeTypeSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeType'SwaggerPetstore.MimeTypes, SwaggerPetstore
mimeTypesSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeTypes'SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeUnrenderSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeUnrenderSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeUnrender'SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeXML 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeXmlCharsetutf8 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
MixedPropertiesAndAdditionalPropertiesClass 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassDateTimeSwaggerPetstore.Model, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassDateTimeLSwaggerPetstore.ModelLens, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassMapSwaggerPetstore.Model, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassMapLSwaggerPetstore.ModelLens, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassUuidSwaggerPetstore.Model, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassUuidLSwaggerPetstore.ModelLens, SwaggerPetstore
mkAdditionalPropertiesClassSwaggerPetstore.Model, SwaggerPetstore
mkAnimalSwaggerPetstore.Model, SwaggerPetstore
mkAnimalFarmSwaggerPetstore.Model, SwaggerPetstore
mkApiResponseSwaggerPetstore.Model, SwaggerPetstore
mkArrayOfArrayOfNumberOnlySwaggerPetstore.Model, SwaggerPetstore
mkArrayOfNumberOnlySwaggerPetstore.Model, SwaggerPetstore
mkArrayTestSwaggerPetstore.Model, SwaggerPetstore
mkCapitalizationSwaggerPetstore.Model, SwaggerPetstore
mkCatSwaggerPetstore.Model, SwaggerPetstore
mkCategorySwaggerPetstore.Model, SwaggerPetstore
mkClassModelSwaggerPetstore.Model, SwaggerPetstore
mkClientSwaggerPetstore.Model, SwaggerPetstore
mkDogSwaggerPetstore.Model, SwaggerPetstore
mkEnumArraysSwaggerPetstore.Model, SwaggerPetstore
mkEnumClassSwaggerPetstore.Model, SwaggerPetstore
mkEnumTestSwaggerPetstore.Model, SwaggerPetstore
mkFormatTestSwaggerPetstore.Model, SwaggerPetstore
mkHasOnlyReadOnlySwaggerPetstore.Model, SwaggerPetstore
mkMapTestSwaggerPetstore.Model, SwaggerPetstore
mkMixedPropertiesAndAdditionalPropertiesClassSwaggerPetstore.Model, SwaggerPetstore
mkModel200ResponseSwaggerPetstore.Model, SwaggerPetstore
mkModelListSwaggerPetstore.Model, SwaggerPetstore
mkModelReturnSwaggerPetstore.Model, SwaggerPetstore
mkNameSwaggerPetstore.Model, SwaggerPetstore
mkNumberOnlySwaggerPetstore.Model, SwaggerPetstore
mkOrderSwaggerPetstore.Model, SwaggerPetstore
mkOuterCompositeSwaggerPetstore.Model, SwaggerPetstore
mkOuterEnumSwaggerPetstore.Model, SwaggerPetstore
mkPetSwaggerPetstore.Model, SwaggerPetstore
mkReadOnlyFirstSwaggerPetstore.Model, SwaggerPetstore
mkSpecialModelNameSwaggerPetstore.Model, SwaggerPetstore
mkTagSwaggerPetstore.Model, SwaggerPetstore
mkUserSwaggerPetstore.Model, SwaggerPetstore
Model200Response 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
model200ResponseClassSwaggerPetstore.Model, SwaggerPetstore
model200ResponseClassLSwaggerPetstore.ModelLens, SwaggerPetstore
model200ResponseNameSwaggerPetstore.Model, SwaggerPetstore
model200ResponseNameLSwaggerPetstore.ModelLens, SwaggerPetstore
ModelList 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
modelList123ListSwaggerPetstore.Model, SwaggerPetstore
modelList123ListLSwaggerPetstore.ModelLens, SwaggerPetstore
ModelReturn 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
modelReturnReturnSwaggerPetstore.Model, SwaggerPetstore
modelReturnReturnLSwaggerPetstore.ModelLens, SwaggerPetstore
modifyInitRequestSwaggerPetstore.Client, SwaggerPetstore
modifyInitRequestMSwaggerPetstore.Client, SwaggerPetstore
MultiParamArraySwaggerPetstore.Core, SwaggerPetstore
Name 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
name123NumberSwaggerPetstore.Model, SwaggerPetstore
name123NumberLSwaggerPetstore.ModelLens, SwaggerPetstore
Name2 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
nameNameSwaggerPetstore.Model, SwaggerPetstore
nameNameLSwaggerPetstore.ModelLens, SwaggerPetstore
namePropertySwaggerPetstore.Model, SwaggerPetstore
namePropertyLSwaggerPetstore.ModelLens, SwaggerPetstore
nameSnakeCaseSwaggerPetstore.Model, SwaggerPetstore
nameSnakeCaseLSwaggerPetstore.ModelLens, SwaggerPetstore
newConfigSwaggerPetstore.Core, SwaggerPetstore
NoContent 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
Number 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
NumberOnly 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
numberOnlyJustNumberSwaggerPetstore.Model, SwaggerPetstore
numberOnlyJustNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
Order 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
orderCompleteSwaggerPetstore.Model, SwaggerPetstore
orderCompleteLSwaggerPetstore.ModelLens, SwaggerPetstore
OrderId 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
orderIdSwaggerPetstore.Model, SwaggerPetstore
orderIdLSwaggerPetstore.ModelLens, SwaggerPetstore
OrderIdText 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
orderPetIdSwaggerPetstore.Model, SwaggerPetstore
orderPetIdLSwaggerPetstore.ModelLens, SwaggerPetstore
orderQuantitySwaggerPetstore.Model, SwaggerPetstore
orderQuantityLSwaggerPetstore.ModelLens, SwaggerPetstore
orderShipDateSwaggerPetstore.Model, SwaggerPetstore
orderShipDateLSwaggerPetstore.ModelLens, SwaggerPetstore
orderStatusSwaggerPetstore.Model, SwaggerPetstore
orderStatusLSwaggerPetstore.ModelLens, SwaggerPetstore
OuterBoolean 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
OuterComposite 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
outerCompositeMyBooleanSwaggerPetstore.Model, SwaggerPetstore
outerCompositeMyBooleanLSwaggerPetstore.ModelLens, SwaggerPetstore
outerCompositeMyNumberSwaggerPetstore.Model, SwaggerPetstore
outerCompositeMyNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
outerCompositeMyStringSwaggerPetstore.Model, SwaggerPetstore
outerCompositeMyStringLSwaggerPetstore.ModelLens, SwaggerPetstore
OuterEnum 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
OuterNumber 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
OuterString 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
Param 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Param2 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ParamBinary 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ParamBodySwaggerPetstore.Core, SwaggerPetstore
ParamBodyBSwaggerPetstore.Core, SwaggerPetstore
ParamBodyBLSwaggerPetstore.Core, SwaggerPetstore
ParamBodyFormUrlEncodedSwaggerPetstore.Core, SwaggerPetstore
ParamBodyMultipartFormDataSwaggerPetstore.Core, SwaggerPetstore
ParamBodyNoneSwaggerPetstore.Core, SwaggerPetstore
ParamDate 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ParamDateTime 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ParamDouble 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ParamFloat 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ParamInteger 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Params 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
paramsBodySwaggerPetstore.Core, SwaggerPetstore
paramsBodyLSwaggerPetstore.Core, SwaggerPetstore
paramsHeadersSwaggerPetstore.Core, SwaggerPetstore
paramsHeadersLSwaggerPetstore.Core, SwaggerPetstore
paramsQuerySwaggerPetstore.Core, SwaggerPetstore
paramsQueryLSwaggerPetstore.Core, SwaggerPetstore
ParamString 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Password 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
PatternWithoutDelimiter 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Pet 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
petCategorySwaggerPetstore.Model, SwaggerPetstore
petCategoryLSwaggerPetstore.ModelLens, SwaggerPetstore
PetId 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
petIdSwaggerPetstore.Model, SwaggerPetstore
petIdLSwaggerPetstore.ModelLens, SwaggerPetstore
petNameSwaggerPetstore.Model, SwaggerPetstore
petNameLSwaggerPetstore.ModelLens, SwaggerPetstore
petPhotoUrlsSwaggerPetstore.Model, SwaggerPetstore
petPhotoUrlsLSwaggerPetstore.ModelLens, SwaggerPetstore
petStatusSwaggerPetstore.Model, SwaggerPetstore
petStatusLSwaggerPetstore.ModelLens, SwaggerPetstore
petTagsSwaggerPetstore.Model, SwaggerPetstore
petTagsLSwaggerPetstore.ModelLens, SwaggerPetstore
PipeSeparatedSwaggerPetstore.Core, SwaggerPetstore
PlaceOrderSwaggerPetstore.API, SwaggerPetstore
placeOrderSwaggerPetstore.API, SwaggerPetstore
ProducesSwaggerPetstore.MimeTypes, SwaggerPetstore
rAuthTypesSwaggerPetstore.Core, SwaggerPetstore
rAuthTypesLSwaggerPetstore.Core, SwaggerPetstore
ReadOnlyFirst 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
readOnlyFirstBarSwaggerPetstore.Model, SwaggerPetstore
readOnlyFirstBarLSwaggerPetstore.ModelLens, SwaggerPetstore
readOnlyFirstBazSwaggerPetstore.Model, SwaggerPetstore
readOnlyFirstBazLSwaggerPetstore.ModelLens, SwaggerPetstore
removeHeaderSwaggerPetstore.Core, SwaggerPetstore
rMethodSwaggerPetstore.Core, SwaggerPetstore
rMethodLSwaggerPetstore.Core, SwaggerPetstore
rParamsSwaggerPetstore.Core, SwaggerPetstore
rParamsLSwaggerPetstore.Core, SwaggerPetstore
runConfigLogSwaggerPetstore.Client, SwaggerPetstore
runConfigLogWithExceptionsSwaggerPetstore.Client, SwaggerPetstore
runDefaultLogExecWithContextSwaggerPetstore.Logging, SwaggerPetstore
runNullLogExecSwaggerPetstore.Logging, SwaggerPetstore
rUrlPathSwaggerPetstore.Core, SwaggerPetstore
rUrlPathLSwaggerPetstore.Core, SwaggerPetstore
setBodyParamSwaggerPetstore.Core, SwaggerPetstore
setHeaderSwaggerPetstore.Core, SwaggerPetstore
setQuerySwaggerPetstore.Core, SwaggerPetstore
SpaceSeparatedSwaggerPetstore.Core, SwaggerPetstore
SpecialModelName 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
specialModelNameSpecialPropertyNameSwaggerPetstore.Model, SwaggerPetstore
specialModelNameSpecialPropertyNameLSwaggerPetstore.ModelLens, SwaggerPetstore
Status 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
StatusText 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
stderrLoggingContextSwaggerPetstore.Logging, SwaggerPetstore
stderrLoggingExecSwaggerPetstore.Logging, SwaggerPetstore
stdoutLoggingContextSwaggerPetstore.Logging, SwaggerPetstore
stdoutLoggingExecSwaggerPetstore.Logging, SwaggerPetstore
SwaggerPetstoreConfig 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
SwaggerPetstoreRequest 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
TabSeparatedSwaggerPetstore.Core, SwaggerPetstore
Tag 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
tagIdSwaggerPetstore.Model, SwaggerPetstore
tagIdLSwaggerPetstore.ModelLens, SwaggerPetstore
tagNameSwaggerPetstore.Model, SwaggerPetstore
tagNameLSwaggerPetstore.ModelLens, SwaggerPetstore
Tags 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
TestClassnameSwaggerPetstore.API, SwaggerPetstore
testClassnameSwaggerPetstore.API, SwaggerPetstore
TestClientModelSwaggerPetstore.API, SwaggerPetstore
testClientModelSwaggerPetstore.API, SwaggerPetstore
TestEndpointParametersSwaggerPetstore.API, SwaggerPetstore
testEndpointParametersSwaggerPetstore.API, SwaggerPetstore
TestEnumParametersSwaggerPetstore.API, SwaggerPetstore
testEnumParametersSwaggerPetstore.API, SwaggerPetstore
TestJsonFormDataSwaggerPetstore.API, SwaggerPetstore
testJsonFormDataSwaggerPetstore.API, SwaggerPetstore
TestSpecialTagsSwaggerPetstore.API, SwaggerPetstore
testSpecialTagsSwaggerPetstore.API, SwaggerPetstore
toFormSwaggerPetstore.Core, SwaggerPetstore
toFormCollSwaggerPetstore.Core, SwaggerPetstore
toHeaderSwaggerPetstore.Core, SwaggerPetstore
toHeaderCollSwaggerPetstore.Core, SwaggerPetstore
toPathSwaggerPetstore.Core, SwaggerPetstore
toQuerySwaggerPetstore.Core, SwaggerPetstore
toQueryCollSwaggerPetstore.Core, SwaggerPetstore
unAdditionalMetadataSwaggerPetstore.API, SwaggerPetstore
unApiKeySwaggerPetstore.API, SwaggerPetstore
unBinarySwaggerPetstore.Core, SwaggerPetstore
unBodySwaggerPetstore.API, SwaggerPetstore
unByteSwaggerPetstore.API, SwaggerPetstore
unByteArraySwaggerPetstore.Core, SwaggerPetstore
unCallbackSwaggerPetstore.API, SwaggerPetstore
unDateSwaggerPetstore.Core, SwaggerPetstore
unDateTimeSwaggerPetstore.Core, SwaggerPetstore
unEnumFormStringSwaggerPetstore.API, SwaggerPetstore
unEnumFormStringArraySwaggerPetstore.API, SwaggerPetstore
unEnumHeaderStringSwaggerPetstore.API, SwaggerPetstore
unEnumHeaderStringArraySwaggerPetstore.API, SwaggerPetstore
unEnumQueryDoubleSwaggerPetstore.API, SwaggerPetstore
unEnumQueryIntegerSwaggerPetstore.API, SwaggerPetstore
unEnumQueryStringSwaggerPetstore.API, SwaggerPetstore
unEnumQueryStringArraySwaggerPetstore.API, SwaggerPetstore
unFileSwaggerPetstore.API, SwaggerPetstore
unInitRequestSwaggerPetstore.Client, SwaggerPetstore
unInt32SwaggerPetstore.API, SwaggerPetstore
unInt64SwaggerPetstore.API, SwaggerPetstore
unName2SwaggerPetstore.API, SwaggerPetstore
unNumberSwaggerPetstore.API, SwaggerPetstore
unOrderIdSwaggerPetstore.API, SwaggerPetstore
unOrderIdTextSwaggerPetstore.API, SwaggerPetstore
unOuterBooleanSwaggerPetstore.Model, SwaggerPetstore
unOuterNumberSwaggerPetstore.Model, SwaggerPetstore
unOuterStringSwaggerPetstore.Model, SwaggerPetstore
unParamSwaggerPetstore.API, SwaggerPetstore
unParam2SwaggerPetstore.API, SwaggerPetstore
unParamBinarySwaggerPetstore.API, SwaggerPetstore
unParamDateSwaggerPetstore.API, SwaggerPetstore
unParamDateTimeSwaggerPetstore.API, SwaggerPetstore
unParamDoubleSwaggerPetstore.API, SwaggerPetstore
unParamFloatSwaggerPetstore.API, SwaggerPetstore
unParamIntegerSwaggerPetstore.API, SwaggerPetstore
unParamStringSwaggerPetstore.API, SwaggerPetstore
unPasswordSwaggerPetstore.API, SwaggerPetstore
unPatternWithoutDelimiterSwaggerPetstore.API, SwaggerPetstore
unPetIdSwaggerPetstore.API, SwaggerPetstore
unStatusSwaggerPetstore.API, SwaggerPetstore
unStatusTextSwaggerPetstore.API, SwaggerPetstore
unTagsSwaggerPetstore.API, SwaggerPetstore
unUsernameSwaggerPetstore.API, SwaggerPetstore
UpdatePetSwaggerPetstore.API, SwaggerPetstore
updatePetSwaggerPetstore.API, SwaggerPetstore
UpdatePetWithFormSwaggerPetstore.API, SwaggerPetstore
updatePetWithFormSwaggerPetstore.API, SwaggerPetstore
UpdateUserSwaggerPetstore.API, SwaggerPetstore
updateUserSwaggerPetstore.API, SwaggerPetstore
UploadFileSwaggerPetstore.API, SwaggerPetstore
uploadFileSwaggerPetstore.API, SwaggerPetstore
User 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
userEmailSwaggerPetstore.Model, SwaggerPetstore
userEmailLSwaggerPetstore.ModelLens, SwaggerPetstore
userFirstNameSwaggerPetstore.Model, SwaggerPetstore
userFirstNameLSwaggerPetstore.ModelLens, SwaggerPetstore
userIdSwaggerPetstore.Model, SwaggerPetstore
userIdLSwaggerPetstore.ModelLens, SwaggerPetstore
userLastNameSwaggerPetstore.Model, SwaggerPetstore
userLastNameLSwaggerPetstore.ModelLens, SwaggerPetstore
Username 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
userPasswordSwaggerPetstore.Model, SwaggerPetstore
userPasswordLSwaggerPetstore.ModelLens, SwaggerPetstore
userPhoneSwaggerPetstore.Model, SwaggerPetstore
userPhoneLSwaggerPetstore.ModelLens, SwaggerPetstore
userUsernameSwaggerPetstore.Model, SwaggerPetstore
userUsernameLSwaggerPetstore.ModelLens, SwaggerPetstore
userUserStatusSwaggerPetstore.Model, SwaggerPetstore
userUserStatusLSwaggerPetstore.ModelLens, SwaggerPetstore
withNoLoggingSwaggerPetstore.Core, SwaggerPetstore
withStderrLoggingSwaggerPetstore.Core, SwaggerPetstore
withStdoutLoggingSwaggerPetstore.Core, SwaggerPetstore
_addMultiFormPartSwaggerPetstore.Core, SwaggerPetstore
_applyAuthMethodsSwaggerPetstore.Core, SwaggerPetstore
_emptyToNothingSwaggerPetstore.Core, SwaggerPetstore
_hasAuthTypeSwaggerPetstore.Core, SwaggerPetstore
_logSwaggerPetstore.Logging, SwaggerPetstore
_memptyToNothingSwaggerPetstore.Core, SwaggerPetstore
_mkParamsSwaggerPetstore.Core, SwaggerPetstore
_mkRequestSwaggerPetstore.Core, SwaggerPetstore
_omitNullsSwaggerPetstore.Core, SwaggerPetstore
_parseISO8601SwaggerPetstore.Core, SwaggerPetstore
_readBinaryBase64SwaggerPetstore.Core, SwaggerPetstore
_readByteArraySwaggerPetstore.Core, SwaggerPetstore
_readDateSwaggerPetstore.Core, SwaggerPetstore
_readDateTimeSwaggerPetstore.Core, SwaggerPetstore
_setAcceptHeaderSwaggerPetstore.Core, SwaggerPetstore
_setBodyBSSwaggerPetstore.Core, SwaggerPetstore
_setBodyLBSSwaggerPetstore.Core, SwaggerPetstore
_setContentTypeHeaderSwaggerPetstore.Core, SwaggerPetstore
_showBinaryBase64SwaggerPetstore.Core, SwaggerPetstore
_showByteArraySwaggerPetstore.Core, SwaggerPetstore
_showDateSwaggerPetstore.Core, SwaggerPetstore
_showDateTimeSwaggerPetstore.Core, SwaggerPetstore
_toCollSwaggerPetstore.Core, SwaggerPetstore
_toCollASwaggerPetstore.Core, SwaggerPetstore
_toCollA'SwaggerPetstore.Core, SwaggerPetstore
_toFormItemSwaggerPetstore.Core, SwaggerPetstore
_toInitRequestSwaggerPetstore.Client, SwaggerPetstore
\ No newline at end of file +

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index

-&-SwaggerPetstore.Core, SwaggerPetstore
Accept 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
addAuthMethodSwaggerPetstore.Core, SwaggerPetstore
addFormSwaggerPetstore.Core, SwaggerPetstore
AdditionalMetadata 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
AdditionalPropertiesClass 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
additionalPropertiesClassMapOfMapPropertySwaggerPetstore.Model, SwaggerPetstore
additionalPropertiesClassMapOfMapPropertyLSwaggerPetstore.ModelLens, SwaggerPetstore
additionalPropertiesClassMapPropertySwaggerPetstore.Model, SwaggerPetstore
additionalPropertiesClassMapPropertyLSwaggerPetstore.ModelLens, SwaggerPetstore
AddPetSwaggerPetstore.API, SwaggerPetstore
addPetSwaggerPetstore.API, SwaggerPetstore
Animal 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
animalClassNameSwaggerPetstore.Model, SwaggerPetstore
animalClassNameLSwaggerPetstore.ModelLens, SwaggerPetstore
animalColorSwaggerPetstore.Model, SwaggerPetstore
animalColorLSwaggerPetstore.ModelLens, SwaggerPetstore
AnimalFarm 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
AnyAuthMethod 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
ApiKey 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ApiResponse 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
apiResponseCodeSwaggerPetstore.Model, SwaggerPetstore
apiResponseCodeLSwaggerPetstore.ModelLens, SwaggerPetstore
apiResponseMessageSwaggerPetstore.Model, SwaggerPetstore
apiResponseMessageLSwaggerPetstore.ModelLens, SwaggerPetstore
apiResponseTypeSwaggerPetstore.Model, SwaggerPetstore
apiResponseTypeLSwaggerPetstore.ModelLens, SwaggerPetstore
applyAuthMethodSwaggerPetstore.Core, SwaggerPetstore
applyOptionalParamSwaggerPetstore.Core, SwaggerPetstore
ArrayOfArrayOfNumberOnly 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
arrayOfArrayOfNumberOnlyArrayArrayNumberSwaggerPetstore.Model, SwaggerPetstore
arrayOfArrayOfNumberOnlyArrayArrayNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
ArrayOfNumberOnly 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
arrayOfNumberOnlyArrayNumberSwaggerPetstore.Model, SwaggerPetstore
arrayOfNumberOnlyArrayNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
ArrayTest 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
arrayTestArrayArrayOfIntegerSwaggerPetstore.Model, SwaggerPetstore
arrayTestArrayArrayOfIntegerLSwaggerPetstore.ModelLens, SwaggerPetstore
arrayTestArrayArrayOfModelSwaggerPetstore.Model, SwaggerPetstore
arrayTestArrayArrayOfModelLSwaggerPetstore.ModelLens, SwaggerPetstore
arrayTestArrayOfStringSwaggerPetstore.Model, SwaggerPetstore
arrayTestArrayOfStringLSwaggerPetstore.ModelLens, SwaggerPetstore
AuthApiKeyApiKey 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
AuthApiKeyApiKeyQuery 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
AuthBasicHttpBasicTest 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
AuthMethodSwaggerPetstore.Core, SwaggerPetstore
AuthMethodException 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
AuthOAuthPetstoreAuth 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Binary 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
Body 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Byte 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ByteArray 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
Callback 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Capitalization 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
capitalizationAttNameSwaggerPetstore.Model, SwaggerPetstore
capitalizationAttNameLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationCapitalCamelSwaggerPetstore.Model, SwaggerPetstore
capitalizationCapitalCamelLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationCapitalSnakeSwaggerPetstore.Model, SwaggerPetstore
capitalizationCapitalSnakeLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationScaEthFlowPointsSwaggerPetstore.Model, SwaggerPetstore
capitalizationScaEthFlowPointsLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationSmallCamelSwaggerPetstore.Model, SwaggerPetstore
capitalizationSmallCamelLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationSmallSnakeSwaggerPetstore.Model, SwaggerPetstore
capitalizationSmallSnakeLSwaggerPetstore.ModelLens, SwaggerPetstore
Cat 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
catClassNameSwaggerPetstore.Model, SwaggerPetstore
catClassNameLSwaggerPetstore.ModelLens, SwaggerPetstore
catColorSwaggerPetstore.Model, SwaggerPetstore
catColorLSwaggerPetstore.ModelLens, SwaggerPetstore
catDeclawedSwaggerPetstore.Model, SwaggerPetstore
catDeclawedLSwaggerPetstore.ModelLens, SwaggerPetstore
Category 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
categoryIdSwaggerPetstore.Model, SwaggerPetstore
categoryIdLSwaggerPetstore.ModelLens, SwaggerPetstore
categoryNameSwaggerPetstore.Model, SwaggerPetstore
categoryNameLSwaggerPetstore.ModelLens, SwaggerPetstore
ClassModel 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
classModelClassSwaggerPetstore.Model, SwaggerPetstore
classModelClassLSwaggerPetstore.ModelLens, SwaggerPetstore
Client 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
clientClientSwaggerPetstore.Model, SwaggerPetstore
clientClientLSwaggerPetstore.ModelLens, SwaggerPetstore
CollectionFormatSwaggerPetstore.Core, SwaggerPetstore
CommaSeparatedSwaggerPetstore.Core, SwaggerPetstore
configAuthMethodsSwaggerPetstore.Core, SwaggerPetstore
configHostSwaggerPetstore.Core, SwaggerPetstore
configLogContextSwaggerPetstore.Core, SwaggerPetstore
configLogExecWithContextSwaggerPetstore.Core, SwaggerPetstore
configUserAgentSwaggerPetstore.Core, SwaggerPetstore
configValidateAuthMethodsSwaggerPetstore.Core, SwaggerPetstore
ConsumesSwaggerPetstore.MimeTypes, SwaggerPetstore
ContentType 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
CreateUserSwaggerPetstore.API, SwaggerPetstore
createUserSwaggerPetstore.API, SwaggerPetstore
CreateUsersWithArrayInputSwaggerPetstore.API, SwaggerPetstore
createUsersWithArrayInputSwaggerPetstore.API, SwaggerPetstore
CreateUsersWithListInputSwaggerPetstore.API, SwaggerPetstore
createUsersWithListInputSwaggerPetstore.API, SwaggerPetstore
Date 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
DateTime 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
DeleteOrderSwaggerPetstore.API, SwaggerPetstore
deleteOrderSwaggerPetstore.API, SwaggerPetstore
DeletePetSwaggerPetstore.API, SwaggerPetstore
deletePetSwaggerPetstore.API, SwaggerPetstore
DeleteUserSwaggerPetstore.API, SwaggerPetstore
deleteUserSwaggerPetstore.API, SwaggerPetstore
dispatchInitUnsafeSwaggerPetstore.Client, SwaggerPetstore
dispatchLbsSwaggerPetstore.Client, SwaggerPetstore
dispatchLbsUnsafeSwaggerPetstore.Client, SwaggerPetstore
dispatchMimeSwaggerPetstore.Client, SwaggerPetstore
dispatchMime'SwaggerPetstore.Client, SwaggerPetstore
Dog 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
dogBreedSwaggerPetstore.Model, SwaggerPetstore
dogBreedLSwaggerPetstore.ModelLens, SwaggerPetstore
dogClassNameSwaggerPetstore.Model, SwaggerPetstore
dogClassNameLSwaggerPetstore.ModelLens, SwaggerPetstore
dogColorSwaggerPetstore.Model, SwaggerPetstore
dogColorLSwaggerPetstore.ModelLens, SwaggerPetstore
E'ArrayEnumSwaggerPetstore.Model, SwaggerPetstore
E'ArrayEnum'CrabSwaggerPetstore.Model, SwaggerPetstore
E'ArrayEnum'FishSwaggerPetstore.Model, SwaggerPetstore
E'EnumFormStringSwaggerPetstore.Model, SwaggerPetstore
E'EnumFormString'_abcSwaggerPetstore.Model, SwaggerPetstore
E'EnumFormString'_efgSwaggerPetstore.Model, SwaggerPetstore
E'EnumFormString'_xyzSwaggerPetstore.Model, SwaggerPetstore
E'EnumIntegerSwaggerPetstore.Model, SwaggerPetstore
E'EnumInteger'Num1SwaggerPetstore.Model, SwaggerPetstore
E'EnumInteger'NumMinus_1SwaggerPetstore.Model, SwaggerPetstore
E'EnumNumberSwaggerPetstore.Model, SwaggerPetstore
E'EnumNumber'Num1_Dot_1SwaggerPetstore.Model, SwaggerPetstore
E'EnumNumber'NumMinus_1_Dot_2SwaggerPetstore.Model, SwaggerPetstore
E'EnumQueryIntegerSwaggerPetstore.Model, SwaggerPetstore
E'EnumQueryInteger'Num1SwaggerPetstore.Model, SwaggerPetstore
E'EnumQueryInteger'NumMinus_2SwaggerPetstore.Model, SwaggerPetstore
E'EnumStringSwaggerPetstore.Model, SwaggerPetstore
E'EnumString'EmptySwaggerPetstore.Model, SwaggerPetstore
E'EnumString'LowerSwaggerPetstore.Model, SwaggerPetstore
E'EnumString'UPPERSwaggerPetstore.Model, SwaggerPetstore
E'InnerSwaggerPetstore.Model, SwaggerPetstore
E'Inner'LowerSwaggerPetstore.Model, SwaggerPetstore
E'Inner'UPPERSwaggerPetstore.Model, SwaggerPetstore
E'Inner2SwaggerPetstore.Model, SwaggerPetstore
E'Inner2'DollarSwaggerPetstore.Model, SwaggerPetstore
E'Inner2'GreaterThanSwaggerPetstore.Model, SwaggerPetstore
E'JustSymbolSwaggerPetstore.Model, SwaggerPetstore
E'JustSymbol'DollarSwaggerPetstore.Model, SwaggerPetstore
E'JustSymbol'Greater_Than_Or_Equal_ToSwaggerPetstore.Model, SwaggerPetstore
E'StatusSwaggerPetstore.Model, SwaggerPetstore
E'Status'ApprovedSwaggerPetstore.Model, SwaggerPetstore
E'Status'DeliveredSwaggerPetstore.Model, SwaggerPetstore
E'Status'PlacedSwaggerPetstore.Model, SwaggerPetstore
E'Status2SwaggerPetstore.Model, SwaggerPetstore
E'Status2'AvailableSwaggerPetstore.Model, SwaggerPetstore
E'Status2'PendingSwaggerPetstore.Model, SwaggerPetstore
E'Status2'SoldSwaggerPetstore.Model, SwaggerPetstore
EnumArrays 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
enumArraysArrayEnumSwaggerPetstore.Model, SwaggerPetstore
enumArraysArrayEnumLSwaggerPetstore.ModelLens, SwaggerPetstore
enumArraysJustSymbolSwaggerPetstore.Model, SwaggerPetstore
enumArraysJustSymbolLSwaggerPetstore.ModelLens, SwaggerPetstore
EnumClassSwaggerPetstore.Model, SwaggerPetstore
EnumClass'_abcSwaggerPetstore.Model, SwaggerPetstore
EnumClass'_efgSwaggerPetstore.Model, SwaggerPetstore
EnumClass'_xyzSwaggerPetstore.Model, SwaggerPetstore
EnumFormString 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumFormStringArray 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumHeaderString 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumHeaderStringArray 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumQueryDouble 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumQueryInteger 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumQueryString 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumQueryStringArray 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumTest 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
enumTestEnumIntegerSwaggerPetstore.Model, SwaggerPetstore
enumTestEnumIntegerLSwaggerPetstore.ModelLens, SwaggerPetstore
enumTestEnumNumberSwaggerPetstore.Model, SwaggerPetstore
enumTestEnumNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
enumTestEnumStringSwaggerPetstore.Model, SwaggerPetstore
enumTestEnumStringLSwaggerPetstore.ModelLens, SwaggerPetstore
enumTestOuterEnumSwaggerPetstore.Model, SwaggerPetstore
enumTestOuterEnumLSwaggerPetstore.ModelLens, SwaggerPetstore
FakeOuterBooleanSerializeSwaggerPetstore.API, SwaggerPetstore
fakeOuterBooleanSerializeSwaggerPetstore.API, SwaggerPetstore
FakeOuterCompositeSerializeSwaggerPetstore.API, SwaggerPetstore
fakeOuterCompositeSerializeSwaggerPetstore.API, SwaggerPetstore
FakeOuterNumberSerializeSwaggerPetstore.API, SwaggerPetstore
fakeOuterNumberSerializeSwaggerPetstore.API, SwaggerPetstore
FakeOuterStringSerializeSwaggerPetstore.API, SwaggerPetstore
fakeOuterStringSerializeSwaggerPetstore.API, SwaggerPetstore
File 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
FindPetsByStatusSwaggerPetstore.API, SwaggerPetstore
findPetsByStatusSwaggerPetstore.API, SwaggerPetstore
FindPetsByTagsSwaggerPetstore.API, SwaggerPetstore
findPetsByTagsSwaggerPetstore.API, SwaggerPetstore
FormatTest 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
formatTestBinarySwaggerPetstore.Model, SwaggerPetstore
formatTestBinaryLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestByteSwaggerPetstore.Model, SwaggerPetstore
formatTestByteLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestDateSwaggerPetstore.Model, SwaggerPetstore
formatTestDateLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestDateTimeSwaggerPetstore.Model, SwaggerPetstore
formatTestDateTimeLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestDoubleSwaggerPetstore.Model, SwaggerPetstore
formatTestDoubleLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestFloatSwaggerPetstore.Model, SwaggerPetstore
formatTestFloatLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestInt32SwaggerPetstore.Model, SwaggerPetstore
formatTestInt32LSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestInt64SwaggerPetstore.Model, SwaggerPetstore
formatTestInt64LSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestIntegerSwaggerPetstore.Model, SwaggerPetstore
formatTestIntegerLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestNumberSwaggerPetstore.Model, SwaggerPetstore
formatTestNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestPasswordSwaggerPetstore.Model, SwaggerPetstore
formatTestPasswordLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestStringSwaggerPetstore.Model, SwaggerPetstore
formatTestStringLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestUuidSwaggerPetstore.Model, SwaggerPetstore
formatTestUuidLSwaggerPetstore.ModelLens, SwaggerPetstore
fromE'ArrayEnumSwaggerPetstore.Model, SwaggerPetstore
fromE'EnumFormStringSwaggerPetstore.Model, SwaggerPetstore
fromE'EnumIntegerSwaggerPetstore.Model, SwaggerPetstore
fromE'EnumNumberSwaggerPetstore.Model, SwaggerPetstore
fromE'EnumQueryIntegerSwaggerPetstore.Model, SwaggerPetstore
fromE'EnumStringSwaggerPetstore.Model, SwaggerPetstore
fromE'InnerSwaggerPetstore.Model, SwaggerPetstore
fromE'Inner2SwaggerPetstore.Model, SwaggerPetstore
fromE'JustSymbolSwaggerPetstore.Model, SwaggerPetstore
fromE'StatusSwaggerPetstore.Model, SwaggerPetstore
fromE'Status2SwaggerPetstore.Model, SwaggerPetstore
fromEnumClassSwaggerPetstore.Model, SwaggerPetstore
fromOuterEnumSwaggerPetstore.Model, SwaggerPetstore
GetInventorySwaggerPetstore.API, SwaggerPetstore
getInventorySwaggerPetstore.API, SwaggerPetstore
GetOrderByIdSwaggerPetstore.API, SwaggerPetstore
getOrderByIdSwaggerPetstore.API, SwaggerPetstore
GetPetByIdSwaggerPetstore.API, SwaggerPetstore
getPetByIdSwaggerPetstore.API, SwaggerPetstore
GetUserByNameSwaggerPetstore.API, SwaggerPetstore
getUserByNameSwaggerPetstore.API, SwaggerPetstore
HasBodyParamSwaggerPetstore.Core, SwaggerPetstore
HasOnlyReadOnly 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
hasOnlyReadOnlyBarSwaggerPetstore.Model, SwaggerPetstore
hasOnlyReadOnlyBarLSwaggerPetstore.ModelLens, SwaggerPetstore
hasOnlyReadOnlyFooSwaggerPetstore.Model, SwaggerPetstore
hasOnlyReadOnlyFooLSwaggerPetstore.ModelLens, SwaggerPetstore
HasOptionalParamSwaggerPetstore.Core, SwaggerPetstore
initLogContextSwaggerPetstore.Logging, SwaggerPetstore
InitRequest 
1 (Type/Class)SwaggerPetstore.Client, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Client, SwaggerPetstore
Int32 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Int64 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Lens_SwaggerPetstore.Core, SwaggerPetstore
Lens_'SwaggerPetstore.Core, SwaggerPetstore
levelDebugSwaggerPetstore.Logging, SwaggerPetstore
levelErrorSwaggerPetstore.Logging, SwaggerPetstore
levelInfoSwaggerPetstore.Logging, SwaggerPetstore
LogContextSwaggerPetstore.Logging, SwaggerPetstore
logExceptionsSwaggerPetstore.Logging, SwaggerPetstore
LogExecSwaggerPetstore.Logging, SwaggerPetstore
LogExecWithContextSwaggerPetstore.Logging, SwaggerPetstore
LoginUserSwaggerPetstore.API, SwaggerPetstore
loginUserSwaggerPetstore.API, SwaggerPetstore
LogLevelSwaggerPetstore.Logging, SwaggerPetstore
LogoutUserSwaggerPetstore.API, SwaggerPetstore
logoutUserSwaggerPetstore.API, SwaggerPetstore
MapTest 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
mapTestMapMapOfStringSwaggerPetstore.Model, SwaggerPetstore
mapTestMapMapOfStringLSwaggerPetstore.ModelLens, SwaggerPetstore
mapTestMapOfEnumStringSwaggerPetstore.Model, SwaggerPetstore
mapTestMapOfEnumStringLSwaggerPetstore.ModelLens, SwaggerPetstore
MimeAny 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeError 
1 (Type/Class)SwaggerPetstore.Client, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Client, SwaggerPetstore
mimeErrorSwaggerPetstore.Client, SwaggerPetstore
mimeErrorResponseSwaggerPetstore.Client, SwaggerPetstore
MimeFormUrlEncoded 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeJSON 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeJsonCharsetutf8 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
MimeMultipartFormData 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeNoContent 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeOctetStream 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimePlainText 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeRenderSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeRenderSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeRender'SwaggerPetstore.MimeTypes, SwaggerPetstore
mimeRenderDefaultMultipartFormDataSwaggerPetstore.MimeTypes, SwaggerPetstore
MimeResult 
1 (Type/Class)SwaggerPetstore.Client, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Client, SwaggerPetstore
mimeResultSwaggerPetstore.Client, SwaggerPetstore
mimeResultResponseSwaggerPetstore.Client, SwaggerPetstore
MimeTypeSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeTypeSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeType'SwaggerPetstore.MimeTypes, SwaggerPetstore
mimeTypesSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeTypes'SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeUnrenderSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeUnrenderSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeUnrender'SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeXML 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeXmlCharsetutf8 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
MixedPropertiesAndAdditionalPropertiesClass 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassDateTimeSwaggerPetstore.Model, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassDateTimeLSwaggerPetstore.ModelLens, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassMapSwaggerPetstore.Model, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassMapLSwaggerPetstore.ModelLens, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassUuidSwaggerPetstore.Model, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassUuidLSwaggerPetstore.ModelLens, SwaggerPetstore
mkAdditionalPropertiesClassSwaggerPetstore.Model, SwaggerPetstore
mkAnimalSwaggerPetstore.Model, SwaggerPetstore
mkAnimalFarmSwaggerPetstore.Model, SwaggerPetstore
mkApiResponseSwaggerPetstore.Model, SwaggerPetstore
mkArrayOfArrayOfNumberOnlySwaggerPetstore.Model, SwaggerPetstore
mkArrayOfNumberOnlySwaggerPetstore.Model, SwaggerPetstore
mkArrayTestSwaggerPetstore.Model, SwaggerPetstore
mkCapitalizationSwaggerPetstore.Model, SwaggerPetstore
mkCatSwaggerPetstore.Model, SwaggerPetstore
mkCategorySwaggerPetstore.Model, SwaggerPetstore
mkClassModelSwaggerPetstore.Model, SwaggerPetstore
mkClientSwaggerPetstore.Model, SwaggerPetstore
mkDogSwaggerPetstore.Model, SwaggerPetstore
mkEnumArraysSwaggerPetstore.Model, SwaggerPetstore
mkEnumTestSwaggerPetstore.Model, SwaggerPetstore
mkFormatTestSwaggerPetstore.Model, SwaggerPetstore
mkHasOnlyReadOnlySwaggerPetstore.Model, SwaggerPetstore
mkMapTestSwaggerPetstore.Model, SwaggerPetstore
mkMixedPropertiesAndAdditionalPropertiesClassSwaggerPetstore.Model, SwaggerPetstore
mkModel200ResponseSwaggerPetstore.Model, SwaggerPetstore
mkModelListSwaggerPetstore.Model, SwaggerPetstore
mkModelReturnSwaggerPetstore.Model, SwaggerPetstore
mkNameSwaggerPetstore.Model, SwaggerPetstore
mkNumberOnlySwaggerPetstore.Model, SwaggerPetstore
mkOrderSwaggerPetstore.Model, SwaggerPetstore
mkOuterCompositeSwaggerPetstore.Model, SwaggerPetstore
mkPetSwaggerPetstore.Model, SwaggerPetstore
mkReadOnlyFirstSwaggerPetstore.Model, SwaggerPetstore
mkSpecialModelNameSwaggerPetstore.Model, SwaggerPetstore
mkTagSwaggerPetstore.Model, SwaggerPetstore
mkUserSwaggerPetstore.Model, SwaggerPetstore
Model200Response 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
model200ResponseClassSwaggerPetstore.Model, SwaggerPetstore
model200ResponseClassLSwaggerPetstore.ModelLens, SwaggerPetstore
model200ResponseNameSwaggerPetstore.Model, SwaggerPetstore
model200ResponseNameLSwaggerPetstore.ModelLens, SwaggerPetstore
ModelList 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
modelList123ListSwaggerPetstore.Model, SwaggerPetstore
modelList123ListLSwaggerPetstore.ModelLens, SwaggerPetstore
ModelReturn 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
modelReturnReturnSwaggerPetstore.Model, SwaggerPetstore
modelReturnReturnLSwaggerPetstore.ModelLens, SwaggerPetstore
modifyInitRequestSwaggerPetstore.Client, SwaggerPetstore
modifyInitRequestMSwaggerPetstore.Client, SwaggerPetstore
MultiParamArraySwaggerPetstore.Core, SwaggerPetstore
Name 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
name123NumberSwaggerPetstore.Model, SwaggerPetstore
name123NumberLSwaggerPetstore.ModelLens, SwaggerPetstore
Name2 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
nameNameSwaggerPetstore.Model, SwaggerPetstore
nameNameLSwaggerPetstore.ModelLens, SwaggerPetstore
namePropertySwaggerPetstore.Model, SwaggerPetstore
namePropertyLSwaggerPetstore.ModelLens, SwaggerPetstore
nameSnakeCaseSwaggerPetstore.Model, SwaggerPetstore
nameSnakeCaseLSwaggerPetstore.ModelLens, SwaggerPetstore
newConfigSwaggerPetstore.Core, SwaggerPetstore
NoContent 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
Number 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
NumberOnly 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
numberOnlyJustNumberSwaggerPetstore.Model, SwaggerPetstore
numberOnlyJustNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
Order 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
orderCompleteSwaggerPetstore.Model, SwaggerPetstore
orderCompleteLSwaggerPetstore.ModelLens, SwaggerPetstore
OrderId 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
orderIdSwaggerPetstore.Model, SwaggerPetstore
orderIdLSwaggerPetstore.ModelLens, SwaggerPetstore
OrderIdText 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
orderPetIdSwaggerPetstore.Model, SwaggerPetstore
orderPetIdLSwaggerPetstore.ModelLens, SwaggerPetstore
orderQuantitySwaggerPetstore.Model, SwaggerPetstore
orderQuantityLSwaggerPetstore.ModelLens, SwaggerPetstore
orderShipDateSwaggerPetstore.Model, SwaggerPetstore
orderShipDateLSwaggerPetstore.ModelLens, SwaggerPetstore
orderStatusSwaggerPetstore.Model, SwaggerPetstore
orderStatusLSwaggerPetstore.ModelLens, SwaggerPetstore
OuterBoolean 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
OuterComposite 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
outerCompositeMyBooleanSwaggerPetstore.Model, SwaggerPetstore
outerCompositeMyBooleanLSwaggerPetstore.ModelLens, SwaggerPetstore
outerCompositeMyNumberSwaggerPetstore.Model, SwaggerPetstore
outerCompositeMyNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
outerCompositeMyStringSwaggerPetstore.Model, SwaggerPetstore
outerCompositeMyStringLSwaggerPetstore.ModelLens, SwaggerPetstore
OuterEnumSwaggerPetstore.Model, SwaggerPetstore
OuterEnum'ApprovedSwaggerPetstore.Model, SwaggerPetstore
OuterEnum'DeliveredSwaggerPetstore.Model, SwaggerPetstore
OuterEnum'PlacedSwaggerPetstore.Model, SwaggerPetstore
OuterNumber 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
OuterString 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
Param 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Param2 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ParamBinary 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ParamBodySwaggerPetstore.Core, SwaggerPetstore
ParamBodyBSwaggerPetstore.Core, SwaggerPetstore
ParamBodyBLSwaggerPetstore.Core, SwaggerPetstore
ParamBodyFormUrlEncodedSwaggerPetstore.Core, SwaggerPetstore
ParamBodyMultipartFormDataSwaggerPetstore.Core, SwaggerPetstore
ParamBodyNoneSwaggerPetstore.Core, SwaggerPetstore
ParamDate 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ParamDateTime 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ParamDouble 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ParamFloat 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
ParamInteger 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Params 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
paramsBodySwaggerPetstore.Core, SwaggerPetstore
paramsBodyLSwaggerPetstore.Core, SwaggerPetstore
paramsHeadersSwaggerPetstore.Core, SwaggerPetstore
paramsHeadersLSwaggerPetstore.Core, SwaggerPetstore
paramsQuerySwaggerPetstore.Core, SwaggerPetstore
paramsQueryLSwaggerPetstore.Core, SwaggerPetstore
ParamString 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Password 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
PatternWithoutDelimiter 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Pet 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
petCategorySwaggerPetstore.Model, SwaggerPetstore
petCategoryLSwaggerPetstore.ModelLens, SwaggerPetstore
PetId 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
petIdSwaggerPetstore.Model, SwaggerPetstore
petIdLSwaggerPetstore.ModelLens, SwaggerPetstore
petNameSwaggerPetstore.Model, SwaggerPetstore
petNameLSwaggerPetstore.ModelLens, SwaggerPetstore
petPhotoUrlsSwaggerPetstore.Model, SwaggerPetstore
petPhotoUrlsLSwaggerPetstore.ModelLens, SwaggerPetstore
petStatusSwaggerPetstore.Model, SwaggerPetstore
petStatusLSwaggerPetstore.ModelLens, SwaggerPetstore
petTagsSwaggerPetstore.Model, SwaggerPetstore
petTagsLSwaggerPetstore.ModelLens, SwaggerPetstore
PipeSeparatedSwaggerPetstore.Core, SwaggerPetstore
PlaceOrderSwaggerPetstore.API, SwaggerPetstore
placeOrderSwaggerPetstore.API, SwaggerPetstore
ProducesSwaggerPetstore.MimeTypes, SwaggerPetstore
rAuthTypesSwaggerPetstore.Core, SwaggerPetstore
rAuthTypesLSwaggerPetstore.Core, SwaggerPetstore
ReadOnlyFirst 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
readOnlyFirstBarSwaggerPetstore.Model, SwaggerPetstore
readOnlyFirstBarLSwaggerPetstore.ModelLens, SwaggerPetstore
readOnlyFirstBazSwaggerPetstore.Model, SwaggerPetstore
readOnlyFirstBazLSwaggerPetstore.ModelLens, SwaggerPetstore
removeHeaderSwaggerPetstore.Core, SwaggerPetstore
rMethodSwaggerPetstore.Core, SwaggerPetstore
rMethodLSwaggerPetstore.Core, SwaggerPetstore
rParamsSwaggerPetstore.Core, SwaggerPetstore
rParamsLSwaggerPetstore.Core, SwaggerPetstore
runConfigLogSwaggerPetstore.Client, SwaggerPetstore
runConfigLogWithExceptionsSwaggerPetstore.Client, SwaggerPetstore
runDefaultLogExecWithContextSwaggerPetstore.Logging, SwaggerPetstore
runNullLogExecSwaggerPetstore.Logging, SwaggerPetstore
rUrlPathSwaggerPetstore.Core, SwaggerPetstore
rUrlPathLSwaggerPetstore.Core, SwaggerPetstore
setBodyParamSwaggerPetstore.Core, SwaggerPetstore
setHeaderSwaggerPetstore.Core, SwaggerPetstore
setQuerySwaggerPetstore.Core, SwaggerPetstore
SpaceSeparatedSwaggerPetstore.Core, SwaggerPetstore
SpecialModelName 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
specialModelNameSpecialPropertyNameSwaggerPetstore.Model, SwaggerPetstore
specialModelNameSpecialPropertyNameLSwaggerPetstore.ModelLens, SwaggerPetstore
Status 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
StatusText 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
stderrLoggingContextSwaggerPetstore.Logging, SwaggerPetstore
stderrLoggingExecSwaggerPetstore.Logging, SwaggerPetstore
stdoutLoggingContextSwaggerPetstore.Logging, SwaggerPetstore
stdoutLoggingExecSwaggerPetstore.Logging, SwaggerPetstore
SwaggerPetstoreConfig 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
SwaggerPetstoreRequest 
1 (Type/Class)SwaggerPetstore.Core, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Core, SwaggerPetstore
TabSeparatedSwaggerPetstore.Core, SwaggerPetstore
Tag 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
tagIdSwaggerPetstore.Model, SwaggerPetstore
tagIdLSwaggerPetstore.ModelLens, SwaggerPetstore
tagNameSwaggerPetstore.Model, SwaggerPetstore
tagNameLSwaggerPetstore.ModelLens, SwaggerPetstore
Tags 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
TestClassnameSwaggerPetstore.API, SwaggerPetstore
testClassnameSwaggerPetstore.API, SwaggerPetstore
TestClientModelSwaggerPetstore.API, SwaggerPetstore
testClientModelSwaggerPetstore.API, SwaggerPetstore
TestEndpointParametersSwaggerPetstore.API, SwaggerPetstore
testEndpointParametersSwaggerPetstore.API, SwaggerPetstore
TestEnumParametersSwaggerPetstore.API, SwaggerPetstore
testEnumParametersSwaggerPetstore.API, SwaggerPetstore
TestInlineAdditionalPropertiesSwaggerPetstore.API, SwaggerPetstore
testInlineAdditionalPropertiesSwaggerPetstore.API, SwaggerPetstore
TestJsonFormDataSwaggerPetstore.API, SwaggerPetstore
testJsonFormDataSwaggerPetstore.API, SwaggerPetstore
TestSpecialTagsSwaggerPetstore.API, SwaggerPetstore
testSpecialTagsSwaggerPetstore.API, SwaggerPetstore
toE'ArrayEnumSwaggerPetstore.Model, SwaggerPetstore
toE'EnumFormStringSwaggerPetstore.Model, SwaggerPetstore
toE'EnumIntegerSwaggerPetstore.Model, SwaggerPetstore
toE'EnumNumberSwaggerPetstore.Model, SwaggerPetstore
toE'EnumQueryIntegerSwaggerPetstore.Model, SwaggerPetstore
toE'EnumStringSwaggerPetstore.Model, SwaggerPetstore
toE'InnerSwaggerPetstore.Model, SwaggerPetstore
toE'Inner2SwaggerPetstore.Model, SwaggerPetstore
toE'JustSymbolSwaggerPetstore.Model, SwaggerPetstore
toE'StatusSwaggerPetstore.Model, SwaggerPetstore
toE'Status2SwaggerPetstore.Model, SwaggerPetstore
toEnumClassSwaggerPetstore.Model, SwaggerPetstore
toFormSwaggerPetstore.Core, SwaggerPetstore
toFormCollSwaggerPetstore.Core, SwaggerPetstore
toHeaderSwaggerPetstore.Core, SwaggerPetstore
toHeaderCollSwaggerPetstore.Core, SwaggerPetstore
toOuterEnumSwaggerPetstore.Model, SwaggerPetstore
toPathSwaggerPetstore.Core, SwaggerPetstore
toQuerySwaggerPetstore.Core, SwaggerPetstore
toQueryCollSwaggerPetstore.Core, SwaggerPetstore
unAcceptSwaggerPetstore.MimeTypes, SwaggerPetstore
unAdditionalMetadataSwaggerPetstore.API, SwaggerPetstore
unApiKeySwaggerPetstore.API, SwaggerPetstore
unBinarySwaggerPetstore.Core, SwaggerPetstore
unBodySwaggerPetstore.API, SwaggerPetstore
unByteSwaggerPetstore.API, SwaggerPetstore
unByteArraySwaggerPetstore.Core, SwaggerPetstore
unCallbackSwaggerPetstore.API, SwaggerPetstore
unContentTypeSwaggerPetstore.MimeTypes, SwaggerPetstore
unDateSwaggerPetstore.Core, SwaggerPetstore
unDateTimeSwaggerPetstore.Core, SwaggerPetstore
unEnumFormStringSwaggerPetstore.API, SwaggerPetstore
unEnumFormStringArraySwaggerPetstore.API, SwaggerPetstore
unEnumHeaderStringSwaggerPetstore.API, SwaggerPetstore
unEnumHeaderStringArraySwaggerPetstore.API, SwaggerPetstore
unEnumQueryDoubleSwaggerPetstore.API, SwaggerPetstore
unEnumQueryIntegerSwaggerPetstore.API, SwaggerPetstore
unEnumQueryStringSwaggerPetstore.API, SwaggerPetstore
unEnumQueryStringArraySwaggerPetstore.API, SwaggerPetstore
unFileSwaggerPetstore.API, SwaggerPetstore
unInitRequestSwaggerPetstore.Client, SwaggerPetstore
unInt32SwaggerPetstore.API, SwaggerPetstore
unInt64SwaggerPetstore.API, SwaggerPetstore
unName2SwaggerPetstore.API, SwaggerPetstore
unNumberSwaggerPetstore.API, SwaggerPetstore
unOrderIdSwaggerPetstore.API, SwaggerPetstore
unOrderIdTextSwaggerPetstore.API, SwaggerPetstore
unOuterBooleanSwaggerPetstore.Model, SwaggerPetstore
unOuterNumberSwaggerPetstore.Model, SwaggerPetstore
unOuterStringSwaggerPetstore.Model, SwaggerPetstore
unParamSwaggerPetstore.API, SwaggerPetstore
unParam2SwaggerPetstore.API, SwaggerPetstore
unParamBinarySwaggerPetstore.API, SwaggerPetstore
unParamDateSwaggerPetstore.API, SwaggerPetstore
unParamDateTimeSwaggerPetstore.API, SwaggerPetstore
unParamDoubleSwaggerPetstore.API, SwaggerPetstore
unParamFloatSwaggerPetstore.API, SwaggerPetstore
unParamIntegerSwaggerPetstore.API, SwaggerPetstore
unParamStringSwaggerPetstore.API, SwaggerPetstore
unPasswordSwaggerPetstore.API, SwaggerPetstore
unPatternWithoutDelimiterSwaggerPetstore.API, SwaggerPetstore
unPetIdSwaggerPetstore.API, SwaggerPetstore
unStatusSwaggerPetstore.API, SwaggerPetstore
unStatusTextSwaggerPetstore.API, SwaggerPetstore
unTagsSwaggerPetstore.API, SwaggerPetstore
unUsernameSwaggerPetstore.API, SwaggerPetstore
UpdatePetSwaggerPetstore.API, SwaggerPetstore
updatePetSwaggerPetstore.API, SwaggerPetstore
UpdatePetWithFormSwaggerPetstore.API, SwaggerPetstore
updatePetWithFormSwaggerPetstore.API, SwaggerPetstore
UpdateUserSwaggerPetstore.API, SwaggerPetstore
updateUserSwaggerPetstore.API, SwaggerPetstore
UploadFileSwaggerPetstore.API, SwaggerPetstore
uploadFileSwaggerPetstore.API, SwaggerPetstore
User 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
userEmailSwaggerPetstore.Model, SwaggerPetstore
userEmailLSwaggerPetstore.ModelLens, SwaggerPetstore
userFirstNameSwaggerPetstore.Model, SwaggerPetstore
userFirstNameLSwaggerPetstore.ModelLens, SwaggerPetstore
userIdSwaggerPetstore.Model, SwaggerPetstore
userIdLSwaggerPetstore.ModelLens, SwaggerPetstore
userLastNameSwaggerPetstore.Model, SwaggerPetstore
userLastNameLSwaggerPetstore.ModelLens, SwaggerPetstore
Username 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
userPasswordSwaggerPetstore.Model, SwaggerPetstore
userPasswordLSwaggerPetstore.ModelLens, SwaggerPetstore
userPhoneSwaggerPetstore.Model, SwaggerPetstore
userPhoneLSwaggerPetstore.ModelLens, SwaggerPetstore
userUsernameSwaggerPetstore.Model, SwaggerPetstore
userUsernameLSwaggerPetstore.ModelLens, SwaggerPetstore
userUserStatusSwaggerPetstore.Model, SwaggerPetstore
userUserStatusLSwaggerPetstore.ModelLens, SwaggerPetstore
withNoLoggingSwaggerPetstore.Core, SwaggerPetstore
withStderrLoggingSwaggerPetstore.Core, SwaggerPetstore
withStdoutLoggingSwaggerPetstore.Core, SwaggerPetstore
_addMultiFormPartSwaggerPetstore.Core, SwaggerPetstore
_applyAuthMethodsSwaggerPetstore.Core, SwaggerPetstore
_emptyToNothingSwaggerPetstore.Core, SwaggerPetstore
_hasAuthTypeSwaggerPetstore.Core, SwaggerPetstore
_logSwaggerPetstore.Logging, SwaggerPetstore
_memptyToNothingSwaggerPetstore.Core, SwaggerPetstore
_mkParamsSwaggerPetstore.Core, SwaggerPetstore
_mkRequestSwaggerPetstore.Core, SwaggerPetstore
_omitNullsSwaggerPetstore.Core, SwaggerPetstore
_parseISO8601SwaggerPetstore.Core, SwaggerPetstore
_readBinaryBase64SwaggerPetstore.Core, SwaggerPetstore
_readByteArraySwaggerPetstore.Core, SwaggerPetstore
_readDateSwaggerPetstore.Core, SwaggerPetstore
_readDateTimeSwaggerPetstore.Core, SwaggerPetstore
_setAcceptHeaderSwaggerPetstore.Core, SwaggerPetstore
_setBodyBSSwaggerPetstore.Core, SwaggerPetstore
_setBodyLBSSwaggerPetstore.Core, SwaggerPetstore
_setContentTypeHeaderSwaggerPetstore.Core, SwaggerPetstore
_showBinaryBase64SwaggerPetstore.Core, SwaggerPetstore
_showByteArraySwaggerPetstore.Core, SwaggerPetstore
_showDateSwaggerPetstore.Core, SwaggerPetstore
_showDateTimeSwaggerPetstore.Core, SwaggerPetstore
_toCollSwaggerPetstore.Core, SwaggerPetstore
_toCollASwaggerPetstore.Core, SwaggerPetstore
_toCollA'SwaggerPetstore.Core, SwaggerPetstore
_toFormItemSwaggerPetstore.Core, SwaggerPetstore
_toInitRequestSwaggerPetstore.Client, SwaggerPetstore
\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/doc-index-C.html b/samples/client/petstore/haskell-http-client/docs/doc-index-C.html index 8f6c4afb14d..e83157085c0 100644 --- a/samples/client/petstore/haskell-http-client/docs/doc-index-C.html +++ b/samples/client/petstore/haskell-http-client/docs/doc-index-C.html @@ -1,4 +1,4 @@ swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client (Index - C)

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index - C

Callback 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Capitalization 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
capitalizationAttNameSwaggerPetstore.Model, SwaggerPetstore
capitalizationAttNameLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationCapitalCamelSwaggerPetstore.Model, SwaggerPetstore
capitalizationCapitalCamelLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationCapitalSnakeSwaggerPetstore.Model, SwaggerPetstore
capitalizationCapitalSnakeLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationScaEthFlowPointsSwaggerPetstore.Model, SwaggerPetstore
capitalizationScaEthFlowPointsLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationSmallCamelSwaggerPetstore.Model, SwaggerPetstore
capitalizationSmallCamelLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationSmallSnakeSwaggerPetstore.Model, SwaggerPetstore
capitalizationSmallSnakeLSwaggerPetstore.ModelLens, SwaggerPetstore
Cat 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
catClassNameSwaggerPetstore.Model, SwaggerPetstore
catClassNameLSwaggerPetstore.ModelLens, SwaggerPetstore
catColorSwaggerPetstore.Model, SwaggerPetstore
catColorLSwaggerPetstore.ModelLens, SwaggerPetstore
catDeclawedSwaggerPetstore.Model, SwaggerPetstore
catDeclawedLSwaggerPetstore.ModelLens, SwaggerPetstore
Category 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
categoryIdSwaggerPetstore.Model, SwaggerPetstore
categoryIdLSwaggerPetstore.ModelLens, SwaggerPetstore
categoryNameSwaggerPetstore.Model, SwaggerPetstore
categoryNameLSwaggerPetstore.ModelLens, SwaggerPetstore
ClassModel 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
classModelClassSwaggerPetstore.Model, SwaggerPetstore
classModelClassLSwaggerPetstore.ModelLens, SwaggerPetstore
Client 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
clientClientSwaggerPetstore.Model, SwaggerPetstore
clientClientLSwaggerPetstore.ModelLens, SwaggerPetstore
CollectionFormatSwaggerPetstore.Core, SwaggerPetstore
CommaSeparatedSwaggerPetstore.Core, SwaggerPetstore
configAuthMethodsSwaggerPetstore.Core, SwaggerPetstore
configHostSwaggerPetstore.Core, SwaggerPetstore
configLogContextSwaggerPetstore.Core, SwaggerPetstore
configLogExecWithContextSwaggerPetstore.Core, SwaggerPetstore
configUserAgentSwaggerPetstore.Core, SwaggerPetstore
configValidateAuthMethodsSwaggerPetstore.Core, SwaggerPetstore
ConsumesSwaggerPetstore.MimeTypes, SwaggerPetstore
CreateUserSwaggerPetstore.API, SwaggerPetstore
createUserSwaggerPetstore.API, SwaggerPetstore
CreateUsersWithArrayInputSwaggerPetstore.API, SwaggerPetstore
createUsersWithArrayInputSwaggerPetstore.API, SwaggerPetstore
CreateUsersWithListInputSwaggerPetstore.API, SwaggerPetstore
createUsersWithListInputSwaggerPetstore.API, SwaggerPetstore
\ No newline at end of file +

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index - C

Callback 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
Capitalization 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
capitalizationAttNameSwaggerPetstore.Model, SwaggerPetstore
capitalizationAttNameLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationCapitalCamelSwaggerPetstore.Model, SwaggerPetstore
capitalizationCapitalCamelLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationCapitalSnakeSwaggerPetstore.Model, SwaggerPetstore
capitalizationCapitalSnakeLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationScaEthFlowPointsSwaggerPetstore.Model, SwaggerPetstore
capitalizationScaEthFlowPointsLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationSmallCamelSwaggerPetstore.Model, SwaggerPetstore
capitalizationSmallCamelLSwaggerPetstore.ModelLens, SwaggerPetstore
capitalizationSmallSnakeSwaggerPetstore.Model, SwaggerPetstore
capitalizationSmallSnakeLSwaggerPetstore.ModelLens, SwaggerPetstore
Cat 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
catClassNameSwaggerPetstore.Model, SwaggerPetstore
catClassNameLSwaggerPetstore.ModelLens, SwaggerPetstore
catColorSwaggerPetstore.Model, SwaggerPetstore
catColorLSwaggerPetstore.ModelLens, SwaggerPetstore
catDeclawedSwaggerPetstore.Model, SwaggerPetstore
catDeclawedLSwaggerPetstore.ModelLens, SwaggerPetstore
Category 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
categoryIdSwaggerPetstore.Model, SwaggerPetstore
categoryIdLSwaggerPetstore.ModelLens, SwaggerPetstore
categoryNameSwaggerPetstore.Model, SwaggerPetstore
categoryNameLSwaggerPetstore.ModelLens, SwaggerPetstore
ClassModel 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
classModelClassSwaggerPetstore.Model, SwaggerPetstore
classModelClassLSwaggerPetstore.ModelLens, SwaggerPetstore
Client 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
clientClientSwaggerPetstore.Model, SwaggerPetstore
clientClientLSwaggerPetstore.ModelLens, SwaggerPetstore
CollectionFormatSwaggerPetstore.Core, SwaggerPetstore
CommaSeparatedSwaggerPetstore.Core, SwaggerPetstore
configAuthMethodsSwaggerPetstore.Core, SwaggerPetstore
configHostSwaggerPetstore.Core, SwaggerPetstore
configLogContextSwaggerPetstore.Core, SwaggerPetstore
configLogExecWithContextSwaggerPetstore.Core, SwaggerPetstore
configUserAgentSwaggerPetstore.Core, SwaggerPetstore
configValidateAuthMethodsSwaggerPetstore.Core, SwaggerPetstore
ConsumesSwaggerPetstore.MimeTypes, SwaggerPetstore
ContentType 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
CreateUserSwaggerPetstore.API, SwaggerPetstore
createUserSwaggerPetstore.API, SwaggerPetstore
CreateUsersWithArrayInputSwaggerPetstore.API, SwaggerPetstore
createUsersWithArrayInputSwaggerPetstore.API, SwaggerPetstore
CreateUsersWithListInputSwaggerPetstore.API, SwaggerPetstore
createUsersWithListInputSwaggerPetstore.API, SwaggerPetstore
\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/doc-index-E.html b/samples/client/petstore/haskell-http-client/docs/doc-index-E.html index 1fe9136d8ee..a02d55d519f 100644 --- a/samples/client/petstore/haskell-http-client/docs/doc-index-E.html +++ b/samples/client/petstore/haskell-http-client/docs/doc-index-E.html @@ -1,4 +1,4 @@ swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client (Index - E)

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index - E

EnumArrays 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
enumArraysArrayEnumSwaggerPetstore.Model, SwaggerPetstore
enumArraysArrayEnumLSwaggerPetstore.ModelLens, SwaggerPetstore
enumArraysJustSymbolSwaggerPetstore.Model, SwaggerPetstore
enumArraysJustSymbolLSwaggerPetstore.ModelLens, SwaggerPetstore
EnumClass 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
EnumFormString 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumFormStringArray 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumHeaderString 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumHeaderStringArray 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumQueryDouble 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumQueryInteger 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumQueryString 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumQueryStringArray 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumTest 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
enumTestEnumIntegerSwaggerPetstore.Model, SwaggerPetstore
enumTestEnumIntegerLSwaggerPetstore.ModelLens, SwaggerPetstore
enumTestEnumNumberSwaggerPetstore.Model, SwaggerPetstore
enumTestEnumNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
enumTestEnumStringSwaggerPetstore.Model, SwaggerPetstore
enumTestEnumStringLSwaggerPetstore.ModelLens, SwaggerPetstore
enumTestOuterEnumSwaggerPetstore.Model, SwaggerPetstore
enumTestOuterEnumLSwaggerPetstore.ModelLens, SwaggerPetstore
\ No newline at end of file +

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index - E

E'ArrayEnumSwaggerPetstore.Model, SwaggerPetstore
E'ArrayEnum'CrabSwaggerPetstore.Model, SwaggerPetstore
E'ArrayEnum'FishSwaggerPetstore.Model, SwaggerPetstore
E'EnumFormStringSwaggerPetstore.Model, SwaggerPetstore
E'EnumFormString'_abcSwaggerPetstore.Model, SwaggerPetstore
E'EnumFormString'_efgSwaggerPetstore.Model, SwaggerPetstore
E'EnumFormString'_xyzSwaggerPetstore.Model, SwaggerPetstore
E'EnumIntegerSwaggerPetstore.Model, SwaggerPetstore
E'EnumInteger'Num1SwaggerPetstore.Model, SwaggerPetstore
E'EnumInteger'NumMinus_1SwaggerPetstore.Model, SwaggerPetstore
E'EnumNumberSwaggerPetstore.Model, SwaggerPetstore
E'EnumNumber'Num1_Dot_1SwaggerPetstore.Model, SwaggerPetstore
E'EnumNumber'NumMinus_1_Dot_2SwaggerPetstore.Model, SwaggerPetstore
E'EnumQueryIntegerSwaggerPetstore.Model, SwaggerPetstore
E'EnumQueryInteger'Num1SwaggerPetstore.Model, SwaggerPetstore
E'EnumQueryInteger'NumMinus_2SwaggerPetstore.Model, SwaggerPetstore
E'EnumStringSwaggerPetstore.Model, SwaggerPetstore
E'EnumString'EmptySwaggerPetstore.Model, SwaggerPetstore
E'EnumString'LowerSwaggerPetstore.Model, SwaggerPetstore
E'EnumString'UPPERSwaggerPetstore.Model, SwaggerPetstore
E'InnerSwaggerPetstore.Model, SwaggerPetstore
E'Inner'LowerSwaggerPetstore.Model, SwaggerPetstore
E'Inner'UPPERSwaggerPetstore.Model, SwaggerPetstore
E'Inner2SwaggerPetstore.Model, SwaggerPetstore
E'Inner2'DollarSwaggerPetstore.Model, SwaggerPetstore
E'Inner2'GreaterThanSwaggerPetstore.Model, SwaggerPetstore
E'JustSymbolSwaggerPetstore.Model, SwaggerPetstore
E'JustSymbol'DollarSwaggerPetstore.Model, SwaggerPetstore
E'JustSymbol'Greater_Than_Or_Equal_ToSwaggerPetstore.Model, SwaggerPetstore
E'StatusSwaggerPetstore.Model, SwaggerPetstore
E'Status'ApprovedSwaggerPetstore.Model, SwaggerPetstore
E'Status'DeliveredSwaggerPetstore.Model, SwaggerPetstore
E'Status'PlacedSwaggerPetstore.Model, SwaggerPetstore
E'Status2SwaggerPetstore.Model, SwaggerPetstore
E'Status2'AvailableSwaggerPetstore.Model, SwaggerPetstore
E'Status2'PendingSwaggerPetstore.Model, SwaggerPetstore
E'Status2'SoldSwaggerPetstore.Model, SwaggerPetstore
EnumArrays 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
enumArraysArrayEnumSwaggerPetstore.Model, SwaggerPetstore
enumArraysArrayEnumLSwaggerPetstore.ModelLens, SwaggerPetstore
enumArraysJustSymbolSwaggerPetstore.Model, SwaggerPetstore
enumArraysJustSymbolLSwaggerPetstore.ModelLens, SwaggerPetstore
EnumClassSwaggerPetstore.Model, SwaggerPetstore
EnumClass'_abcSwaggerPetstore.Model, SwaggerPetstore
EnumClass'_efgSwaggerPetstore.Model, SwaggerPetstore
EnumClass'_xyzSwaggerPetstore.Model, SwaggerPetstore
EnumFormString 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumFormStringArray 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumHeaderString 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumHeaderStringArray 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumQueryDouble 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumQueryInteger 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumQueryString 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumQueryStringArray 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
EnumTest 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
enumTestEnumIntegerSwaggerPetstore.Model, SwaggerPetstore
enumTestEnumIntegerLSwaggerPetstore.ModelLens, SwaggerPetstore
enumTestEnumNumberSwaggerPetstore.Model, SwaggerPetstore
enumTestEnumNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
enumTestEnumStringSwaggerPetstore.Model, SwaggerPetstore
enumTestEnumStringLSwaggerPetstore.ModelLens, SwaggerPetstore
enumTestOuterEnumSwaggerPetstore.Model, SwaggerPetstore
enumTestOuterEnumLSwaggerPetstore.ModelLens, SwaggerPetstore
\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/doc-index-F.html b/samples/client/petstore/haskell-http-client/docs/doc-index-F.html index 43bb244eb57..e32e228d7f2 100644 --- a/samples/client/petstore/haskell-http-client/docs/doc-index-F.html +++ b/samples/client/petstore/haskell-http-client/docs/doc-index-F.html @@ -1,4 +1,4 @@ swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client (Index - F)

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index - F

FakeOuterBooleanSerializeSwaggerPetstore.API, SwaggerPetstore
fakeOuterBooleanSerializeSwaggerPetstore.API, SwaggerPetstore
FakeOuterCompositeSerializeSwaggerPetstore.API, SwaggerPetstore
fakeOuterCompositeSerializeSwaggerPetstore.API, SwaggerPetstore
FakeOuterNumberSerializeSwaggerPetstore.API, SwaggerPetstore
fakeOuterNumberSerializeSwaggerPetstore.API, SwaggerPetstore
FakeOuterStringSerializeSwaggerPetstore.API, SwaggerPetstore
fakeOuterStringSerializeSwaggerPetstore.API, SwaggerPetstore
File 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
FindPetsByStatusSwaggerPetstore.API, SwaggerPetstore
findPetsByStatusSwaggerPetstore.API, SwaggerPetstore
FindPetsByTagsSwaggerPetstore.API, SwaggerPetstore
findPetsByTagsSwaggerPetstore.API, SwaggerPetstore
FormatTest 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
formatTestBinarySwaggerPetstore.Model, SwaggerPetstore
formatTestBinaryLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestByteSwaggerPetstore.Model, SwaggerPetstore
formatTestByteLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestDateSwaggerPetstore.Model, SwaggerPetstore
formatTestDateLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestDateTimeSwaggerPetstore.Model, SwaggerPetstore
formatTestDateTimeLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestDoubleSwaggerPetstore.Model, SwaggerPetstore
formatTestDoubleLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestFloatSwaggerPetstore.Model, SwaggerPetstore
formatTestFloatLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestInt32SwaggerPetstore.Model, SwaggerPetstore
formatTestInt32LSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestInt64SwaggerPetstore.Model, SwaggerPetstore
formatTestInt64LSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestIntegerSwaggerPetstore.Model, SwaggerPetstore
formatTestIntegerLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestNumberSwaggerPetstore.Model, SwaggerPetstore
formatTestNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestPasswordSwaggerPetstore.Model, SwaggerPetstore
formatTestPasswordLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestStringSwaggerPetstore.Model, SwaggerPetstore
formatTestStringLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestUuidSwaggerPetstore.Model, SwaggerPetstore
formatTestUuidLSwaggerPetstore.ModelLens, SwaggerPetstore
\ No newline at end of file +

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index - F

FakeOuterBooleanSerializeSwaggerPetstore.API, SwaggerPetstore
fakeOuterBooleanSerializeSwaggerPetstore.API, SwaggerPetstore
FakeOuterCompositeSerializeSwaggerPetstore.API, SwaggerPetstore
fakeOuterCompositeSerializeSwaggerPetstore.API, SwaggerPetstore
FakeOuterNumberSerializeSwaggerPetstore.API, SwaggerPetstore
fakeOuterNumberSerializeSwaggerPetstore.API, SwaggerPetstore
FakeOuterStringSerializeSwaggerPetstore.API, SwaggerPetstore
fakeOuterStringSerializeSwaggerPetstore.API, SwaggerPetstore
File 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
FindPetsByStatusSwaggerPetstore.API, SwaggerPetstore
findPetsByStatusSwaggerPetstore.API, SwaggerPetstore
FindPetsByTagsSwaggerPetstore.API, SwaggerPetstore
findPetsByTagsSwaggerPetstore.API, SwaggerPetstore
FormatTest 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
formatTestBinarySwaggerPetstore.Model, SwaggerPetstore
formatTestBinaryLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestByteSwaggerPetstore.Model, SwaggerPetstore
formatTestByteLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestDateSwaggerPetstore.Model, SwaggerPetstore
formatTestDateLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestDateTimeSwaggerPetstore.Model, SwaggerPetstore
formatTestDateTimeLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestDoubleSwaggerPetstore.Model, SwaggerPetstore
formatTestDoubleLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestFloatSwaggerPetstore.Model, SwaggerPetstore
formatTestFloatLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestInt32SwaggerPetstore.Model, SwaggerPetstore
formatTestInt32LSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestInt64SwaggerPetstore.Model, SwaggerPetstore
formatTestInt64LSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestIntegerSwaggerPetstore.Model, SwaggerPetstore
formatTestIntegerLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestNumberSwaggerPetstore.Model, SwaggerPetstore
formatTestNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestPasswordSwaggerPetstore.Model, SwaggerPetstore
formatTestPasswordLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestStringSwaggerPetstore.Model, SwaggerPetstore
formatTestStringLSwaggerPetstore.ModelLens, SwaggerPetstore
formatTestUuidSwaggerPetstore.Model, SwaggerPetstore
formatTestUuidLSwaggerPetstore.ModelLens, SwaggerPetstore
fromE'ArrayEnumSwaggerPetstore.Model, SwaggerPetstore
fromE'EnumFormStringSwaggerPetstore.Model, SwaggerPetstore
fromE'EnumIntegerSwaggerPetstore.Model, SwaggerPetstore
fromE'EnumNumberSwaggerPetstore.Model, SwaggerPetstore
fromE'EnumQueryIntegerSwaggerPetstore.Model, SwaggerPetstore
fromE'EnumStringSwaggerPetstore.Model, SwaggerPetstore
fromE'InnerSwaggerPetstore.Model, SwaggerPetstore
fromE'Inner2SwaggerPetstore.Model, SwaggerPetstore
fromE'JustSymbolSwaggerPetstore.Model, SwaggerPetstore
fromE'StatusSwaggerPetstore.Model, SwaggerPetstore
fromE'Status2SwaggerPetstore.Model, SwaggerPetstore
fromEnumClassSwaggerPetstore.Model, SwaggerPetstore
fromOuterEnumSwaggerPetstore.Model, SwaggerPetstore
\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/doc-index-M.html b/samples/client/petstore/haskell-http-client/docs/doc-index-M.html index 8286f28c991..c7c2031d61e 100644 --- a/samples/client/petstore/haskell-http-client/docs/doc-index-M.html +++ b/samples/client/petstore/haskell-http-client/docs/doc-index-M.html @@ -1,4 +1,4 @@ swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client (Index - M)

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index - M

MapTest 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
mapTestMapMapOfStringSwaggerPetstore.Model, SwaggerPetstore
mapTestMapMapOfStringLSwaggerPetstore.ModelLens, SwaggerPetstore
mapTestMapOfEnumStringSwaggerPetstore.Model, SwaggerPetstore
mapTestMapOfEnumStringLSwaggerPetstore.ModelLens, SwaggerPetstore
MimeAny 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeError 
1 (Type/Class)SwaggerPetstore.Client, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Client, SwaggerPetstore
mimeErrorSwaggerPetstore.Client, SwaggerPetstore
mimeErrorResponseSwaggerPetstore.Client, SwaggerPetstore
MimeFormUrlEncoded 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeJSON 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeJsonCharsetutf8 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
MimeMultipartFormData 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeNoContent 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeOctetStream 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimePlainText 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeRenderSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeRenderSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeRender'SwaggerPetstore.MimeTypes, SwaggerPetstore
mimeRenderDefaultMultipartFormDataSwaggerPetstore.MimeTypes, SwaggerPetstore
MimeResult 
1 (Type/Class)SwaggerPetstore.Client, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Client, SwaggerPetstore
mimeResultSwaggerPetstore.Client, SwaggerPetstore
mimeResultResponseSwaggerPetstore.Client, SwaggerPetstore
MimeTypeSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeTypeSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeType'SwaggerPetstore.MimeTypes, SwaggerPetstore
mimeTypesSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeTypes'SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeUnrenderSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeUnrenderSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeUnrender'SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeXML 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeXmlCharsetutf8 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
MixedPropertiesAndAdditionalPropertiesClass 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassDateTimeSwaggerPetstore.Model, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassDateTimeLSwaggerPetstore.ModelLens, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassMapSwaggerPetstore.Model, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassMapLSwaggerPetstore.ModelLens, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassUuidSwaggerPetstore.Model, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassUuidLSwaggerPetstore.ModelLens, SwaggerPetstore
mkAdditionalPropertiesClassSwaggerPetstore.Model, SwaggerPetstore
mkAnimalSwaggerPetstore.Model, SwaggerPetstore
mkAnimalFarmSwaggerPetstore.Model, SwaggerPetstore
mkApiResponseSwaggerPetstore.Model, SwaggerPetstore
mkArrayOfArrayOfNumberOnlySwaggerPetstore.Model, SwaggerPetstore
mkArrayOfNumberOnlySwaggerPetstore.Model, SwaggerPetstore
mkArrayTestSwaggerPetstore.Model, SwaggerPetstore
mkCapitalizationSwaggerPetstore.Model, SwaggerPetstore
mkCatSwaggerPetstore.Model, SwaggerPetstore
mkCategorySwaggerPetstore.Model, SwaggerPetstore
mkClassModelSwaggerPetstore.Model, SwaggerPetstore
mkClientSwaggerPetstore.Model, SwaggerPetstore
mkDogSwaggerPetstore.Model, SwaggerPetstore
mkEnumArraysSwaggerPetstore.Model, SwaggerPetstore
mkEnumClassSwaggerPetstore.Model, SwaggerPetstore
mkEnumTestSwaggerPetstore.Model, SwaggerPetstore
mkFormatTestSwaggerPetstore.Model, SwaggerPetstore
mkHasOnlyReadOnlySwaggerPetstore.Model, SwaggerPetstore
mkMapTestSwaggerPetstore.Model, SwaggerPetstore
mkMixedPropertiesAndAdditionalPropertiesClassSwaggerPetstore.Model, SwaggerPetstore
mkModel200ResponseSwaggerPetstore.Model, SwaggerPetstore
mkModelListSwaggerPetstore.Model, SwaggerPetstore
mkModelReturnSwaggerPetstore.Model, SwaggerPetstore
mkNameSwaggerPetstore.Model, SwaggerPetstore
mkNumberOnlySwaggerPetstore.Model, SwaggerPetstore
mkOrderSwaggerPetstore.Model, SwaggerPetstore
mkOuterCompositeSwaggerPetstore.Model, SwaggerPetstore
mkOuterEnumSwaggerPetstore.Model, SwaggerPetstore
mkPetSwaggerPetstore.Model, SwaggerPetstore
mkReadOnlyFirstSwaggerPetstore.Model, SwaggerPetstore
mkSpecialModelNameSwaggerPetstore.Model, SwaggerPetstore
mkTagSwaggerPetstore.Model, SwaggerPetstore
mkUserSwaggerPetstore.Model, SwaggerPetstore
Model200Response 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
model200ResponseClassSwaggerPetstore.Model, SwaggerPetstore
model200ResponseClassLSwaggerPetstore.ModelLens, SwaggerPetstore
model200ResponseNameSwaggerPetstore.Model, SwaggerPetstore
model200ResponseNameLSwaggerPetstore.ModelLens, SwaggerPetstore
ModelList 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
modelList123ListSwaggerPetstore.Model, SwaggerPetstore
modelList123ListLSwaggerPetstore.ModelLens, SwaggerPetstore
ModelReturn 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
modelReturnReturnSwaggerPetstore.Model, SwaggerPetstore
modelReturnReturnLSwaggerPetstore.ModelLens, SwaggerPetstore
modifyInitRequestSwaggerPetstore.Client, SwaggerPetstore
modifyInitRequestMSwaggerPetstore.Client, SwaggerPetstore
MultiParamArraySwaggerPetstore.Core, SwaggerPetstore
\ No newline at end of file +

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index - M

MapTest 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
mapTestMapMapOfStringSwaggerPetstore.Model, SwaggerPetstore
mapTestMapMapOfStringLSwaggerPetstore.ModelLens, SwaggerPetstore
mapTestMapOfEnumStringSwaggerPetstore.Model, SwaggerPetstore
mapTestMapOfEnumStringLSwaggerPetstore.ModelLens, SwaggerPetstore
MimeAny 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeError 
1 (Type/Class)SwaggerPetstore.Client, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Client, SwaggerPetstore
mimeErrorSwaggerPetstore.Client, SwaggerPetstore
mimeErrorResponseSwaggerPetstore.Client, SwaggerPetstore
MimeFormUrlEncoded 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeJSON 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeJsonCharsetutf8 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
MimeMultipartFormData 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeNoContent 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeOctetStream 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimePlainText 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeRenderSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeRenderSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeRender'SwaggerPetstore.MimeTypes, SwaggerPetstore
mimeRenderDefaultMultipartFormDataSwaggerPetstore.MimeTypes, SwaggerPetstore
MimeResult 
1 (Type/Class)SwaggerPetstore.Client, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Client, SwaggerPetstore
mimeResultSwaggerPetstore.Client, SwaggerPetstore
mimeResultResponseSwaggerPetstore.Client, SwaggerPetstore
MimeTypeSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeTypeSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeType'SwaggerPetstore.MimeTypes, SwaggerPetstore
mimeTypesSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeTypes'SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeUnrenderSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeUnrenderSwaggerPetstore.MimeTypes, SwaggerPetstore
mimeUnrender'SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeXML 
1 (Type/Class)SwaggerPetstore.MimeTypes, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.MimeTypes, SwaggerPetstore
MimeXmlCharsetutf8 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
MixedPropertiesAndAdditionalPropertiesClass 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassDateTimeSwaggerPetstore.Model, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassDateTimeLSwaggerPetstore.ModelLens, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassMapSwaggerPetstore.Model, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassMapLSwaggerPetstore.ModelLens, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassUuidSwaggerPetstore.Model, SwaggerPetstore
mixedPropertiesAndAdditionalPropertiesClassUuidLSwaggerPetstore.ModelLens, SwaggerPetstore
mkAdditionalPropertiesClassSwaggerPetstore.Model, SwaggerPetstore
mkAnimalSwaggerPetstore.Model, SwaggerPetstore
mkAnimalFarmSwaggerPetstore.Model, SwaggerPetstore
mkApiResponseSwaggerPetstore.Model, SwaggerPetstore
mkArrayOfArrayOfNumberOnlySwaggerPetstore.Model, SwaggerPetstore
mkArrayOfNumberOnlySwaggerPetstore.Model, SwaggerPetstore
mkArrayTestSwaggerPetstore.Model, SwaggerPetstore
mkCapitalizationSwaggerPetstore.Model, SwaggerPetstore
mkCatSwaggerPetstore.Model, SwaggerPetstore
mkCategorySwaggerPetstore.Model, SwaggerPetstore
mkClassModelSwaggerPetstore.Model, SwaggerPetstore
mkClientSwaggerPetstore.Model, SwaggerPetstore
mkDogSwaggerPetstore.Model, SwaggerPetstore
mkEnumArraysSwaggerPetstore.Model, SwaggerPetstore
mkEnumTestSwaggerPetstore.Model, SwaggerPetstore
mkFormatTestSwaggerPetstore.Model, SwaggerPetstore
mkHasOnlyReadOnlySwaggerPetstore.Model, SwaggerPetstore
mkMapTestSwaggerPetstore.Model, SwaggerPetstore
mkMixedPropertiesAndAdditionalPropertiesClassSwaggerPetstore.Model, SwaggerPetstore
mkModel200ResponseSwaggerPetstore.Model, SwaggerPetstore
mkModelListSwaggerPetstore.Model, SwaggerPetstore
mkModelReturnSwaggerPetstore.Model, SwaggerPetstore
mkNameSwaggerPetstore.Model, SwaggerPetstore
mkNumberOnlySwaggerPetstore.Model, SwaggerPetstore
mkOrderSwaggerPetstore.Model, SwaggerPetstore
mkOuterCompositeSwaggerPetstore.Model, SwaggerPetstore
mkPetSwaggerPetstore.Model, SwaggerPetstore
mkReadOnlyFirstSwaggerPetstore.Model, SwaggerPetstore
mkSpecialModelNameSwaggerPetstore.Model, SwaggerPetstore
mkTagSwaggerPetstore.Model, SwaggerPetstore
mkUserSwaggerPetstore.Model, SwaggerPetstore
Model200Response 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
model200ResponseClassSwaggerPetstore.Model, SwaggerPetstore
model200ResponseClassLSwaggerPetstore.ModelLens, SwaggerPetstore
model200ResponseNameSwaggerPetstore.Model, SwaggerPetstore
model200ResponseNameLSwaggerPetstore.ModelLens, SwaggerPetstore
ModelList 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
modelList123ListSwaggerPetstore.Model, SwaggerPetstore
modelList123ListLSwaggerPetstore.ModelLens, SwaggerPetstore
ModelReturn 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
modelReturnReturnSwaggerPetstore.Model, SwaggerPetstore
modelReturnReturnLSwaggerPetstore.ModelLens, SwaggerPetstore
modifyInitRequestSwaggerPetstore.Client, SwaggerPetstore
modifyInitRequestMSwaggerPetstore.Client, SwaggerPetstore
MultiParamArraySwaggerPetstore.Core, SwaggerPetstore
\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/doc-index-O.html b/samples/client/petstore/haskell-http-client/docs/doc-index-O.html index ad118f965bc..08faaae547c 100644 --- a/samples/client/petstore/haskell-http-client/docs/doc-index-O.html +++ b/samples/client/petstore/haskell-http-client/docs/doc-index-O.html @@ -1,4 +1,4 @@ swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client (Index - O)

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index - O

Order 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
orderCompleteSwaggerPetstore.Model, SwaggerPetstore
orderCompleteLSwaggerPetstore.ModelLens, SwaggerPetstore
OrderId 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
orderIdSwaggerPetstore.Model, SwaggerPetstore
orderIdLSwaggerPetstore.ModelLens, SwaggerPetstore
OrderIdText 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
orderPetIdSwaggerPetstore.Model, SwaggerPetstore
orderPetIdLSwaggerPetstore.ModelLens, SwaggerPetstore
orderQuantitySwaggerPetstore.Model, SwaggerPetstore
orderQuantityLSwaggerPetstore.ModelLens, SwaggerPetstore
orderShipDateSwaggerPetstore.Model, SwaggerPetstore
orderShipDateLSwaggerPetstore.ModelLens, SwaggerPetstore
orderStatusSwaggerPetstore.Model, SwaggerPetstore
orderStatusLSwaggerPetstore.ModelLens, SwaggerPetstore
OuterBoolean 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
OuterComposite 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
outerCompositeMyBooleanSwaggerPetstore.Model, SwaggerPetstore
outerCompositeMyBooleanLSwaggerPetstore.ModelLens, SwaggerPetstore
outerCompositeMyNumberSwaggerPetstore.Model, SwaggerPetstore
outerCompositeMyNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
outerCompositeMyStringSwaggerPetstore.Model, SwaggerPetstore
outerCompositeMyStringLSwaggerPetstore.ModelLens, SwaggerPetstore
OuterEnum 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
OuterNumber 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
OuterString 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
\ No newline at end of file +

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index - O

Order 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
orderCompleteSwaggerPetstore.Model, SwaggerPetstore
orderCompleteLSwaggerPetstore.ModelLens, SwaggerPetstore
OrderId 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
orderIdSwaggerPetstore.Model, SwaggerPetstore
orderIdLSwaggerPetstore.ModelLens, SwaggerPetstore
OrderIdText 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
orderPetIdSwaggerPetstore.Model, SwaggerPetstore
orderPetIdLSwaggerPetstore.ModelLens, SwaggerPetstore
orderQuantitySwaggerPetstore.Model, SwaggerPetstore
orderQuantityLSwaggerPetstore.ModelLens, SwaggerPetstore
orderShipDateSwaggerPetstore.Model, SwaggerPetstore
orderShipDateLSwaggerPetstore.ModelLens, SwaggerPetstore
orderStatusSwaggerPetstore.Model, SwaggerPetstore
orderStatusLSwaggerPetstore.ModelLens, SwaggerPetstore
OuterBoolean 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
OuterComposite 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
outerCompositeMyBooleanSwaggerPetstore.Model, SwaggerPetstore
outerCompositeMyBooleanLSwaggerPetstore.ModelLens, SwaggerPetstore
outerCompositeMyNumberSwaggerPetstore.Model, SwaggerPetstore
outerCompositeMyNumberLSwaggerPetstore.ModelLens, SwaggerPetstore
outerCompositeMyStringSwaggerPetstore.Model, SwaggerPetstore
outerCompositeMyStringLSwaggerPetstore.ModelLens, SwaggerPetstore
OuterEnumSwaggerPetstore.Model, SwaggerPetstore
OuterEnum'ApprovedSwaggerPetstore.Model, SwaggerPetstore
OuterEnum'DeliveredSwaggerPetstore.Model, SwaggerPetstore
OuterEnum'PlacedSwaggerPetstore.Model, SwaggerPetstore
OuterNumber 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
OuterString 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/doc-index-T.html b/samples/client/petstore/haskell-http-client/docs/doc-index-T.html index 4a11f437a62..e0e98a350ec 100644 --- a/samples/client/petstore/haskell-http-client/docs/doc-index-T.html +++ b/samples/client/petstore/haskell-http-client/docs/doc-index-T.html @@ -1,4 +1,4 @@ swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client (Index - T)

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index - T

TabSeparatedSwaggerPetstore.Core, SwaggerPetstore
Tag 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
tagIdSwaggerPetstore.Model, SwaggerPetstore
tagIdLSwaggerPetstore.ModelLens, SwaggerPetstore
tagNameSwaggerPetstore.Model, SwaggerPetstore
tagNameLSwaggerPetstore.ModelLens, SwaggerPetstore
Tags 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
TestClassnameSwaggerPetstore.API, SwaggerPetstore
testClassnameSwaggerPetstore.API, SwaggerPetstore
TestClientModelSwaggerPetstore.API, SwaggerPetstore
testClientModelSwaggerPetstore.API, SwaggerPetstore
TestEndpointParametersSwaggerPetstore.API, SwaggerPetstore
testEndpointParametersSwaggerPetstore.API, SwaggerPetstore
TestEnumParametersSwaggerPetstore.API, SwaggerPetstore
testEnumParametersSwaggerPetstore.API, SwaggerPetstore
TestJsonFormDataSwaggerPetstore.API, SwaggerPetstore
testJsonFormDataSwaggerPetstore.API, SwaggerPetstore
TestSpecialTagsSwaggerPetstore.API, SwaggerPetstore
testSpecialTagsSwaggerPetstore.API, SwaggerPetstore
toFormSwaggerPetstore.Core, SwaggerPetstore
toFormCollSwaggerPetstore.Core, SwaggerPetstore
toHeaderSwaggerPetstore.Core, SwaggerPetstore
toHeaderCollSwaggerPetstore.Core, SwaggerPetstore
toPathSwaggerPetstore.Core, SwaggerPetstore
toQuerySwaggerPetstore.Core, SwaggerPetstore
toQueryCollSwaggerPetstore.Core, SwaggerPetstore
\ No newline at end of file +

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index - T

TabSeparatedSwaggerPetstore.Core, SwaggerPetstore
Tag 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
tagIdSwaggerPetstore.Model, SwaggerPetstore
tagIdLSwaggerPetstore.ModelLens, SwaggerPetstore
tagNameSwaggerPetstore.Model, SwaggerPetstore
tagNameLSwaggerPetstore.ModelLens, SwaggerPetstore
Tags 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
TestClassnameSwaggerPetstore.API, SwaggerPetstore
testClassnameSwaggerPetstore.API, SwaggerPetstore
TestClientModelSwaggerPetstore.API, SwaggerPetstore
testClientModelSwaggerPetstore.API, SwaggerPetstore
TestEndpointParametersSwaggerPetstore.API, SwaggerPetstore
testEndpointParametersSwaggerPetstore.API, SwaggerPetstore
TestEnumParametersSwaggerPetstore.API, SwaggerPetstore
testEnumParametersSwaggerPetstore.API, SwaggerPetstore
TestInlineAdditionalPropertiesSwaggerPetstore.API, SwaggerPetstore
testInlineAdditionalPropertiesSwaggerPetstore.API, SwaggerPetstore
TestJsonFormDataSwaggerPetstore.API, SwaggerPetstore
testJsonFormDataSwaggerPetstore.API, SwaggerPetstore
TestSpecialTagsSwaggerPetstore.API, SwaggerPetstore
testSpecialTagsSwaggerPetstore.API, SwaggerPetstore
toE'ArrayEnumSwaggerPetstore.Model, SwaggerPetstore
toE'EnumFormStringSwaggerPetstore.Model, SwaggerPetstore
toE'EnumIntegerSwaggerPetstore.Model, SwaggerPetstore
toE'EnumNumberSwaggerPetstore.Model, SwaggerPetstore
toE'EnumQueryIntegerSwaggerPetstore.Model, SwaggerPetstore
toE'EnumStringSwaggerPetstore.Model, SwaggerPetstore
toE'InnerSwaggerPetstore.Model, SwaggerPetstore
toE'Inner2SwaggerPetstore.Model, SwaggerPetstore
toE'JustSymbolSwaggerPetstore.Model, SwaggerPetstore
toE'StatusSwaggerPetstore.Model, SwaggerPetstore
toE'Status2SwaggerPetstore.Model, SwaggerPetstore
toEnumClassSwaggerPetstore.Model, SwaggerPetstore
toFormSwaggerPetstore.Core, SwaggerPetstore
toFormCollSwaggerPetstore.Core, SwaggerPetstore
toHeaderSwaggerPetstore.Core, SwaggerPetstore
toHeaderCollSwaggerPetstore.Core, SwaggerPetstore
toOuterEnumSwaggerPetstore.Model, SwaggerPetstore
toPathSwaggerPetstore.Core, SwaggerPetstore
toQuerySwaggerPetstore.Core, SwaggerPetstore
toQueryCollSwaggerPetstore.Core, SwaggerPetstore
\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/doc-index-U.html b/samples/client/petstore/haskell-http-client/docs/doc-index-U.html index 9abedbd95b8..7a8dcedc46a 100644 --- a/samples/client/petstore/haskell-http-client/docs/doc-index-U.html +++ b/samples/client/petstore/haskell-http-client/docs/doc-index-U.html @@ -1,4 +1,4 @@ swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client (Index - U)

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index - U

unAdditionalMetadataSwaggerPetstore.API, SwaggerPetstore
unApiKeySwaggerPetstore.API, SwaggerPetstore
unBinarySwaggerPetstore.Core, SwaggerPetstore
unBodySwaggerPetstore.API, SwaggerPetstore
unByteSwaggerPetstore.API, SwaggerPetstore
unByteArraySwaggerPetstore.Core, SwaggerPetstore
unCallbackSwaggerPetstore.API, SwaggerPetstore
unDateSwaggerPetstore.Core, SwaggerPetstore
unDateTimeSwaggerPetstore.Core, SwaggerPetstore
unEnumFormStringSwaggerPetstore.API, SwaggerPetstore
unEnumFormStringArraySwaggerPetstore.API, SwaggerPetstore
unEnumHeaderStringSwaggerPetstore.API, SwaggerPetstore
unEnumHeaderStringArraySwaggerPetstore.API, SwaggerPetstore
unEnumQueryDoubleSwaggerPetstore.API, SwaggerPetstore
unEnumQueryIntegerSwaggerPetstore.API, SwaggerPetstore
unEnumQueryStringSwaggerPetstore.API, SwaggerPetstore
unEnumQueryStringArraySwaggerPetstore.API, SwaggerPetstore
unFileSwaggerPetstore.API, SwaggerPetstore
unInitRequestSwaggerPetstore.Client, SwaggerPetstore
unInt32SwaggerPetstore.API, SwaggerPetstore
unInt64SwaggerPetstore.API, SwaggerPetstore
unName2SwaggerPetstore.API, SwaggerPetstore
unNumberSwaggerPetstore.API, SwaggerPetstore
unOrderIdSwaggerPetstore.API, SwaggerPetstore
unOrderIdTextSwaggerPetstore.API, SwaggerPetstore
unOuterBooleanSwaggerPetstore.Model, SwaggerPetstore
unOuterNumberSwaggerPetstore.Model, SwaggerPetstore
unOuterStringSwaggerPetstore.Model, SwaggerPetstore
unParamSwaggerPetstore.API, SwaggerPetstore
unParam2SwaggerPetstore.API, SwaggerPetstore
unParamBinarySwaggerPetstore.API, SwaggerPetstore
unParamDateSwaggerPetstore.API, SwaggerPetstore
unParamDateTimeSwaggerPetstore.API, SwaggerPetstore
unParamDoubleSwaggerPetstore.API, SwaggerPetstore
unParamFloatSwaggerPetstore.API, SwaggerPetstore
unParamIntegerSwaggerPetstore.API, SwaggerPetstore
unParamStringSwaggerPetstore.API, SwaggerPetstore
unPasswordSwaggerPetstore.API, SwaggerPetstore
unPatternWithoutDelimiterSwaggerPetstore.API, SwaggerPetstore
unPetIdSwaggerPetstore.API, SwaggerPetstore
unStatusSwaggerPetstore.API, SwaggerPetstore
unStatusTextSwaggerPetstore.API, SwaggerPetstore
unTagsSwaggerPetstore.API, SwaggerPetstore
unUsernameSwaggerPetstore.API, SwaggerPetstore
UpdatePetSwaggerPetstore.API, SwaggerPetstore
updatePetSwaggerPetstore.API, SwaggerPetstore
UpdatePetWithFormSwaggerPetstore.API, SwaggerPetstore
updatePetWithFormSwaggerPetstore.API, SwaggerPetstore
UpdateUserSwaggerPetstore.API, SwaggerPetstore
updateUserSwaggerPetstore.API, SwaggerPetstore
UploadFileSwaggerPetstore.API, SwaggerPetstore
uploadFileSwaggerPetstore.API, SwaggerPetstore
User 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
userEmailSwaggerPetstore.Model, SwaggerPetstore
userEmailLSwaggerPetstore.ModelLens, SwaggerPetstore
userFirstNameSwaggerPetstore.Model, SwaggerPetstore
userFirstNameLSwaggerPetstore.ModelLens, SwaggerPetstore
userIdSwaggerPetstore.Model, SwaggerPetstore
userIdLSwaggerPetstore.ModelLens, SwaggerPetstore
userLastNameSwaggerPetstore.Model, SwaggerPetstore
userLastNameLSwaggerPetstore.ModelLens, SwaggerPetstore
Username 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
userPasswordSwaggerPetstore.Model, SwaggerPetstore
userPasswordLSwaggerPetstore.ModelLens, SwaggerPetstore
userPhoneSwaggerPetstore.Model, SwaggerPetstore
userPhoneLSwaggerPetstore.ModelLens, SwaggerPetstore
userUsernameSwaggerPetstore.Model, SwaggerPetstore
userUsernameLSwaggerPetstore.ModelLens, SwaggerPetstore
userUserStatusSwaggerPetstore.Model, SwaggerPetstore
userUserStatusLSwaggerPetstore.ModelLens, SwaggerPetstore
\ No newline at end of file +

swagger-petstore-0.1.0.0: Auto-generated swagger-petstore API Client

Index - U

unAcceptSwaggerPetstore.MimeTypes, SwaggerPetstore
unAdditionalMetadataSwaggerPetstore.API, SwaggerPetstore
unApiKeySwaggerPetstore.API, SwaggerPetstore
unBinarySwaggerPetstore.Core, SwaggerPetstore
unBodySwaggerPetstore.API, SwaggerPetstore
unByteSwaggerPetstore.API, SwaggerPetstore
unByteArraySwaggerPetstore.Core, SwaggerPetstore
unCallbackSwaggerPetstore.API, SwaggerPetstore
unContentTypeSwaggerPetstore.MimeTypes, SwaggerPetstore
unDateSwaggerPetstore.Core, SwaggerPetstore
unDateTimeSwaggerPetstore.Core, SwaggerPetstore
unEnumFormStringSwaggerPetstore.API, SwaggerPetstore
unEnumFormStringArraySwaggerPetstore.API, SwaggerPetstore
unEnumHeaderStringSwaggerPetstore.API, SwaggerPetstore
unEnumHeaderStringArraySwaggerPetstore.API, SwaggerPetstore
unEnumQueryDoubleSwaggerPetstore.API, SwaggerPetstore
unEnumQueryIntegerSwaggerPetstore.API, SwaggerPetstore
unEnumQueryStringSwaggerPetstore.API, SwaggerPetstore
unEnumQueryStringArraySwaggerPetstore.API, SwaggerPetstore
unFileSwaggerPetstore.API, SwaggerPetstore
unInitRequestSwaggerPetstore.Client, SwaggerPetstore
unInt32SwaggerPetstore.API, SwaggerPetstore
unInt64SwaggerPetstore.API, SwaggerPetstore
unName2SwaggerPetstore.API, SwaggerPetstore
unNumberSwaggerPetstore.API, SwaggerPetstore
unOrderIdSwaggerPetstore.API, SwaggerPetstore
unOrderIdTextSwaggerPetstore.API, SwaggerPetstore
unOuterBooleanSwaggerPetstore.Model, SwaggerPetstore
unOuterNumberSwaggerPetstore.Model, SwaggerPetstore
unOuterStringSwaggerPetstore.Model, SwaggerPetstore
unParamSwaggerPetstore.API, SwaggerPetstore
unParam2SwaggerPetstore.API, SwaggerPetstore
unParamBinarySwaggerPetstore.API, SwaggerPetstore
unParamDateSwaggerPetstore.API, SwaggerPetstore
unParamDateTimeSwaggerPetstore.API, SwaggerPetstore
unParamDoubleSwaggerPetstore.API, SwaggerPetstore
unParamFloatSwaggerPetstore.API, SwaggerPetstore
unParamIntegerSwaggerPetstore.API, SwaggerPetstore
unParamStringSwaggerPetstore.API, SwaggerPetstore
unPasswordSwaggerPetstore.API, SwaggerPetstore
unPatternWithoutDelimiterSwaggerPetstore.API, SwaggerPetstore
unPetIdSwaggerPetstore.API, SwaggerPetstore
unStatusSwaggerPetstore.API, SwaggerPetstore
unStatusTextSwaggerPetstore.API, SwaggerPetstore
unTagsSwaggerPetstore.API, SwaggerPetstore
unUsernameSwaggerPetstore.API, SwaggerPetstore
UpdatePetSwaggerPetstore.API, SwaggerPetstore
updatePetSwaggerPetstore.API, SwaggerPetstore
UpdatePetWithFormSwaggerPetstore.API, SwaggerPetstore
updatePetWithFormSwaggerPetstore.API, SwaggerPetstore
UpdateUserSwaggerPetstore.API, SwaggerPetstore
updateUserSwaggerPetstore.API, SwaggerPetstore
UploadFileSwaggerPetstore.API, SwaggerPetstore
uploadFileSwaggerPetstore.API, SwaggerPetstore
User 
1 (Type/Class)SwaggerPetstore.Model, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.Model, SwaggerPetstore
userEmailSwaggerPetstore.Model, SwaggerPetstore
userEmailLSwaggerPetstore.ModelLens, SwaggerPetstore
userFirstNameSwaggerPetstore.Model, SwaggerPetstore
userFirstNameLSwaggerPetstore.ModelLens, SwaggerPetstore
userIdSwaggerPetstore.Model, SwaggerPetstore
userIdLSwaggerPetstore.ModelLens, SwaggerPetstore
userLastNameSwaggerPetstore.Model, SwaggerPetstore
userLastNameLSwaggerPetstore.ModelLens, SwaggerPetstore
Username 
1 (Type/Class)SwaggerPetstore.API, SwaggerPetstore
2 (Data Constructor)SwaggerPetstore.API, SwaggerPetstore
userPasswordSwaggerPetstore.Model, SwaggerPetstore
userPasswordLSwaggerPetstore.ModelLens, SwaggerPetstore
userPhoneSwaggerPetstore.Model, SwaggerPetstore
userPhoneLSwaggerPetstore.ModelLens, SwaggerPetstore
userUsernameSwaggerPetstore.Model, SwaggerPetstore
userUsernameLSwaggerPetstore.ModelLens, SwaggerPetstore
userUserStatusSwaggerPetstore.Model, SwaggerPetstore
userUserStatusLSwaggerPetstore.ModelLens, SwaggerPetstore
\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/mini_SwaggerPetstore-API.html b/samples/client/petstore/haskell-http-client/docs/mini_SwaggerPetstore-API.html index dc389c7b979..9e01b1aa39b 100644 --- a/samples/client/petstore/haskell-http-client/docs/mini_SwaggerPetstore-API.html +++ b/samples/client/petstore/haskell-http-client/docs/mini_SwaggerPetstore-API.html @@ -1,4 +1,4 @@ SwaggerPetstore.API

SwaggerPetstore.API

Operations

AnotherFake

testSpecialTags

Fake

fakeOuterBooleanSerialize

fakeOuterCompositeSerialize

fakeOuterNumberSerialize

fakeOuterStringSerialize

testClientModel

testEndpointParameters

testEnumParameters

testJsonFormData

FakeClassnameTags123

testClassname

Pet

addPet

data AddPet

deletePet

findPetsByStatus

findPetsByTags

getPetById

updatePet

updatePetWithForm

uploadFile

Store

deleteOrder

getInventory

getOrderById

placeOrder

User

createUser

createUsersWithArrayInput

createUsersWithListInput

deleteUser

getUserByName

loginUser

logoutUser

updateUser

Parameter newtypes

data ApiKey

data Body

data Byte

data File

data Int32

data Int64

data Name2

data Number

data OrderId

data Param

data Param2

data PetId

data Status

data Tags

Auth Methods

AuthApiKeyApiKey

AuthApiKeyApiKeyQuery

AuthBasicHttpBasicTest

AuthOAuthPetstoreAuth

Custom Mime Types

MimeJsonCharsetutf8

MimeXmlCharsetutf8

\ No newline at end of file +

SwaggerPetstore.API

Operations

AnotherFake

testSpecialTags

Fake

fakeOuterBooleanSerialize

fakeOuterCompositeSerialize

fakeOuterNumberSerialize

fakeOuterStringSerialize

testClientModel

testEndpointParameters

testEnumParameters

testInlineAdditionalProperties

testJsonFormData

FakeClassnameTags123

testClassname

Pet

addPet

data AddPet

deletePet

findPetsByStatus

findPetsByTags

getPetById

updatePet

updatePetWithForm

uploadFile

Store

deleteOrder

getInventory

getOrderById

placeOrder

User

createUser

createUsersWithArrayInput

createUsersWithListInput

deleteUser

getUserByName

loginUser

logoutUser

updateUser

Parameter newtypes

data ApiKey

data Body

data Byte

data File

data Int32

data Int64

data Name2

data Number

data OrderId

data Param

data Param2

data PetId

data Status

data Tags

Auth Methods

AuthApiKeyApiKey

AuthApiKeyApiKeyQuery

AuthBasicHttpBasicTest

AuthOAuthPetstoreAuth

Custom Mime Types

MimeJsonCharsetutf8

MimeXmlCharsetutf8

\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/mini_SwaggerPetstore-Core.html b/samples/client/petstore/haskell-http-client/docs/mini_SwaggerPetstore-Core.html index 27848471619..4f487e572e9 100644 --- a/samples/client/petstore/haskell-http-client/docs/mini_SwaggerPetstore-Core.html +++ b/samples/client/petstore/haskell-http-client/docs/mini_SwaggerPetstore-Core.html @@ -1,4 +1,4 @@ SwaggerPetstore.Core

SwaggerPetstore.Core

\ No newline at end of file +

SwaggerPetstore.Core

\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/mini_SwaggerPetstore-MimeTypes.html b/samples/client/petstore/haskell-http-client/docs/mini_SwaggerPetstore-MimeTypes.html index 023970b51a8..45f1a47f1b0 100644 --- a/samples/client/petstore/haskell-http-client/docs/mini_SwaggerPetstore-MimeTypes.html +++ b/samples/client/petstore/haskell-http-client/docs/mini_SwaggerPetstore-MimeTypes.html @@ -1,4 +1,4 @@ SwaggerPetstore.MimeTypes

SwaggerPetstore.MimeTypes

Consumes Class

class Consumes req mtype

Produces Class

class Produces req mtype

Default Mime Types

data MimeXML

data MimeAny

MimeType Class

class MimeType mtype

MimeRender Class

class MimeRender mtype x

MimeUnrender Class

class MimeUnrender mtype o

\ No newline at end of file +

SwaggerPetstore.MimeTypes

ContentType MimeType

Accept MimeType

data Accept a

Consumes Class

class Consumes req mtype

Produces Class

class Produces req mtype

Default Mime Types

data MimeXML

data MimeAny

MimeType Class

class MimeType mtype

MimeRender Class

class MimeRender mtype x

MimeUnrender Class

class MimeUnrender mtype o

\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/mini_SwaggerPetstore-Model.html b/samples/client/petstore/haskell-http-client/docs/mini_SwaggerPetstore-Model.html index 99d6cf89bf1..529a1d4113a 100644 --- a/samples/client/petstore/haskell-http-client/docs/mini_SwaggerPetstore-Model.html +++ b/samples/client/petstore/haskell-http-client/docs/mini_SwaggerPetstore-Model.html @@ -1,4 +1,4 @@ SwaggerPetstore.Model

SwaggerPetstore.Model

Models

AdditionalPropertiesClass

Animal

data Animal

AnimalFarm

ApiResponse

ArrayOfArrayOfNumberOnly

ArrayOfNumberOnly

ArrayTest

Capitalization

Category

ClassModel

Client

data Client

EnumArrays

EnumClass

EnumTest

FormatTest

HasOnlyReadOnly

MapTest

data MapTest

MixedPropertiesAndAdditionalPropertiesClass

Model200Response

ModelList

ModelReturn

Name

data Name

NumberOnly

Order

data Order

OuterBoolean

OuterComposite

OuterEnum

OuterNumber

OuterString

Pet

data Pet

ReadOnlyFirst

SpecialModelName

Tag

data Tag

User

data User

Cat

data Cat

Dog

data Dog

\ No newline at end of file +

SwaggerPetstore.Model

Models

AdditionalPropertiesClass

Animal

data Animal

AnimalFarm

ApiResponse

ArrayOfArrayOfNumberOnly

ArrayOfNumberOnly

ArrayTest

Capitalization

Category

ClassModel

Client

data Client

EnumArrays

EnumTest

FormatTest

HasOnlyReadOnly

MapTest

data MapTest

MixedPropertiesAndAdditionalPropertiesClass

Model200Response

ModelList

ModelReturn

Name

data Name

NumberOnly

Order

data Order

OuterBoolean

OuterComposite

OuterNumber

OuterString

Pet

data Pet

ReadOnlyFirst

SpecialModelName

Tag

data Tag

User

data User

Cat

data Cat

Dog

data Dog

Enums

E'ArrayEnum

E'EnumFormString

E'EnumInteger

E'EnumNumber

E'EnumQueryInteger

E'EnumString

E'Inner

data E'Inner

E'Inner2

E'JustSymbol

E'Status

E'Status2

EnumClass

OuterEnum

\ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/src/Paths_swagger_petstore.html b/samples/client/petstore/haskell-http-client/docs/src/Paths_swagger_petstore.html index 3bba33b677f..e80b55cfc24 100644 --- a/samples/client/petstore/haskell-http-client/docs/src/Paths_swagger_petstore.html +++ b/samples/client/petstore/haskell-http-client/docs/src/Paths_swagger_petstore.html @@ -15,7 +15,7 @@ #if defined(VERSION_base) #if MIN_VERSION_base(4,0,0) -catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a +catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a #else catchIO :: IO a -> (Exception.Exception -> IO a) -> IO a #endif @@ -29,12 +29,12 @@ version = Version [0,1,0,0] [] bindir, libdir, dynlibdir, datadir, libexecdir, sysconfdir :: FilePath -bindir = "/home/jon/fs/git/swagger-codegen/samples/client/petstore/haskell-http-client/.stack-work/install/x86_64-linux-nopie/lts-9.0/8.0.2/bin" -libdir = "/home/jon/fs/git/swagger-codegen/samples/client/petstore/haskell-http-client/.stack-work/install/x86_64-linux-nopie/lts-9.0/8.0.2/lib/x86_64-linux-ghc-8.0.2/swagger-petstore-0.1.0.0-6vvnt0nNbFQ21xc4iZiS7J" -dynlibdir = "/home/jon/fs/git/swagger-codegen/samples/client/petstore/haskell-http-client/.stack-work/install/x86_64-linux-nopie/lts-9.0/8.0.2/lib/x86_64-linux-ghc-8.0.2" -datadir = "/home/jon/fs/git/swagger-codegen/samples/client/petstore/haskell-http-client/.stack-work/install/x86_64-linux-nopie/lts-9.0/8.0.2/share/x86_64-linux-ghc-8.0.2/swagger-petstore-0.1.0.0" -libexecdir = "/home/jon/fs/git/swagger-codegen/samples/client/petstore/haskell-http-client/.stack-work/install/x86_64-linux-nopie/lts-9.0/8.0.2/libexec" -sysconfdir = "/home/jon/fs/git/swagger-codegen/samples/client/petstore/haskell-http-client/.stack-work/install/x86_64-linux-nopie/lts-9.0/8.0.2/etc" +bindir = "/home/jon/fs/git/swagger-codegen/samples/client/petstore/haskell-http-client/.stack-work/install/x86_64-linux-nopie/lts-9.10/8.0.2/bin" +libdir = "/home/jon/fs/git/swagger-codegen/samples/client/petstore/haskell-http-client/.stack-work/install/x86_64-linux-nopie/lts-9.10/8.0.2/lib/x86_64-linux-ghc-8.0.2/swagger-petstore-0.1.0.0-G0PVVG38xKf22jM35QKNTa" +dynlibdir = "/home/jon/fs/git/swagger-codegen/samples/client/petstore/haskell-http-client/.stack-work/install/x86_64-linux-nopie/lts-9.10/8.0.2/lib/x86_64-linux-ghc-8.0.2" +datadir = "/home/jon/fs/git/swagger-codegen/samples/client/petstore/haskell-http-client/.stack-work/install/x86_64-linux-nopie/lts-9.10/8.0.2/share/x86_64-linux-ghc-8.0.2/swagger-petstore-0.1.0.0" +libexecdir = "/home/jon/fs/git/swagger-codegen/samples/client/petstore/haskell-http-client/.stack-work/install/x86_64-linux-nopie/lts-9.10/8.0.2/libexec" +sysconfdir = "/home/jon/fs/git/swagger-codegen/samples/client/petstore/haskell-http-client/.stack-work/install/x86_64-linux-nopie/lts-9.10/8.0.2/etc" getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath getBinDir = catchIO (getEnv "swagger_petstore_bindir") (\_ -> return bindir) @@ -45,7 +45,7 @@ getSysconfDir = catchIO (getEnv "swagger_petstore_sysconfdir") (\_ -> return sysconfdir) getDataFileName :: FilePath -> IO FilePath -getDataFileName name = do - dir <- getDataDir - return (dir ++ "/" ++ name) +getDataFileName name = do + dir <- getDataDir + return (dir ++ "/" ++ name) \ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.API.html b/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.API.html index 1b60e4447ab..12ff4c824cb 100644 --- a/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.API.html +++ b/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.API.html @@ -79,1029 +79,1084 @@ Module : SwaggerPetstore.API -- To test special tags -- testSpecialTags - :: (Consumes TestSpecialTags contentType, MimeRender contentType Client) - => contentType -- ^ request content-type ('MimeType') - -> Client -- ^ "body" - client model - -> SwaggerPetstoreRequest TestSpecialTags contentType Client -testSpecialTags _ body = - _mkRequest "PATCH" ["/another-fake/dummy"] - `setBodyParam` body - -data TestSpecialTags - --- | /Body Param/ "body" - client model -instance HasBodyParam TestSpecialTags Client - --- | @application/json@ -instance Consumes TestSpecialTags MimeJSON - --- | @application/json@ -instance Produces TestSpecialTags MimeJSON - + :: (Consumes TestSpecialTags contentType, MimeRender contentType Client) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> Client -- ^ "body" - client model + -> SwaggerPetstoreRequest TestSpecialTags contentType Client accept +testSpecialTags _ _ body = + _mkRequest "PATCH" ["/another-fake/dummy"] + `setBodyParam` body + +data TestSpecialTags + +-- | /Body Param/ "body" - client model +instance HasBodyParam TestSpecialTags Client + +-- | @application/json@ +instance Consumes TestSpecialTags MimeJSON + +-- | @application/json@ +instance Produces TestSpecialTags MimeJSON --- ** Fake - --- *** fakeOuterBooleanSerialize - --- | @POST \/fake\/outer\/boolean@ --- --- Test serialization of outer boolean types --- -fakeOuterBooleanSerialize - :: (Consumes FakeOuterBooleanSerialize contentType) - => contentType -- ^ request content-type ('MimeType') - -> SwaggerPetstoreRequest FakeOuterBooleanSerialize contentType OuterBoolean -fakeOuterBooleanSerialize _ = - _mkRequest "POST" ["/fake/outer/boolean"] - -data FakeOuterBooleanSerialize + +-- ** Fake + +-- *** fakeOuterBooleanSerialize + +-- | @POST \/fake\/outer\/boolean@ +-- +-- Test serialization of outer boolean types +-- +fakeOuterBooleanSerialize + :: (Consumes FakeOuterBooleanSerialize contentType) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> SwaggerPetstoreRequest FakeOuterBooleanSerialize contentType OuterBoolean accept +fakeOuterBooleanSerialize _ _ = + _mkRequest "POST" ["/fake/outer/boolean"] --- | /Body Param/ "body" - Input boolean as post body -instance HasBodyParam FakeOuterBooleanSerialize OuterBoolean - --- *** fakeOuterCompositeSerialize +data FakeOuterBooleanSerialize + +-- | /Body Param/ "body" - Input boolean as post body +instance HasBodyParam FakeOuterBooleanSerialize OuterBoolean --- | @POST \/fake\/outer\/composite@ --- --- Test serialization of object with outer number type +-- *** fakeOuterCompositeSerialize + +-- | @POST \/fake\/outer\/composite@ -- -fakeOuterCompositeSerialize - :: (Consumes FakeOuterCompositeSerialize contentType) - => contentType -- ^ request content-type ('MimeType') - -> SwaggerPetstoreRequest FakeOuterCompositeSerialize contentType OuterComposite -fakeOuterCompositeSerialize _ = - _mkRequest "POST" ["/fake/outer/composite"] - -data FakeOuterCompositeSerialize - --- | /Body Param/ "body" - Input composite as post body -instance HasBodyParam FakeOuterCompositeSerialize OuterComposite +-- Test serialization of object with outer number type +-- +fakeOuterCompositeSerialize + :: (Consumes FakeOuterCompositeSerialize contentType) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> SwaggerPetstoreRequest FakeOuterCompositeSerialize contentType OuterComposite accept +fakeOuterCompositeSerialize _ _ = + _mkRequest "POST" ["/fake/outer/composite"] + +data FakeOuterCompositeSerialize --- *** fakeOuterNumberSerialize - --- | @POST \/fake\/outer\/number@ --- --- Test serialization of outer number types --- -fakeOuterNumberSerialize - :: (Consumes FakeOuterNumberSerialize contentType) - => contentType -- ^ request content-type ('MimeType') - -> SwaggerPetstoreRequest FakeOuterNumberSerialize contentType OuterNumber -fakeOuterNumberSerialize _ = - _mkRequest "POST" ["/fake/outer/number"] - -data FakeOuterNumberSerialize - --- | /Body Param/ "body" - Input number as post body -instance HasBodyParam FakeOuterNumberSerialize OuterNumber - --- *** fakeOuterStringSerialize - --- | @POST \/fake\/outer\/string@ --- --- Test serialization of outer string types --- -fakeOuterStringSerialize - :: (Consumes FakeOuterStringSerialize contentType) - => contentType -- ^ request content-type ('MimeType') - -> SwaggerPetstoreRequest FakeOuterStringSerialize contentType OuterString -fakeOuterStringSerialize _ = - _mkRequest "POST" ["/fake/outer/string"] - -data FakeOuterStringSerialize - --- | /Body Param/ "body" - Input string as post body -instance HasBodyParam FakeOuterStringSerialize OuterString +-- | /Body Param/ "body" - Input composite as post body +instance HasBodyParam FakeOuterCompositeSerialize OuterComposite + +-- *** fakeOuterNumberSerialize + +-- | @POST \/fake\/outer\/number@ +-- +-- Test serialization of outer number types +-- +fakeOuterNumberSerialize + :: (Consumes FakeOuterNumberSerialize contentType) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> SwaggerPetstoreRequest FakeOuterNumberSerialize contentType OuterNumber accept +fakeOuterNumberSerialize _ _ = + _mkRequest "POST" ["/fake/outer/number"] + +data FakeOuterNumberSerialize + +-- | /Body Param/ "body" - Input number as post body +instance HasBodyParam FakeOuterNumberSerialize OuterNumber + +-- *** fakeOuterStringSerialize + +-- | @POST \/fake\/outer\/string@ +-- +-- Test serialization of outer string types +-- +fakeOuterStringSerialize + :: (Consumes FakeOuterStringSerialize contentType) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> SwaggerPetstoreRequest FakeOuterStringSerialize contentType OuterString accept +fakeOuterStringSerialize _ _ = + _mkRequest "POST" ["/fake/outer/string"] --- *** testClientModel +data FakeOuterStringSerialize --- | @PATCH \/fake@ --- --- To test \"client\" model --- --- To test \"client\" model --- -testClientModel - :: (Consumes TestClientModel contentType, MimeRender contentType Client) - => contentType -- ^ request content-type ('MimeType') - -> Client -- ^ "body" - client model - -> SwaggerPetstoreRequest TestClientModel contentType Client -testClientModel _ body = - _mkRequest "PATCH" ["/fake"] - `setBodyParam` body - -data TestClientModel - --- | /Body Param/ "body" - client model -instance HasBodyParam TestClientModel Client - --- | @application/json@ -instance Consumes TestClientModel MimeJSON +-- | /Body Param/ "body" - Input string as post body +instance HasBodyParam FakeOuterStringSerialize OuterString + +-- *** testClientModel + +-- | @PATCH \/fake@ +-- +-- To test \"client\" model +-- +-- To test \"client\" model +-- +testClientModel + :: (Consumes TestClientModel contentType, MimeRender contentType Client) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> Client -- ^ "body" - client model + -> SwaggerPetstoreRequest TestClientModel contentType Client accept +testClientModel _ _ body = + _mkRequest "PATCH" ["/fake"] + `setBodyParam` body + +data TestClientModel --- | @application/json@ -instance Produces TestClientModel MimeJSON +-- | /Body Param/ "body" - client model +instance HasBodyParam TestClientModel Client - --- *** testEndpointParameters +-- | @application/json@ +instance Consumes TestClientModel MimeJSON --- | @POST \/fake@ --- --- Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 --- --- Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 --- --- AuthMethod: 'AuthBasicHttpBasicTest' +-- | @application/json@ +instance Produces TestClientModel MimeJSON + + +-- *** testEndpointParameters + +-- | @POST \/fake@ -- --- Note: Has 'Produces' instances, but no response schema +-- Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -- -testEndpointParameters - :: (Consumes TestEndpointParameters contentType) - => contentType -- ^ request content-type ('MimeType') - -> Number -- ^ "number" - None - -> ParamDouble -- ^ "double" - None - -> PatternWithoutDelimiter -- ^ "patternWithoutDelimiter" - None - -> Byte -- ^ "byte" - None - -> SwaggerPetstoreRequest TestEndpointParameters contentType res -testEndpointParameters _ (Number number) (ParamDouble double) (PatternWithoutDelimiter patternWithoutDelimiter) (Byte byte) = - _mkRequest "POST" ["/fake"] - `_hasAuthType` (P.Proxy :: P.Proxy AuthBasicHttpBasicTest) - `addForm` toForm ("number", number) - `addForm` toForm ("double", double) - `addForm` toForm ("pattern_without_delimiter", patternWithoutDelimiter) - `addForm` toForm ("byte", byte) - -data TestEndpointParameters - --- | /Optional Param/ "integer" - None -instance HasOptionalParam TestEndpointParameters ParamInteger where - applyOptionalParam req (ParamInteger xs) = - req `addForm` toForm ("integer", xs) +-- Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +-- +-- AuthMethod: 'AuthBasicHttpBasicTest' +-- +-- Note: Has 'Produces' instances, but no response schema +-- +testEndpointParameters + :: (Consumes TestEndpointParameters contentType) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> Number -- ^ "number" - None + -> ParamDouble -- ^ "double" - None + -> PatternWithoutDelimiter -- ^ "patternWithoutDelimiter" - None + -> Byte -- ^ "byte" - None + -> SwaggerPetstoreRequest TestEndpointParameters contentType res accept +testEndpointParameters _ _ (Number number) (ParamDouble double) (PatternWithoutDelimiter patternWithoutDelimiter) (Byte byte) = + _mkRequest "POST" ["/fake"] + `_hasAuthType` (P.Proxy :: P.Proxy AuthBasicHttpBasicTest) + `addForm` toForm ("number", number) + `addForm` toForm ("double", double) + `addForm` toForm ("pattern_without_delimiter", patternWithoutDelimiter) + `addForm` toForm ("byte", byte) --- | /Optional Param/ "int32" - None -instance HasOptionalParam TestEndpointParameters Int32 where - applyOptionalParam req (Int32 xs) = - req `addForm` toForm ("int32", xs) - --- | /Optional Param/ "int64" - None -instance HasOptionalParam TestEndpointParameters Int64 where - applyOptionalParam req (Int64 xs) = - req `addForm` toForm ("int64", xs) - --- | /Optional Param/ "float" - None -instance HasOptionalParam TestEndpointParameters ParamFloat where - applyOptionalParam req (ParamFloat xs) = - req `addForm` toForm ("float", xs) - --- | /Optional Param/ "string" - None -instance HasOptionalParam TestEndpointParameters ParamString where - applyOptionalParam req (ParamString xs) = - req `addForm` toForm ("string", xs) - --- | /Optional Param/ "binary" - None -instance HasOptionalParam TestEndpointParameters ParamBinary where - applyOptionalParam req (ParamBinary xs) = - req `addForm` toForm ("binary", xs) - --- | /Optional Param/ "date" - None -instance HasOptionalParam TestEndpointParameters ParamDate where - applyOptionalParam req (ParamDate xs) = - req `addForm` toForm ("date", xs) - --- | /Optional Param/ "dateTime" - None -instance HasOptionalParam TestEndpointParameters ParamDateTime where - applyOptionalParam req (ParamDateTime xs) = - req `addForm` toForm ("dateTime", xs) - --- | /Optional Param/ "password" - None -instance HasOptionalParam TestEndpointParameters Password where - applyOptionalParam req (Password xs) = - req `addForm` toForm ("password", xs) - --- | /Optional Param/ "callback" - None -instance HasOptionalParam TestEndpointParameters Callback where - applyOptionalParam req (Callback xs) = - req `addForm` toForm ("callback", xs) - --- | @application/xml; charset=utf-8@ -instance Consumes TestEndpointParameters MimeXmlCharsetutf8 --- | @application/json; charset=utf-8@ -instance Consumes TestEndpointParameters MimeJsonCharsetutf8 - --- | @application/xml; charset=utf-8@ -instance Produces TestEndpointParameters MimeXmlCharsetutf8 --- | @application/json; charset=utf-8@ -instance Produces TestEndpointParameters MimeJsonCharsetutf8 - - --- *** testEnumParameters - --- | @GET \/fake@ --- --- To test enum parameters --- --- To test enum parameters --- --- Note: Has 'Produces' instances, but no response schema --- -testEnumParameters - :: (Consumes TestEnumParameters contentType) - => contentType -- ^ request content-type ('MimeType') - -> SwaggerPetstoreRequest TestEnumParameters contentType res -testEnumParameters _ = - _mkRequest "GET" ["/fake"] - -data TestEnumParameters - --- | /Optional Param/ "enum_form_string_array" - Form parameter enum test (string array) -instance HasOptionalParam TestEnumParameters EnumFormStringArray where - applyOptionalParam req (EnumFormStringArray xs) = - req `addForm` toFormColl CommaSeparated ("enum_form_string_array", xs) - --- | /Optional Param/ "enum_form_string" - Form parameter enum test (string) -instance HasOptionalParam TestEnumParameters EnumFormString where - applyOptionalParam req (EnumFormString xs) = - req `addForm` toForm ("enum_form_string", xs) - --- | /Optional Param/ "enum_header_string_array" - Header parameter enum test (string array) -instance HasOptionalParam TestEnumParameters EnumHeaderStringArray where - applyOptionalParam req (EnumHeaderStringArray xs) = - req `setHeader` toHeaderColl CommaSeparated ("enum_header_string_array", xs) - --- | /Optional Param/ "enum_header_string" - Header parameter enum test (string) -instance HasOptionalParam TestEnumParameters EnumHeaderString where - applyOptionalParam req (EnumHeaderString xs) = - req `setHeader` toHeader ("enum_header_string", xs) - --- | /Optional Param/ "enum_query_string_array" - Query parameter enum test (string array) -instance HasOptionalParam TestEnumParameters EnumQueryStringArray where - applyOptionalParam req (EnumQueryStringArray xs) = - req `setQuery` toQueryColl CommaSeparated ("enum_query_string_array", Just xs) - --- | /Optional Param/ "enum_query_string" - Query parameter enum test (string) -instance HasOptionalParam TestEnumParameters EnumQueryString where - applyOptionalParam req (EnumQueryString xs) = - req `setQuery` toQuery ("enum_query_string", Just xs) - --- | /Optional Param/ "enum_query_integer" - Query parameter enum test (double) -instance HasOptionalParam TestEnumParameters EnumQueryInteger where - applyOptionalParam req (EnumQueryInteger xs) = - req `setQuery` toQuery ("enum_query_integer", Just xs) - --- | /Optional Param/ "enum_query_double" - Query parameter enum test (double) -instance HasOptionalParam TestEnumParameters EnumQueryDouble where - applyOptionalParam req (EnumQueryDouble xs) = - req `addForm` toForm ("enum_query_double", xs) - --- | @*/*@ -instance Consumes TestEnumParameters MimeAny +data TestEndpointParameters + +-- | /Optional Param/ "integer" - None +instance HasOptionalParam TestEndpointParameters ParamInteger where + applyOptionalParam req (ParamInteger xs) = + req `addForm` toForm ("integer", xs) + +-- | /Optional Param/ "int32" - None +instance HasOptionalParam TestEndpointParameters Int32 where + applyOptionalParam req (Int32 xs) = + req `addForm` toForm ("int32", xs) + +-- | /Optional Param/ "int64" - None +instance HasOptionalParam TestEndpointParameters Int64 where + applyOptionalParam req (Int64 xs) = + req `addForm` toForm ("int64", xs) + +-- | /Optional Param/ "float" - None +instance HasOptionalParam TestEndpointParameters ParamFloat where + applyOptionalParam req (ParamFloat xs) = + req `addForm` toForm ("float", xs) + +-- | /Optional Param/ "string" - None +instance HasOptionalParam TestEndpointParameters ParamString where + applyOptionalParam req (ParamString xs) = + req `addForm` toForm ("string", xs) + +-- | /Optional Param/ "binary" - None +instance HasOptionalParam TestEndpointParameters ParamBinary where + applyOptionalParam req (ParamBinary xs) = + req `addForm` toForm ("binary", xs) + +-- | /Optional Param/ "date" - None +instance HasOptionalParam TestEndpointParameters ParamDate where + applyOptionalParam req (ParamDate xs) = + req `addForm` toForm ("date", xs) + +-- | /Optional Param/ "dateTime" - None +instance HasOptionalParam TestEndpointParameters ParamDateTime where + applyOptionalParam req (ParamDateTime xs) = + req `addForm` toForm ("dateTime", xs) + +-- | /Optional Param/ "password" - None +instance HasOptionalParam TestEndpointParameters Password where + applyOptionalParam req (Password xs) = + req `addForm` toForm ("password", xs) + +-- | /Optional Param/ "callback" - None +instance HasOptionalParam TestEndpointParameters Callback where + applyOptionalParam req (Callback xs) = + req `addForm` toForm ("callback", xs) + +-- | @application/xml; charset=utf-8@ +instance Consumes TestEndpointParameters MimeXmlCharsetutf8 +-- | @application/json; charset=utf-8@ +instance Consumes TestEndpointParameters MimeJsonCharsetutf8 + +-- | @application/xml; charset=utf-8@ +instance Produces TestEndpointParameters MimeXmlCharsetutf8 +-- | @application/json; charset=utf-8@ +instance Produces TestEndpointParameters MimeJsonCharsetutf8 + + +-- *** testEnumParameters + +-- | @GET \/fake@ +-- +-- To test enum parameters +-- +-- To test enum parameters +-- +-- Note: Has 'Produces' instances, but no response schema +-- +testEnumParameters + :: (Consumes TestEnumParameters contentType) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> SwaggerPetstoreRequest TestEnumParameters contentType res accept +testEnumParameters _ _ = + _mkRequest "GET" ["/fake"] + +data TestEnumParameters + +-- | /Optional Param/ "enum_form_string_array" - Form parameter enum test (string array) +instance HasOptionalParam TestEnumParameters EnumFormStringArray where + applyOptionalParam req (EnumFormStringArray xs) = + req `addForm` toFormColl CommaSeparated ("enum_form_string_array", xs) + +-- | /Optional Param/ "enum_form_string" - Form parameter enum test (string) +instance HasOptionalParam TestEnumParameters EnumFormString where + applyOptionalParam req (EnumFormString xs) = + req `addForm` toForm ("enum_form_string", xs) + +-- | /Optional Param/ "enum_header_string_array" - Header parameter enum test (string array) +instance HasOptionalParam TestEnumParameters EnumHeaderStringArray where + applyOptionalParam req (EnumHeaderStringArray xs) = + req `setHeader` toHeaderColl CommaSeparated ("enum_header_string_array", xs) + +-- | /Optional Param/ "enum_header_string" - Header parameter enum test (string) +instance HasOptionalParam TestEnumParameters EnumHeaderString where + applyOptionalParam req (EnumHeaderString xs) = + req `setHeader` toHeader ("enum_header_string", xs) + +-- | /Optional Param/ "enum_query_string_array" - Query parameter enum test (string array) +instance HasOptionalParam TestEnumParameters EnumQueryStringArray where + applyOptionalParam req (EnumQueryStringArray xs) = + req `setQuery` toQueryColl CommaSeparated ("enum_query_string_array", Just xs) + +-- | /Optional Param/ "enum_query_string" - Query parameter enum test (string) +instance HasOptionalParam TestEnumParameters EnumQueryString where + applyOptionalParam req (EnumQueryString xs) = + req `setQuery` toQuery ("enum_query_string", Just xs) + +-- | /Optional Param/ "enum_query_integer" - Query parameter enum test (double) +instance HasOptionalParam TestEnumParameters EnumQueryInteger where + applyOptionalParam req (EnumQueryInteger xs) = + req `setQuery` toQuery ("enum_query_integer", Just xs) --- | @*/*@ -instance Produces TestEnumParameters MimeAny - - --- *** testJsonFormData - --- | @GET \/fake\/jsonFormData@ --- --- test json serialization of form data --- --- --- -testJsonFormData - :: (Consumes TestJsonFormData contentType) - => contentType -- ^ request content-type ('MimeType') - -> Param -- ^ "param" - field1 - -> Param2 -- ^ "param2" - field2 - -> SwaggerPetstoreRequest TestJsonFormData contentType NoContent -testJsonFormData _ (Param param) (Param2 param2) = - _mkRequest "GET" ["/fake/jsonFormData"] - `addForm` toForm ("param", param) - `addForm` toForm ("param2", param2) - -data TestJsonFormData - --- | @application/json@ -instance Consumes TestJsonFormData MimeJSON - +-- | /Optional Param/ "enum_query_double" - Query parameter enum test (double) +instance HasOptionalParam TestEnumParameters EnumQueryDouble where + applyOptionalParam req (EnumQueryDouble xs) = + req `addForm` toForm ("enum_query_double", xs) + +-- | @*/*@ +instance Consumes TestEnumParameters MimeAny + +-- | @*/*@ +instance Produces TestEnumParameters MimeAny + + +-- *** testInlineAdditionalProperties + +-- | @POST \/fake\/inline-additionalProperties@ +-- +-- test inline additionalProperties +-- +-- +-- +testInlineAdditionalProperties + :: (Consumes TestInlineAdditionalProperties contentType, MimeRender contentType A.Value) + => ContentType contentType -- ^ request content-type ('MimeType') + -> A.Value -- ^ "param" - request body + -> SwaggerPetstoreRequest TestInlineAdditionalProperties contentType NoContent MimeNoContent +testInlineAdditionalProperties _ param = + _mkRequest "POST" ["/fake/inline-additionalProperties"] + `setBodyParam` param --- ** FakeClassnameTags123 +data TestInlineAdditionalProperties --- *** testClassname - --- | @PATCH \/fake_classname_test@ --- --- To test class name in snake case --- --- AuthMethod: 'AuthApiKeyApiKeyQuery' --- -testClassname - :: (Consumes TestClassname contentType, MimeRender contentType Client) - => contentType -- ^ request content-type ('MimeType') - -> Client -- ^ "body" - client model - -> SwaggerPetstoreRequest TestClassname contentType Client -testClassname _ body = - _mkRequest "PATCH" ["/fake_classname_test"] - `_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyApiKeyQuery) - `setBodyParam` body - -data TestClassname - --- | /Body Param/ "body" - client model -instance HasBodyParam TestClassname Client - --- | @application/json@ -instance Consumes TestClassname MimeJSON +-- | /Body Param/ "param" - request body +instance HasBodyParam TestInlineAdditionalProperties A.Value + +-- | @application/json@ +instance Consumes TestInlineAdditionalProperties MimeJSON + + +-- *** testJsonFormData + +-- | @GET \/fake\/jsonFormData@ +-- +-- test json serialization of form data +-- +-- +-- +testJsonFormData + :: (Consumes TestJsonFormData contentType) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Param -- ^ "param" - field1 + -> Param2 -- ^ "param2" - field2 + -> SwaggerPetstoreRequest TestJsonFormData contentType NoContent MimeNoContent +testJsonFormData _ (Param param) (Param2 param2) = + _mkRequest "GET" ["/fake/jsonFormData"] + `addForm` toForm ("param", param) + `addForm` toForm ("param2", param2) --- | @application/json@ -instance Produces TestClassname MimeJSON - - --- ** Pet +data TestJsonFormData + +-- | @application/json@ +instance Consumes TestJsonFormData MimeJSON + --- *** addPet +-- ** FakeClassnameTags123 --- | @POST \/pet@ --- --- Add a new pet to the store +-- *** testClassname + +-- | @PATCH \/fake_classname_test@ -- --- +-- To test class name in snake case -- --- AuthMethod: 'AuthOAuthPetstoreAuth' +-- AuthMethod: 'AuthApiKeyApiKeyQuery' -- --- Note: Has 'Produces' instances, but no response schema --- -addPet - :: (Consumes AddPet contentType, MimeRender contentType Pet) - => contentType -- ^ request content-type ('MimeType') - -> Pet -- ^ "body" - Pet object that needs to be added to the store - -> SwaggerPetstoreRequest AddPet contentType res -addPet _ body = - _mkRequest "POST" ["/pet"] - `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) - `setBodyParam` body - -data AddPet - --- | /Body Param/ "body" - Pet object that needs to be added to the store -instance HasBodyParam AddPet Pet - --- | @application/json@ -instance Consumes AddPet MimeJSON --- | @application/xml@ -instance Consumes AddPet MimeXML +testClassname + :: (Consumes TestClassname contentType, MimeRender contentType Client) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> Client -- ^ "body" - client model + -> SwaggerPetstoreRequest TestClassname contentType Client accept +testClassname _ _ body = + _mkRequest "PATCH" ["/fake_classname_test"] + `_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyApiKeyQuery) + `setBodyParam` body + +data TestClassname + +-- | /Body Param/ "body" - client model +instance HasBodyParam TestClassname Client + +-- | @application/json@ +instance Consumes TestClassname MimeJSON + +-- | @application/json@ +instance Produces TestClassname MimeJSON --- | @application/xml@ -instance Produces AddPet MimeXML --- | @application/json@ -instance Produces AddPet MimeJSON + +-- ** Pet + +-- *** addPet - --- *** deletePet - --- | @DELETE \/pet\/{petId}@ +-- | @POST \/pet@ +-- +-- Add a new pet to the store +-- -- --- Deletes a pet --- +-- +-- AuthMethod: 'AuthOAuthPetstoreAuth' -- --- --- AuthMethod: 'AuthOAuthPetstoreAuth' --- --- Note: Has 'Produces' instances, but no response schema --- -deletePet - :: PetId -- ^ "petId" - Pet id to delete - -> SwaggerPetstoreRequest DeletePet MimeNoContent res -deletePet (PetId petId) = - _mkRequest "DELETE" ["/pet/",toPath petId] +-- Note: Has 'Produces' instances, but no response schema +-- +addPet + :: (Consumes AddPet contentType, MimeRender contentType Pet) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> Pet -- ^ "body" - Pet object that needs to be added to the store + -> SwaggerPetstoreRequest AddPet contentType res accept +addPet _ _ body = + _mkRequest "POST" ["/pet"] `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) - -data DeletePet -instance HasOptionalParam DeletePet ApiKey where - applyOptionalParam req (ApiKey xs) = - req `setHeader` toHeader ("api_key", xs) --- | @application/xml@ -instance Produces DeletePet MimeXML + `setBodyParam` body + +data AddPet + +-- | /Body Param/ "body" - Pet object that needs to be added to the store +instance HasBodyParam AddPet Pet + -- | @application/json@ -instance Produces DeletePet MimeJSON - - --- *** findPetsByStatus - --- | @GET \/pet\/findByStatus@ --- --- Finds Pets by status --- --- Multiple status values can be provided with comma separated strings --- --- AuthMethod: 'AuthOAuthPetstoreAuth' --- -findPetsByStatus - :: Status -- ^ "status" - Status values that need to be considered for filter - -> SwaggerPetstoreRequest FindPetsByStatus MimeNoContent [Pet] -findPetsByStatus (Status status) = - _mkRequest "GET" ["/pet/findByStatus"] - `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) - `setQuery` toQueryColl CommaSeparated ("status", Just status) - -data FindPetsByStatus --- | @application/xml@ -instance Produces FindPetsByStatus MimeXML --- | @application/json@ -instance Produces FindPetsByStatus MimeJSON - - --- *** findPetsByTags +instance Consumes AddPet MimeJSON +-- | @application/xml@ +instance Consumes AddPet MimeXML + +-- | @application/xml@ +instance Produces AddPet MimeXML +-- | @application/json@ +instance Produces AddPet MimeJSON + + +-- *** deletePet + +-- | @DELETE \/pet\/{petId}@ +-- +-- Deletes a pet +-- +-- +-- +-- AuthMethod: 'AuthOAuthPetstoreAuth' +-- +-- Note: Has 'Produces' instances, but no response schema +-- +deletePet + :: Accept accept -- ^ request accept ('MimeType') + -> PetId -- ^ "petId" - Pet id to delete + -> SwaggerPetstoreRequest DeletePet MimeNoContent res accept +deletePet _ (PetId petId) = + _mkRequest "DELETE" ["/pet/",toPath petId] + `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) --- | @GET \/pet\/findByTags@ --- --- Finds Pets by tags --- --- Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. --- --- AuthMethod: 'AuthOAuthPetstoreAuth' --- -findPetsByTags - :: Tags -- ^ "tags" - Tags to filter by - -> SwaggerPetstoreRequest FindPetsByTags MimeNoContent [Pet] -findPetsByTags (Tags tags) = - _mkRequest "GET" ["/pet/findByTags"] - `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) - `setQuery` toQueryColl CommaSeparated ("tags", Just tags) - -{-# DEPRECATED findPetsByTags "" #-} - -data FindPetsByTags --- | @application/xml@ -instance Produces FindPetsByTags MimeXML --- | @application/json@ -instance Produces FindPetsByTags MimeJSON - - --- *** getPetById - --- | @GET \/pet\/{petId}@ --- --- Find pet by ID --- --- Returns a single pet --- --- AuthMethod: 'AuthApiKeyApiKey' --- -getPetById - :: PetId -- ^ "petId" - ID of pet to return - -> SwaggerPetstoreRequest GetPetById MimeNoContent Pet -getPetById (PetId petId) = - _mkRequest "GET" ["/pet/",toPath petId] - `_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyApiKey) - -data GetPetById --- | @application/xml@ -instance Produces GetPetById MimeXML --- | @application/json@ -instance Produces GetPetById MimeJSON - - --- *** updatePet - --- | @PUT \/pet@ --- --- Update an existing pet --- --- --- --- AuthMethod: 'AuthOAuthPetstoreAuth' --- --- Note: Has 'Produces' instances, but no response schema --- -updatePet - :: (Consumes UpdatePet contentType, MimeRender contentType Pet) - => contentType -- ^ request content-type ('MimeType') - -> Pet -- ^ "body" - Pet object that needs to be added to the store - -> SwaggerPetstoreRequest UpdatePet contentType res -updatePet _ body = - _mkRequest "PUT" ["/pet"] - `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) - `setBodyParam` body - -data UpdatePet - --- | /Body Param/ "body" - Pet object that needs to be added to the store -instance HasBodyParam UpdatePet Pet - --- | @application/json@ -instance Consumes UpdatePet MimeJSON --- | @application/xml@ -instance Consumes UpdatePet MimeXML - --- | @application/xml@ -instance Produces UpdatePet MimeXML --- | @application/json@ -instance Produces UpdatePet MimeJSON - - --- *** updatePetWithForm +data DeletePet +instance HasOptionalParam DeletePet ApiKey where + applyOptionalParam req (ApiKey xs) = + req `setHeader` toHeader ("api_key", xs) +-- | @application/xml@ +instance Produces DeletePet MimeXML +-- | @application/json@ +instance Produces DeletePet MimeJSON + + +-- *** findPetsByStatus + +-- | @GET \/pet\/findByStatus@ +-- +-- Finds Pets by status +-- +-- Multiple status values can be provided with comma separated strings +-- +-- AuthMethod: 'AuthOAuthPetstoreAuth' +-- +findPetsByStatus + :: Accept accept -- ^ request accept ('MimeType') + -> Status -- ^ "status" - Status values that need to be considered for filter + -> SwaggerPetstoreRequest FindPetsByStatus MimeNoContent [Pet] accept +findPetsByStatus _ (Status status) = + _mkRequest "GET" ["/pet/findByStatus"] + `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) + `setQuery` toQueryColl CommaSeparated ("status", Just status) + +data FindPetsByStatus +-- | @application/xml@ +instance Produces FindPetsByStatus MimeXML +-- | @application/json@ +instance Produces FindPetsByStatus MimeJSON + + +-- *** findPetsByTags + +-- | @GET \/pet\/findByTags@ +-- +-- Finds Pets by tags +-- +-- Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. +-- +-- AuthMethod: 'AuthOAuthPetstoreAuth' +-- +findPetsByTags + :: Accept accept -- ^ request accept ('MimeType') + -> Tags -- ^ "tags" - Tags to filter by + -> SwaggerPetstoreRequest FindPetsByTags MimeNoContent [Pet] accept +findPetsByTags _ (Tags tags) = + _mkRequest "GET" ["/pet/findByTags"] + `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) + `setQuery` toQueryColl CommaSeparated ("tags", Just tags) + +{-# DEPRECATED findPetsByTags "" #-} + +data FindPetsByTags +-- | @application/xml@ +instance Produces FindPetsByTags MimeXML +-- | @application/json@ +instance Produces FindPetsByTags MimeJSON + + +-- *** getPetById + +-- | @GET \/pet\/{petId}@ +-- +-- Find pet by ID +-- +-- Returns a single pet +-- +-- AuthMethod: 'AuthApiKeyApiKey' +-- +getPetById + :: Accept accept -- ^ request accept ('MimeType') + -> PetId -- ^ "petId" - ID of pet to return + -> SwaggerPetstoreRequest GetPetById MimeNoContent Pet accept +getPetById _ (PetId petId) = + _mkRequest "GET" ["/pet/",toPath petId] + `_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyApiKey) + +data GetPetById +-- | @application/xml@ +instance Produces GetPetById MimeXML +-- | @application/json@ +instance Produces GetPetById MimeJSON + --- | @POST \/pet\/{petId}@ --- --- Updates a pet in the store with form data +-- *** updatePet + +-- | @PUT \/pet@ -- --- +-- Update an existing pet -- --- AuthMethod: 'AuthOAuthPetstoreAuth' +-- -- --- Note: Has 'Produces' instances, but no response schema +-- AuthMethod: 'AuthOAuthPetstoreAuth' -- -updatePetWithForm - :: (Consumes UpdatePetWithForm contentType) - => contentType -- ^ request content-type ('MimeType') - -> PetId -- ^ "petId" - ID of pet that needs to be updated - -> SwaggerPetstoreRequest UpdatePetWithForm contentType res -updatePetWithForm _ (PetId petId) = - _mkRequest "POST" ["/pet/",toPath petId] - `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) - -data UpdatePetWithForm - --- | /Optional Param/ "name" - Updated name of the pet -instance HasOptionalParam UpdatePetWithForm Name2 where - applyOptionalParam req (Name2 xs) = - req `addForm` toForm ("name", xs) - --- | /Optional Param/ "status" - Updated status of the pet -instance HasOptionalParam UpdatePetWithForm StatusText where - applyOptionalParam req (StatusText xs) = - req `addForm` toForm ("status", xs) - --- | @application/x-www-form-urlencoded@ -instance Consumes UpdatePetWithForm MimeFormUrlEncoded - --- | @application/xml@ -instance Produces UpdatePetWithForm MimeXML --- | @application/json@ -instance Produces UpdatePetWithForm MimeJSON +-- Note: Has 'Produces' instances, but no response schema +-- +updatePet + :: (Consumes UpdatePet contentType, MimeRender contentType Pet) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> Pet -- ^ "body" - Pet object that needs to be added to the store + -> SwaggerPetstoreRequest UpdatePet contentType res accept +updatePet _ _ body = + _mkRequest "PUT" ["/pet"] + `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) + `setBodyParam` body + +data UpdatePet + +-- | /Body Param/ "body" - Pet object that needs to be added to the store +instance HasBodyParam UpdatePet Pet + +-- | @application/json@ +instance Consumes UpdatePet MimeJSON +-- | @application/xml@ +instance Consumes UpdatePet MimeXML + +-- | @application/xml@ +instance Produces UpdatePet MimeXML +-- | @application/json@ +instance Produces UpdatePet MimeJSON + - --- *** uploadFile - --- | @POST \/pet\/{petId}\/uploadImage@ --- --- uploads an image +-- *** updatePetWithForm + +-- | @POST \/pet\/{petId}@ +-- +-- Updates a pet in the store with form data +-- -- -- --- --- AuthMethod: 'AuthOAuthPetstoreAuth' --- -uploadFile - :: (Consumes UploadFile contentType) - => contentType -- ^ request content-type ('MimeType') - -> PetId -- ^ "petId" - ID of pet to update - -> SwaggerPetstoreRequest UploadFile contentType ApiResponse -uploadFile _ (PetId petId) = - _mkRequest "POST" ["/pet/",toPath petId,"/uploadImage"] - `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) - -data UploadFile +-- AuthMethod: 'AuthOAuthPetstoreAuth' +-- +-- Note: Has 'Produces' instances, but no response schema +-- +updatePetWithForm + :: (Consumes UpdatePetWithForm contentType) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> PetId -- ^ "petId" - ID of pet that needs to be updated + -> SwaggerPetstoreRequest UpdatePetWithForm contentType res accept +updatePetWithForm _ _ (PetId petId) = + _mkRequest "POST" ["/pet/",toPath petId] + `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) --- | /Optional Param/ "additionalMetadata" - Additional data to pass to server -instance HasOptionalParam UploadFile AdditionalMetadata where - applyOptionalParam req (AdditionalMetadata xs) = - req `_addMultiFormPart` NH.partLBS "additionalMetadata" (mimeRender' MimeMultipartFormData xs) - --- | /Optional Param/ "file" - file to upload -instance HasOptionalParam UploadFile File where - applyOptionalParam req (File xs) = - req `_addMultiFormPart` NH.partFileSource "file" xs - --- | @multipart/form-data@ -instance Consumes UploadFile MimeMultipartFormData - --- | @application/json@ -instance Produces UploadFile MimeJSON - - --- ** Store - --- *** deleteOrder +data UpdatePetWithForm + +-- | /Optional Param/ "name" - Updated name of the pet +instance HasOptionalParam UpdatePetWithForm Name2 where + applyOptionalParam req (Name2 xs) = + req `addForm` toForm ("name", xs) + +-- | /Optional Param/ "status" - Updated status of the pet +instance HasOptionalParam UpdatePetWithForm StatusText where + applyOptionalParam req (StatusText xs) = + req `addForm` toForm ("status", xs) + +-- | @application/x-www-form-urlencoded@ +instance Consumes UpdatePetWithForm MimeFormUrlEncoded + +-- | @application/xml@ +instance Produces UpdatePetWithForm MimeXML +-- | @application/json@ +instance Produces UpdatePetWithForm MimeJSON + --- | @DELETE \/store\/order\/{order_id}@ --- --- Delete purchase order by ID +-- *** uploadFile + +-- | @POST \/pet\/{petId}\/uploadImage@ -- --- For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors +-- uploads an image -- --- Note: Has 'Produces' instances, but no response schema +-- -- -deleteOrder - :: OrderIdText -- ^ "orderId" - ID of the order that needs to be deleted - -> SwaggerPetstoreRequest DeleteOrder MimeNoContent res -deleteOrder (OrderIdText orderId) = - _mkRequest "DELETE" ["/store/order/",toPath orderId] - -data DeleteOrder --- | @application/xml@ -instance Produces DeleteOrder MimeXML --- | @application/json@ -instance Produces DeleteOrder MimeJSON +-- AuthMethod: 'AuthOAuthPetstoreAuth' +-- +uploadFile + :: (Consumes UploadFile contentType) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> PetId -- ^ "petId" - ID of pet to update + -> SwaggerPetstoreRequest UploadFile contentType ApiResponse accept +uploadFile _ _ (PetId petId) = + _mkRequest "POST" ["/pet/",toPath petId,"/uploadImage"] + `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) - --- *** getInventory - --- | @GET \/store\/inventory@ --- --- Returns pet inventories by status --- --- Returns a map of status codes to quantities --- --- AuthMethod: 'AuthApiKeyApiKey' --- -getInventory - :: SwaggerPetstoreRequest GetInventory MimeNoContent ((Map.Map String Int)) -getInventory = - _mkRequest "GET" ["/store/inventory"] - `_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyApiKey) - -data GetInventory --- | @application/json@ -instance Produces GetInventory MimeJSON +data UploadFile + +-- | /Optional Param/ "additionalMetadata" - Additional data to pass to server +instance HasOptionalParam UploadFile AdditionalMetadata where + applyOptionalParam req (AdditionalMetadata xs) = + req `_addMultiFormPart` NH.partLBS "additionalMetadata" (mimeRender' MimeMultipartFormData xs) + +-- | /Optional Param/ "file" - file to upload +instance HasOptionalParam UploadFile File where + applyOptionalParam req (File xs) = + req `_addMultiFormPart` NH.partFileSource "file" xs + +-- | @multipart/form-data@ +instance Consumes UploadFile MimeMultipartFormData + +-- | @application/json@ +instance Produces UploadFile MimeJSON + + +-- ** Store - --- *** getOrderById - --- | @GET \/store\/order\/{order_id}@ --- --- Find purchase order by ID --- --- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions --- -getOrderById - :: OrderId -- ^ "orderId" - ID of pet that needs to be fetched - -> SwaggerPetstoreRequest GetOrderById MimeNoContent Order -getOrderById (OrderId orderId) = - _mkRequest "GET" ["/store/order/",toPath orderId] - -data GetOrderById --- | @application/xml@ -instance Produces GetOrderById MimeXML --- | @application/json@ -instance Produces GetOrderById MimeJSON - - --- *** placeOrder +-- *** deleteOrder + +-- | @DELETE \/store\/order\/{order_id}@ +-- +-- Delete purchase order by ID +-- +-- For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors +-- +-- Note: Has 'Produces' instances, but no response schema +-- +deleteOrder + :: Accept accept -- ^ request accept ('MimeType') + -> OrderIdText -- ^ "orderId" - ID of the order that needs to be deleted + -> SwaggerPetstoreRequest DeleteOrder MimeNoContent res accept +deleteOrder _ (OrderIdText orderId) = + _mkRequest "DELETE" ["/store/order/",toPath orderId] + +data DeleteOrder +-- | @application/xml@ +instance Produces DeleteOrder MimeXML +-- | @application/json@ +instance Produces DeleteOrder MimeJSON + --- | @POST \/store\/order@ --- --- Place an order for a pet +-- *** getInventory + +-- | @GET \/store\/inventory@ -- --- +-- Returns pet inventories by status -- -placeOrder - :: (Consumes PlaceOrder contentType, MimeRender contentType Order) - => contentType -- ^ request content-type ('MimeType') - -> Order -- ^ "body" - order placed for purchasing the pet - -> SwaggerPetstoreRequest PlaceOrder contentType Order -placeOrder _ body = - _mkRequest "POST" ["/store/order"] - `setBodyParam` body - -data PlaceOrder +-- Returns a map of status codes to quantities +-- +-- AuthMethod: 'AuthApiKeyApiKey' +-- +getInventory + :: Accept accept -- ^ request accept ('MimeType') + -> SwaggerPetstoreRequest GetInventory MimeNoContent ((Map.Map String Int)) accept +getInventory _ = + _mkRequest "GET" ["/store/inventory"] + `_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyApiKey) --- | /Body Param/ "body" - order placed for purchasing the pet -instance HasBodyParam PlaceOrder Order --- | @application/xml@ -instance Produces PlaceOrder MimeXML --- | @application/json@ -instance Produces PlaceOrder MimeJSON +data GetInventory +-- | @application/json@ +instance Produces GetInventory MimeJSON + + +-- *** getOrderById - --- ** User - --- *** createUser - --- | @POST \/user@ --- --- Create user --- --- This can only be done by the logged in user. --- --- Note: Has 'Produces' instances, but no response schema --- -createUser - :: (Consumes CreateUser contentType, MimeRender contentType User) - => contentType -- ^ request content-type ('MimeType') - -> User -- ^ "body" - Created user object - -> SwaggerPetstoreRequest CreateUser contentType res -createUser _ body = - _mkRequest "POST" ["/user"] - `setBodyParam` body +-- | @GET \/store\/order\/{order_id}@ +-- +-- Find purchase order by ID +-- +-- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions +-- +getOrderById + :: Accept accept -- ^ request accept ('MimeType') + -> OrderId -- ^ "orderId" - ID of pet that needs to be fetched + -> SwaggerPetstoreRequest GetOrderById MimeNoContent Order accept +getOrderById _ (OrderId orderId) = + _mkRequest "GET" ["/store/order/",toPath orderId] + +data GetOrderById +-- | @application/xml@ +instance Produces GetOrderById MimeXML +-- | @application/json@ +instance Produces GetOrderById MimeJSON + + +-- *** placeOrder -data CreateUser - --- | /Body Param/ "body" - Created user object -instance HasBodyParam CreateUser User --- | @application/xml@ -instance Produces CreateUser MimeXML --- | @application/json@ -instance Produces CreateUser MimeJSON - - --- *** createUsersWithArrayInput - --- | @POST \/user\/createWithArray@ --- --- Creates list of users with given input array --- --- --- --- Note: Has 'Produces' instances, but no response schema --- -createUsersWithArrayInput - :: (Consumes CreateUsersWithArrayInput contentType, MimeRender contentType Body) - => contentType -- ^ request content-type ('MimeType') - -> Body -- ^ "body" - List of user object - -> SwaggerPetstoreRequest CreateUsersWithArrayInput contentType res -createUsersWithArrayInput _ body = - _mkRequest "POST" ["/user/createWithArray"] - `setBodyParam` body - -data CreateUsersWithArrayInput - --- | /Body Param/ "body" - List of user object -instance HasBodyParam CreateUsersWithArrayInput Body --- | @application/xml@ -instance Produces CreateUsersWithArrayInput MimeXML --- | @application/json@ -instance Produces CreateUsersWithArrayInput MimeJSON - - --- *** createUsersWithListInput - --- | @POST \/user\/createWithList@ --- --- Creates list of users with given input array --- --- --- --- Note: Has 'Produces' instances, but no response schema --- -createUsersWithListInput - :: (Consumes CreateUsersWithListInput contentType, MimeRender contentType Body) - => contentType -- ^ request content-type ('MimeType') - -> Body -- ^ "body" - List of user object - -> SwaggerPetstoreRequest CreateUsersWithListInput contentType res -createUsersWithListInput _ body = - _mkRequest "POST" ["/user/createWithList"] - `setBodyParam` body +-- | @POST \/store\/order@ +-- +-- Place an order for a pet +-- +-- +-- +placeOrder + :: (Consumes PlaceOrder contentType, MimeRender contentType Order) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> Order -- ^ "body" - order placed for purchasing the pet + -> SwaggerPetstoreRequest PlaceOrder contentType Order accept +placeOrder _ _ body = + _mkRequest "POST" ["/store/order"] + `setBodyParam` body + +data PlaceOrder + +-- | /Body Param/ "body" - order placed for purchasing the pet +instance HasBodyParam PlaceOrder Order +-- | @application/xml@ +instance Produces PlaceOrder MimeXML +-- | @application/json@ +instance Produces PlaceOrder MimeJSON + + +-- ** User + +-- *** createUser + +-- | @POST \/user@ +-- +-- Create user +-- +-- This can only be done by the logged in user. +-- +-- Note: Has 'Produces' instances, but no response schema +-- +createUser + :: (Consumes CreateUser contentType, MimeRender contentType User) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> User -- ^ "body" - Created user object + -> SwaggerPetstoreRequest CreateUser contentType res accept +createUser _ _ body = + _mkRequest "POST" ["/user"] + `setBodyParam` body + +data CreateUser + +-- | /Body Param/ "body" - Created user object +instance HasBodyParam CreateUser User +-- | @application/xml@ +instance Produces CreateUser MimeXML +-- | @application/json@ +instance Produces CreateUser MimeJSON + -data CreateUsersWithListInput +-- *** createUsersWithArrayInput --- | /Body Param/ "body" - List of user object -instance HasBodyParam CreateUsersWithListInput Body --- | @application/xml@ -instance Produces CreateUsersWithListInput MimeXML --- | @application/json@ -instance Produces CreateUsersWithListInput MimeJSON - - --- *** deleteUser - --- | @DELETE \/user\/{username}@ --- --- Delete user --- --- This can only be done by the logged in user. --- --- Note: Has 'Produces' instances, but no response schema --- -deleteUser - :: Username -- ^ "username" - The name that needs to be deleted - -> SwaggerPetstoreRequest DeleteUser MimeNoContent res -deleteUser (Username username) = - _mkRequest "DELETE" ["/user/",toPath username] - -data DeleteUser --- | @application/xml@ -instance Produces DeleteUser MimeXML --- | @application/json@ -instance Produces DeleteUser MimeJSON +-- | @POST \/user\/createWithArray@ +-- +-- Creates list of users with given input array +-- +-- +-- +-- Note: Has 'Produces' instances, but no response schema +-- +createUsersWithArrayInput + :: (Consumes CreateUsersWithArrayInput contentType, MimeRender contentType Body) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> Body -- ^ "body" - List of user object + -> SwaggerPetstoreRequest CreateUsersWithArrayInput contentType res accept +createUsersWithArrayInput _ _ body = + _mkRequest "POST" ["/user/createWithArray"] + `setBodyParam` body + +data CreateUsersWithArrayInput + +-- | /Body Param/ "body" - List of user object +instance HasBodyParam CreateUsersWithArrayInput Body +-- | @application/xml@ +instance Produces CreateUsersWithArrayInput MimeXML +-- | @application/json@ +instance Produces CreateUsersWithArrayInput MimeJSON + + +-- *** createUsersWithListInput - --- *** getUserByName - --- | @GET \/user\/{username}@ +-- | @POST \/user\/createWithList@ +-- +-- Creates list of users with given input array +-- -- --- Get user by user name --- +-- +-- Note: Has 'Produces' instances, but no response schema -- --- -getUserByName - :: Username -- ^ "username" - The name that needs to be fetched. Use user1 for testing. - -> SwaggerPetstoreRequest GetUserByName MimeNoContent User -getUserByName (Username username) = - _mkRequest "GET" ["/user/",toPath username] - -data GetUserByName --- | @application/xml@ -instance Produces GetUserByName MimeXML --- | @application/json@ -instance Produces GetUserByName MimeJSON - - --- *** loginUser - --- | @GET \/user\/login@ --- --- Logs user into the system --- --- --- -loginUser - :: Username -- ^ "username" - The user name for login - -> Password -- ^ "password" - The password for login in clear text - -> SwaggerPetstoreRequest LoginUser MimeNoContent Text -loginUser (Username username) (Password password) = - _mkRequest "GET" ["/user/login"] - `setQuery` toQuery ("username", Just username) - `setQuery` toQuery ("password", Just password) - -data LoginUser --- | @application/xml@ -instance Produces LoginUser MimeXML --- | @application/json@ -instance Produces LoginUser MimeJSON +createUsersWithListInput + :: (Consumes CreateUsersWithListInput contentType, MimeRender contentType Body) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> Body -- ^ "body" - List of user object + -> SwaggerPetstoreRequest CreateUsersWithListInput contentType res accept +createUsersWithListInput _ _ body = + _mkRequest "POST" ["/user/createWithList"] + `setBodyParam` body + +data CreateUsersWithListInput + +-- | /Body Param/ "body" - List of user object +instance HasBodyParam CreateUsersWithListInput Body +-- | @application/xml@ +instance Produces CreateUsersWithListInput MimeXML +-- | @application/json@ +instance Produces CreateUsersWithListInput MimeJSON + + +-- *** deleteUser + +-- | @DELETE \/user\/{username}@ +-- +-- Delete user +-- +-- This can only be done by the logged in user. +-- +-- Note: Has 'Produces' instances, but no response schema +-- +deleteUser + :: Accept accept -- ^ request accept ('MimeType') + -> Username -- ^ "username" - The name that needs to be deleted + -> SwaggerPetstoreRequest DeleteUser MimeNoContent res accept +deleteUser _ (Username username) = + _mkRequest "DELETE" ["/user/",toPath username] - --- *** logoutUser - --- | @GET \/user\/logout@ --- --- Logs out current logged in user session --- --- --- --- Note: Has 'Produces' instances, but no response schema +data DeleteUser +-- | @application/xml@ +instance Produces DeleteUser MimeXML +-- | @application/json@ +instance Produces DeleteUser MimeJSON + + +-- *** getUserByName + +-- | @GET \/user\/{username}@ -- -logoutUser - :: SwaggerPetstoreRequest LogoutUser MimeNoContent res -logoutUser = - _mkRequest "GET" ["/user/logout"] - -data LogoutUser --- | @application/xml@ -instance Produces LogoutUser MimeXML --- | @application/json@ -instance Produces LogoutUser MimeJSON +-- Get user by user name +-- +-- +-- +getUserByName + :: Accept accept -- ^ request accept ('MimeType') + -> Username -- ^ "username" - The name that needs to be fetched. Use user1 for testing. + -> SwaggerPetstoreRequest GetUserByName MimeNoContent User accept +getUserByName _ (Username username) = + _mkRequest "GET" ["/user/",toPath username] - --- *** updateUser - --- | @PUT \/user\/{username}@ --- --- Updated user --- --- This can only be done by the logged in user. --- --- Note: Has 'Produces' instances, but no response schema +data GetUserByName +-- | @application/xml@ +instance Produces GetUserByName MimeXML +-- | @application/json@ +instance Produces GetUserByName MimeJSON + + +-- *** loginUser + +-- | @GET \/user\/login@ -- -updateUser - :: (Consumes UpdateUser contentType, MimeRender contentType User) - => contentType -- ^ request content-type ('MimeType') - -> Username -- ^ "username" - name that need to be deleted - -> User -- ^ "body" - Updated user object - -> SwaggerPetstoreRequest UpdateUser contentType res -updateUser _ (Username username) body = - _mkRequest "PUT" ["/user/",toPath username] - `setBodyParam` body - -data UpdateUser - --- | /Body Param/ "body" - Updated user object -instance HasBodyParam UpdateUser User --- | @application/xml@ -instance Produces UpdateUser MimeXML --- | @application/json@ -instance Produces UpdateUser MimeJSON - +-- Logs user into the system +-- +-- +-- +loginUser + :: Accept accept -- ^ request accept ('MimeType') + -> Username -- ^ "username" - The user name for login + -> Password -- ^ "password" - The password for login in clear text + -> SwaggerPetstoreRequest LoginUser MimeNoContent Text accept +loginUser _ (Username username) (Password password) = + _mkRequest "GET" ["/user/login"] + `setQuery` toQuery ("username", Just username) + `setQuery` toQuery ("password", Just password) + +data LoginUser +-- | @application/xml@ +instance Produces LoginUser MimeXML +-- | @application/json@ +instance Produces LoginUser MimeJSON --- * Parameter newtypes +-- *** logoutUser -newtype AdditionalMetadata = AdditionalMetadata { unAdditionalMetadata :: Text } deriving (P.Eq, P.Show) -newtype ApiKey = ApiKey { unApiKey :: Text } deriving (P.Eq, P.Show) -newtype Body = Body { unBody :: [User] } deriving (P.Eq, P.Show, A.ToJSON) -newtype Byte = Byte { unByte :: ByteArray } deriving (P.Eq, P.Show) -newtype Callback = Callback { unCallback :: Text } deriving (P.Eq, P.Show) -newtype EnumFormString = EnumFormString { unEnumFormString :: Text } deriving (P.Eq, P.Show) -newtype EnumFormStringArray = EnumFormStringArray { unEnumFormStringArray :: [Text] } deriving (P.Eq, P.Show) -newtype EnumHeaderString = EnumHeaderString { unEnumHeaderString :: Text } deriving (P.Eq, P.Show) -newtype EnumHeaderStringArray = EnumHeaderStringArray { unEnumHeaderStringArray :: [Text] } deriving (P.Eq, P.Show) -newtype EnumQueryDouble = EnumQueryDouble { unEnumQueryDouble :: Double } deriving (P.Eq, P.Show) -newtype EnumQueryInteger = EnumQueryInteger { unEnumQueryInteger :: Int } deriving (P.Eq, P.Show) -newtype EnumQueryString = EnumQueryString { unEnumQueryString :: Text } deriving (P.Eq, P.Show) -newtype EnumQueryStringArray = EnumQueryStringArray { unEnumQueryStringArray :: [Text] } deriving (P.Eq, P.Show) -newtype File = File { unFile :: FilePath } deriving (P.Eq, P.Show) -newtype Int32 = Int32 { unInt32 :: Int } deriving (P.Eq, P.Show) -newtype Int64 = Int64 { unInt64 :: Integer } deriving (P.Eq, P.Show) -newtype Name2 = Name2 { unName2 :: Text } deriving (P.Eq, P.Show) -newtype Number = Number { unNumber :: Double } deriving (P.Eq, P.Show) -newtype OrderId = OrderId { unOrderId :: Integer } deriving (P.Eq, P.Show) -newtype OrderIdText = OrderIdText { unOrderIdText :: Text } deriving (P.Eq, P.Show) -newtype Param = Param { unParam :: Text } deriving (P.Eq, P.Show) -newtype Param2 = Param2 { unParam2 :: Text } deriving (P.Eq, P.Show) -newtype ParamBinary = ParamBinary { unParamBinary :: Binary } deriving (P.Eq, P.Show) -newtype ParamDate = ParamDate { unParamDate :: Date } deriving (P.Eq, P.Show) -newtype ParamDateTime = ParamDateTime { unParamDateTime :: DateTime } deriving (P.Eq, P.Show) -newtype ParamDouble = ParamDouble { unParamDouble :: Double } deriving (P.Eq, P.Show) -newtype ParamFloat = ParamFloat { unParamFloat :: Float } deriving (P.Eq, P.Show) -newtype ParamInteger = ParamInteger { unParamInteger :: Int } deriving (P.Eq, P.Show) -newtype ParamString = ParamString { unParamString :: Text } deriving (P.Eq, P.Show) -newtype Password = Password { unPassword :: Text } deriving (P.Eq, P.Show) -newtype PatternWithoutDelimiter = PatternWithoutDelimiter { unPatternWithoutDelimiter :: Text } deriving (P.Eq, P.Show) -newtype PetId = PetId { unPetId :: Integer } deriving (P.Eq, P.Show) -newtype Status = Status { unStatus :: [Text] } deriving (P.Eq, P.Show) -newtype StatusText = StatusText { unStatusText :: Text } deriving (P.Eq, P.Show) -newtype Tags = Tags { unTags :: [Text] } deriving (P.Eq, P.Show) -newtype Username = Username { unUsername :: Text } deriving (P.Eq, P.Show) - --- * Auth Methods - --- ** AuthApiKeyApiKey -data AuthApiKeyApiKey = - AuthApiKeyApiKey Text -- ^ secret - deriving (P.Eq, P.Show, P.Typeable) +-- | @GET \/user\/logout@ +-- +-- Logs out current logged in user session +-- +-- +-- +-- Note: Has 'Produces' instances, but no response schema +-- +logoutUser + :: Accept accept -- ^ request accept ('MimeType') + -> SwaggerPetstoreRequest LogoutUser MimeNoContent res accept +logoutUser _ = + _mkRequest "GET" ["/user/logout"] + +data LogoutUser +-- | @application/xml@ +instance Produces LogoutUser MimeXML +-- | @application/json@ +instance Produces LogoutUser MimeJSON + + +-- *** updateUser + +-- | @PUT \/user\/{username}@ +-- +-- Updated user +-- +-- This can only be done by the logged in user. +-- +-- Note: Has 'Produces' instances, but no response schema +-- +updateUser + :: (Consumes UpdateUser contentType, MimeRender contentType User) + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> Username -- ^ "username" - name that need to be deleted + -> User -- ^ "body" - Updated user object + -> SwaggerPetstoreRequest UpdateUser contentType res accept +updateUser _ _ (Username username) body = + _mkRequest "PUT" ["/user/",toPath username] + `setBodyParam` body + +data UpdateUser -instance AuthMethod AuthApiKeyApiKey where - applyAuthMethod _ a@(AuthApiKeyApiKey secret) req = - P.pure $ - if (P.typeOf a `P.elem` rAuthTypes req) - then req `setHeader` toHeader ("api_key", secret) - & L.over rAuthTypesL (P.filter (/= P.typeOf a)) - else req +-- | /Body Param/ "body" - Updated user object +instance HasBodyParam UpdateUser User +-- | @application/xml@ +instance Produces UpdateUser MimeXML +-- | @application/json@ +instance Produces UpdateUser MimeJSON + --- ** AuthApiKeyApiKeyQuery -data AuthApiKeyApiKeyQuery = - AuthApiKeyApiKeyQuery Text -- ^ secret - deriving (P.Eq, P.Show, P.Typeable) - -instance AuthMethod AuthApiKeyApiKeyQuery where - applyAuthMethod _ a@(AuthApiKeyApiKeyQuery secret) req = - P.pure $ - if (P.typeOf a `P.elem` rAuthTypes req) - then req `setQuery` toQuery ("api_key_query", Just secret) - & L.over rAuthTypesL (P.filter (/= P.typeOf a)) - else req - --- ** AuthBasicHttpBasicTest -data AuthBasicHttpBasicTest = - AuthBasicHttpBasicTest B.ByteString B.ByteString -- ^ username password - deriving (P.Eq, P.Show, P.Typeable) - -instance AuthMethod AuthBasicHttpBasicTest where - applyAuthMethod _ a@(AuthBasicHttpBasicTest user pw) req = - P.pure $ - if (P.typeOf a `P.elem` rAuthTypes req) - then req `setHeader` toHeader ("Authorization", T.decodeUtf8 cred) - & L.over rAuthTypesL (P.filter (/= P.typeOf a)) - else req - where cred = BC.append "Basic " (B64.encode $ BC.concat [ user, ":", pw ]) - --- ** AuthOAuthPetstoreAuth -data AuthOAuthPetstoreAuth = - AuthOAuthPetstoreAuth Text -- ^ secret - deriving (P.Eq, P.Show, P.Typeable) - -instance AuthMethod AuthOAuthPetstoreAuth where - applyAuthMethod _ a@(AuthOAuthPetstoreAuth secret) req = - P.pure $ - if (P.typeOf a `P.elem` rAuthTypes req) - then req `setHeader` toHeader ("Authorization", "Bearer " <> secret) - & L.over rAuthTypesL (P.filter (/= P.typeOf a)) - else req + +-- * Parameter newtypes + +newtype AdditionalMetadata = AdditionalMetadata { unAdditionalMetadata :: Text } deriving (P.Eq, P.Show) +newtype ApiKey = ApiKey { unApiKey :: Text } deriving (P.Eq, P.Show) +newtype Body = Body { unBody :: [User] } deriving (P.Eq, P.Show, A.ToJSON) +newtype Byte = Byte { unByte :: ByteArray } deriving (P.Eq, P.Show) +newtype Callback = Callback { unCallback :: Text } deriving (P.Eq, P.Show) +newtype EnumFormString = EnumFormString { unEnumFormString :: E'EnumFormString } deriving (P.Eq, P.Show) +newtype EnumFormStringArray = EnumFormStringArray { unEnumFormStringArray :: [E'Inner2] } deriving (P.Eq, P.Show) +newtype EnumHeaderString = EnumHeaderString { unEnumHeaderString :: E'EnumFormString } deriving (P.Eq, P.Show) +newtype EnumHeaderStringArray = EnumHeaderStringArray { unEnumHeaderStringArray :: [E'Inner2] } deriving (P.Eq, P.Show) +newtype EnumQueryDouble = EnumQueryDouble { unEnumQueryDouble :: E'EnumNumber } deriving (P.Eq, P.Show) +newtype EnumQueryInteger = EnumQueryInteger { unEnumQueryInteger :: E'EnumQueryInteger } deriving (P.Eq, P.Show) +newtype EnumQueryString = EnumQueryString { unEnumQueryString :: E'EnumFormString } deriving (P.Eq, P.Show) +newtype EnumQueryStringArray = EnumQueryStringArray { unEnumQueryStringArray :: [E'Inner2] } deriving (P.Eq, P.Show) +newtype File = File { unFile :: FilePath } deriving (P.Eq, P.Show) +newtype Int32 = Int32 { unInt32 :: Int } deriving (P.Eq, P.Show) +newtype Int64 = Int64 { unInt64 :: Integer } deriving (P.Eq, P.Show) +newtype Name2 = Name2 { unName2 :: Text } deriving (P.Eq, P.Show) +newtype Number = Number { unNumber :: Double } deriving (P.Eq, P.Show) +newtype OrderId = OrderId { unOrderId :: Integer } deriving (P.Eq, P.Show) +newtype OrderIdText = OrderIdText { unOrderIdText :: Text } deriving (P.Eq, P.Show) +newtype Param = Param { unParam :: Text } deriving (P.Eq, P.Show) +newtype Param2 = Param2 { unParam2 :: Text } deriving (P.Eq, P.Show) +newtype ParamBinary = ParamBinary { unParamBinary :: Binary } deriving (P.Eq, P.Show) +newtype ParamDate = ParamDate { unParamDate :: Date } deriving (P.Eq, P.Show) +newtype ParamDateTime = ParamDateTime { unParamDateTime :: DateTime } deriving (P.Eq, P.Show) +newtype ParamDouble = ParamDouble { unParamDouble :: Double } deriving (P.Eq, P.Show) +newtype ParamFloat = ParamFloat { unParamFloat :: Float } deriving (P.Eq, P.Show) +newtype ParamInteger = ParamInteger { unParamInteger :: Int } deriving (P.Eq, P.Show) +newtype ParamString = ParamString { unParamString :: Text } deriving (P.Eq, P.Show) +newtype Password = Password { unPassword :: Text } deriving (P.Eq, P.Show) +newtype PatternWithoutDelimiter = PatternWithoutDelimiter { unPatternWithoutDelimiter :: Text } deriving (P.Eq, P.Show) +newtype PetId = PetId { unPetId :: Integer } deriving (P.Eq, P.Show) +newtype Status = Status { unStatus :: [E'Status2] } deriving (P.Eq, P.Show) +newtype StatusText = StatusText { unStatusText :: Text } deriving (P.Eq, P.Show) +newtype Tags = Tags { unTags :: [Text] } deriving (P.Eq, P.Show) +newtype Username = Username { unUsername :: Text } deriving (P.Eq, P.Show) - +-- * Auth Methods --- * Custom Mime Types - --- ** MimeJsonCharsetutf8 - -data MimeJsonCharsetutf8 = MimeJsonCharsetutf8 deriving (P.Typeable) - --- | @application/json; charset=utf-8@ -instance MimeType MimeJsonCharsetutf8 where - mimeType _ = Just $ P.fromString "application/json; charset=utf-8" -instance A.ToJSON a => MimeRender MimeJsonCharsetutf8 a where mimeRender _ = A.encode -instance A.FromJSON a => MimeUnrender MimeJsonCharsetutf8 a where mimeUnrender _ = A.eitherDecode --- instance MimeRender MimeJsonCharsetutf8 T.Text where mimeRender _ = undefined --- instance MimeUnrender MimeJsonCharsetutf8 T.Text where mimeUnrender _ = undefined - --- ** MimeXmlCharsetutf8 - -data MimeXmlCharsetutf8 = MimeXmlCharsetutf8 deriving (P.Typeable) +-- ** AuthApiKeyApiKey +data AuthApiKeyApiKey = + AuthApiKeyApiKey Text -- ^ secret + deriving (P.Eq, P.Show, P.Typeable) + +instance AuthMethod AuthApiKeyApiKey where + applyAuthMethod _ a@(AuthApiKeyApiKey secret) req = + P.pure $ + if (P.typeOf a `P.elem` rAuthTypes req) + then req `setHeader` toHeader ("api_key", secret) + & L.over rAuthTypesL (P.filter (/= P.typeOf a)) + else req + +-- ** AuthApiKeyApiKeyQuery +data AuthApiKeyApiKeyQuery = + AuthApiKeyApiKeyQuery Text -- ^ secret + deriving (P.Eq, P.Show, P.Typeable) --- | @application/xml; charset=utf-8@ -instance MimeType MimeXmlCharsetutf8 where - mimeType _ = Just $ P.fromString "application/xml; charset=utf-8" --- instance MimeRender MimeXmlCharsetutf8 T.Text where mimeRender _ = undefined --- instance MimeUnrender MimeXmlCharsetutf8 T.Text where mimeUnrender _ = undefined - - - \ No newline at end of file +instance AuthMethod AuthApiKeyApiKeyQuery where + applyAuthMethod _ a@(AuthApiKeyApiKeyQuery secret) req = + P.pure $ + if (P.typeOf a `P.elem` rAuthTypes req) + then req `setQuery` toQuery ("api_key_query", Just secret) + & L.over rAuthTypesL (P.filter (/= P.typeOf a)) + else req + +-- ** AuthBasicHttpBasicTest +data AuthBasicHttpBasicTest = + AuthBasicHttpBasicTest B.ByteString B.ByteString -- ^ username password + deriving (P.Eq, P.Show, P.Typeable) + +instance AuthMethod AuthBasicHttpBasicTest where + applyAuthMethod _ a@(AuthBasicHttpBasicTest user pw) req = + P.pure $ + if (P.typeOf a `P.elem` rAuthTypes req) + then req `setHeader` toHeader ("Authorization", T.decodeUtf8 cred) + & L.over rAuthTypesL (P.filter (/= P.typeOf a)) + else req + where cred = BC.append "Basic " (B64.encode $ BC.concat [ user, ":", pw ]) + +-- ** AuthOAuthPetstoreAuth +data AuthOAuthPetstoreAuth = + AuthOAuthPetstoreAuth Text -- ^ secret + deriving (P.Eq, P.Show, P.Typeable) + +instance AuthMethod AuthOAuthPetstoreAuth where + applyAuthMethod _ a@(AuthOAuthPetstoreAuth secret) req = + P.pure $ + if (P.typeOf a `P.elem` rAuthTypes req) + then req `setHeader` toHeader ("Authorization", "Bearer " <> secret) + & L.over rAuthTypesL (P.filter (/= P.typeOf a)) + else req + + + +-- * Custom Mime Types + +-- ** MimeJsonCharsetutf8 + +data MimeJsonCharsetutf8 = MimeJsonCharsetutf8 deriving (P.Typeable) + +-- | @application/json; charset=utf-8@ +instance MimeType MimeJsonCharsetutf8 where + mimeType _ = Just $ P.fromString "application/json; charset=utf-8" +instance A.ToJSON a => MimeRender MimeJsonCharsetutf8 a where mimeRender _ = A.encode +instance A.FromJSON a => MimeUnrender MimeJsonCharsetutf8 a where mimeUnrender _ = A.eitherDecode +-- instance MimeRender MimeJsonCharsetutf8 T.Text where mimeRender _ = undefined +-- instance MimeUnrender MimeJsonCharsetutf8 T.Text where mimeUnrender _ = undefined + +-- ** MimeXmlCharsetutf8 + +data MimeXmlCharsetutf8 = MimeXmlCharsetutf8 deriving (P.Typeable) + +-- | @application/xml; charset=utf-8@ +instance MimeType MimeXmlCharsetutf8 where + mimeType _ = Just $ P.fromString "application/xml; charset=utf-8" +-- instance MimeRender MimeXmlCharsetutf8 T.Text where mimeRender _ = undefined +-- instance MimeUnrender MimeXmlCharsetutf8 T.Text where mimeUnrender _ = undefined + + + \ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.Client.html b/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.Client.html index 2c876b81d8a..216e373e1b6 100644 --- a/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.Client.html +++ b/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.Client.html @@ -56,163 +56,158 @@ Module : SwaggerPetstore.Client -- | send a request returning the raw http response dispatchLbs - :: (Produces req accept, MimeType contentType) + :: (Produces req accept, MimeType contentType) => NH.Manager -- ^ http-client Connection manager -> SwaggerPetstoreConfig -- ^ config - -> SwaggerPetstoreRequest req contentType res -- ^ request - -> accept -- ^ "accept" 'MimeType' - -> IO (NH.Response BCL.ByteString) -- ^ response -dispatchLbs manager config request accept = do - initReq <- _toInitRequest config request accept - dispatchInitUnsafe manager config initReq - --- ** Mime - --- | pair of decoded http body and http response -data MimeResult res = - MimeResult { mimeResult :: Either MimeError res -- ^ decoded http body - , mimeResultResponse :: NH.Response BCL.ByteString -- ^ http response - } - deriving (Show, Functor, Foldable, Traversable) - --- | pair of unrender/parser error and http response -data MimeError = - MimeError { - mimeError :: String -- ^ unrender/parser error - , mimeErrorResponse :: NH.Response BCL.ByteString -- ^ http response - } deriving (Eq, Show) - --- | send a request returning the 'MimeResult' -dispatchMime - :: (Produces req accept, MimeUnrender accept res, MimeType contentType) - => NH.Manager -- ^ http-client Connection manager - -> SwaggerPetstoreConfig -- ^ config - -> SwaggerPetstoreRequest req contentType res -- ^ request - -> accept -- ^ "accept" 'MimeType' - -> IO (MimeResult res) -- ^ response -dispatchMime manager config request accept = do - httpResponse <- dispatchLbs manager config request accept - parsedResult <- - runConfigLogWithExceptions "Client" config $ - do case mimeUnrender' accept (NH.responseBody httpResponse) of - Left s -> do - _log "Client" levelError (T.pack s) - pure (Left (MimeError s httpResponse)) - Right r -> pure (Right r) - return (MimeResult parsedResult httpResponse) - --- | like 'dispatchMime', but only returns the decoded http body -dispatchMime' - :: (Produces req accept, MimeUnrender accept res, MimeType contentType) - => NH.Manager -- ^ http-client Connection manager - -> SwaggerPetstoreConfig -- ^ config - -> SwaggerPetstoreRequest req contentType res -- ^ request - -> accept -- ^ "accept" 'MimeType' - -> IO (Either MimeError res) -- ^ response -dispatchMime' manager config request accept = do - MimeResult parsedResult _ <- dispatchMime manager config request accept - return parsedResult - --- ** Unsafe - --- | like 'dispatchReqLbs', but does not validate the operation is a 'Producer' of the "accept" 'MimeType'. (Useful if the server's response is undocumented) -dispatchLbsUnsafe - :: (MimeType accept, MimeType contentType) - => NH.Manager -- ^ http-client Connection manager - -> SwaggerPetstoreConfig -- ^ config - -> SwaggerPetstoreRequest req contentType res -- ^ request - -> accept -- ^ "accept" 'MimeType' - -> IO (NH.Response BCL.ByteString) -- ^ response -dispatchLbsUnsafe manager config request accept = do - initReq <- _toInitRequest config request accept - dispatchInitUnsafe manager config initReq - --- | dispatch an InitRequest -dispatchInitUnsafe - :: NH.Manager -- ^ http-client Connection manager - -> SwaggerPetstoreConfig -- ^ config - -> InitRequest req contentType res accept -- ^ init request - -> IO (NH.Response BCL.ByteString) -- ^ response -dispatchInitUnsafe manager config (InitRequest req) = do - runConfigLogWithExceptions src config $ - do _log src levelInfo requestLogMsg - _log src levelDebug requestDbgLogMsg - res <- P.liftIO $ NH.httpLbs req manager - _log src levelInfo (responseLogMsg res) - _log src levelDebug ((T.pack . show) res) - return res - where - src = "Client" - endpoint = - T.pack $ - BC.unpack $ - NH.method req <> " " <> NH.host req <> NH.path req <> NH.queryString req - requestLogMsg = "REQ:" <> endpoint - requestDbgLogMsg = - "Headers=" <> (T.pack . show) (NH.requestHeaders req) <> " Body=" <> - (case NH.requestBody req of - NH.RequestBodyLBS xs -> T.decodeUtf8 (BL.toStrict xs) - _ -> "<RequestBody>") - responseStatusCode = (T.pack . show) . NH.statusCode . NH.responseStatus - responseLogMsg res = - "RES:statusCode=" <> responseStatusCode res <> " (" <> endpoint <> ")" - --- * InitRequest - --- | wraps an http-client 'Request' with request/response type parameters -newtype InitRequest req contentType res accept = InitRequest - { unInitRequest :: NH.Request - } deriving (Show) - --- | Build an http-client 'Request' record from the supplied config and request -_toInitRequest - :: (MimeType accept, MimeType contentType) - => SwaggerPetstoreConfig -- ^ config - -> SwaggerPetstoreRequest req contentType res -- ^ request - -> accept -- ^ "accept" 'MimeType' - -> IO (InitRequest req contentType res accept) -- ^ initialized request -_toInitRequest config req0 accept = - runConfigLogWithExceptions "Client" config $ do - parsedReq <- P.liftIO $ NH.parseRequest $ BCL.unpack $ BCL.append (configHost config) (BCL.concat (rUrlPath req0)) - req1 <- P.liftIO $ _applyAuthMethods req0 config - P.when - (configValidateAuthMethods config && (not . null . rAuthTypes) req1) - (E.throwString $ "AuthMethod not configured: " <> (show . head . rAuthTypes) req1) - let req2 = req1 & _setContentTypeHeader & flip _setAcceptHeader accept - reqHeaders = ("User-Agent", WH.toHeader (configUserAgent config)) : paramsHeaders (rParams req2) - reqQuery = NH.renderQuery True (paramsQuery (rParams req2)) - pReq = parsedReq { NH.method = (rMethod req2) - , NH.requestHeaders = reqHeaders - , NH.queryString = reqQuery - } - outReq <- case paramsBody (rParams req2) of - ParamBodyNone -> pure (pReq { NH.requestBody = mempty }) - ParamBodyB bs -> pure (pReq { NH.requestBody = NH.RequestBodyBS bs }) - ParamBodyBL bl -> pure (pReq { NH.requestBody = NH.RequestBodyLBS bl }) - ParamBodyFormUrlEncoded form -> pure (pReq { NH.requestBody = NH.RequestBodyLBS (WH.urlEncodeForm form) }) - ParamBodyMultipartFormData parts -> NH.formDataBody parts pReq - - pure (InitRequest outReq) - --- | modify the underlying Request -modifyInitRequest :: InitRequest req contentType res accept -> (NH.Request -> NH.Request) -> InitRequest req contentType res accept -modifyInitRequest (InitRequest req) f = InitRequest (f req) - --- | modify the underlying Request (monadic) -modifyInitRequestM :: Monad m => InitRequest req contentType res accept -> (NH.Request -> m NH.Request) -> m (InitRequest req contentType res accept) -modifyInitRequestM (InitRequest req) f = fmap InitRequest (f req) - --- ** Logging - --- | Run a block using the configured logger instance -runConfigLog - :: P.MonadIO m - => SwaggerPetstoreConfig -> LogExec m -runConfigLog config = configLogExecWithContext config (configLogContext config) - --- | Run a block using the configured logger instance (logs exceptions) -runConfigLogWithExceptions - :: (E.MonadCatch m, P.MonadIO m) - => T.Text -> SwaggerPetstoreConfig -> LogExec m -runConfigLogWithExceptions src config = runConfigLog config . logExceptions src - \ No newline at end of file + -> SwaggerPetstoreRequest req contentType res accept -- ^ request + -> IO (NH.Response BCL.ByteString) -- ^ response +dispatchLbs manager config request = do + initReq <- _toInitRequest config request + dispatchInitUnsafe manager config initReq + +-- ** Mime + +-- | pair of decoded http body and http response +data MimeResult res = + MimeResult { mimeResult :: Either MimeError res -- ^ decoded http body + , mimeResultResponse :: NH.Response BCL.ByteString -- ^ http response + } + deriving (Show, Functor, Foldable, Traversable) + +-- | pair of unrender/parser error and http response +data MimeError = + MimeError { + mimeError :: String -- ^ unrender/parser error + , mimeErrorResponse :: NH.Response BCL.ByteString -- ^ http response + } deriving (Eq, Show) + +-- | send a request returning the 'MimeResult' +dispatchMime + :: forall req contentType res accept. (Produces req accept, MimeUnrender accept res, MimeType contentType) + => NH.Manager -- ^ http-client Connection manager + -> SwaggerPetstoreConfig -- ^ config + -> SwaggerPetstoreRequest req contentType res accept -- ^ request + -> IO (MimeResult res) -- ^ response +dispatchMime manager config request = do + httpResponse <- dispatchLbs manager config request + parsedResult <- + runConfigLogWithExceptions "Client" config $ + do case mimeUnrender (P.Proxy :: P.Proxy accept) (NH.responseBody httpResponse) of + Left s -> do + _log "Client" levelError (T.pack s) + pure (Left (MimeError s httpResponse)) + Right r -> pure (Right r) + return (MimeResult parsedResult httpResponse) + +-- | like 'dispatchMime', but only returns the decoded http body +dispatchMime' + :: (Produces req accept, MimeUnrender accept res, MimeType contentType) + => NH.Manager -- ^ http-client Connection manager + -> SwaggerPetstoreConfig -- ^ config + -> SwaggerPetstoreRequest req contentType res accept -- ^ request + -> IO (Either MimeError res) -- ^ response +dispatchMime' manager config request = do + MimeResult parsedResult _ <- dispatchMime manager config request + return parsedResult + +-- ** Unsafe + +-- | like 'dispatchReqLbs', but does not validate the operation is a 'Producer' of the "accept" 'MimeType'. (Useful if the server's response is undocumented) +dispatchLbsUnsafe + :: (MimeType accept, MimeType contentType) + => NH.Manager -- ^ http-client Connection manager + -> SwaggerPetstoreConfig -- ^ config + -> SwaggerPetstoreRequest req contentType res accept -- ^ request + -> IO (NH.Response BCL.ByteString) -- ^ response +dispatchLbsUnsafe manager config request = do + initReq <- _toInitRequest config request + dispatchInitUnsafe manager config initReq + +-- | dispatch an InitRequest +dispatchInitUnsafe + :: NH.Manager -- ^ http-client Connection manager + -> SwaggerPetstoreConfig -- ^ config + -> InitRequest req contentType res accept -- ^ init request + -> IO (NH.Response BCL.ByteString) -- ^ response +dispatchInitUnsafe manager config (InitRequest req) = do + runConfigLogWithExceptions src config $ + do _log src levelInfo requestLogMsg + _log src levelDebug requestDbgLogMsg + res <- P.liftIO $ NH.httpLbs req manager + _log src levelInfo (responseLogMsg res) + _log src levelDebug ((T.pack . show) res) + return res + where + src = "Client" + endpoint = + T.pack $ + BC.unpack $ + NH.method req <> " " <> NH.host req <> NH.path req <> NH.queryString req + requestLogMsg = "REQ:" <> endpoint + requestDbgLogMsg = + "Headers=" <> (T.pack . show) (NH.requestHeaders req) <> " Body=" <> + (case NH.requestBody req of + NH.RequestBodyLBS xs -> T.decodeUtf8 (BL.toStrict xs) + _ -> "<RequestBody>") + responseStatusCode = (T.pack . show) . NH.statusCode . NH.responseStatus + responseLogMsg res = + "RES:statusCode=" <> responseStatusCode res <> " (" <> endpoint <> ")" + +-- * InitRequest + +-- | wraps an http-client 'Request' with request/response type parameters +newtype InitRequest req contentType res accept = InitRequest + { unInitRequest :: NH.Request + } deriving (Show) + +-- | Build an http-client 'Request' record from the supplied config and request +_toInitRequest + :: (MimeType accept, MimeType contentType) + => SwaggerPetstoreConfig -- ^ config + -> SwaggerPetstoreRequest req contentType res accept -- ^ request + -> IO (InitRequest req contentType res accept) -- ^ initialized request +_toInitRequest config req0 = + runConfigLogWithExceptions "Client" config $ do + parsedReq <- P.liftIO $ NH.parseRequest $ BCL.unpack $ BCL.append (configHost config) (BCL.concat (rUrlPath req0)) + req1 <- P.liftIO $ _applyAuthMethods req0 config + P.when + (configValidateAuthMethods config && (not . null . rAuthTypes) req1) + (E.throw $ AuthMethodException $ "AuthMethod not configured: " <> (show . head . rAuthTypes) req1) + let req2 = req1 & _setContentTypeHeader & _setAcceptHeader + reqHeaders = ("User-Agent", WH.toHeader (configUserAgent config)) : paramsHeaders (rParams req2) + reqQuery = NH.renderQuery True (paramsQuery (rParams req2)) + pReq = parsedReq { NH.method = (rMethod req2) + , NH.requestHeaders = reqHeaders + , NH.queryString = reqQuery + } + outReq <- case paramsBody (rParams req2) of + ParamBodyNone -> pure (pReq { NH.requestBody = mempty }) + ParamBodyB bs -> pure (pReq { NH.requestBody = NH.RequestBodyBS bs }) + ParamBodyBL bl -> pure (pReq { NH.requestBody = NH.RequestBodyLBS bl }) + ParamBodyFormUrlEncoded form -> pure (pReq { NH.requestBody = NH.RequestBodyLBS (WH.urlEncodeForm form) }) + ParamBodyMultipartFormData parts -> NH.formDataBody parts pReq + + pure (InitRequest outReq) + +-- | modify the underlying Request +modifyInitRequest :: InitRequest req contentType res accept -> (NH.Request -> NH.Request) -> InitRequest req contentType res accept +modifyInitRequest (InitRequest req) f = InitRequest (f req) + +-- | modify the underlying Request (monadic) +modifyInitRequestM :: Monad m => InitRequest req contentType res accept -> (NH.Request -> m NH.Request) -> m (InitRequest req contentType res accept) +modifyInitRequestM (InitRequest req) f = fmap InitRequest (f req) + +-- ** Logging + +-- | Run a block using the configured logger instance +runConfigLog + :: P.MonadIO m + => SwaggerPetstoreConfig -> LogExec m +runConfigLog config = configLogExecWithContext config (configLogContext config) + +-- | Run a block using the configured logger instance (logs exceptions) +runConfigLogWithExceptions + :: (E.MonadCatch m, P.MonadIO m) + => T.Text -> SwaggerPetstoreConfig -> LogExec m +runConfigLogWithExceptions src config = runConfigLog config . logExceptions src + \ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.Core.html b/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.Core.html index c170e868212..29399356ae3 100644 --- a/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.Core.html +++ b/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.Core.html @@ -33,501 +33,514 @@ Module : SwaggerPetstore.Core import qualified Control.Arrow as P (left) import qualified Control.DeepSeq as NF -import qualified Data.Aeson as A -import qualified Data.ByteString as B -import qualified Data.ByteString.Base64.Lazy as BL64 -import qualified Data.ByteString.Builder as BB -import qualified Data.ByteString.Char8 as BC -import qualified Data.ByteString.Lazy as BL -import qualified Data.ByteString.Lazy.Char8 as BCL -import qualified Data.CaseInsensitive as CI -import qualified Data.Data as P (Data, Typeable, TypeRep, typeRep) -import qualified Data.Foldable as P -import qualified Data.Ix as P -import qualified Data.Maybe as P -import qualified Data.Proxy as P (Proxy(..)) -import qualified Data.Text as T -import qualified Data.Text.Encoding as T -import qualified Data.Time as TI -import qualified Data.Time.ISO8601 as TI -import qualified GHC.Base as P (Alternative) -import qualified Lens.Micro as L -import qualified Network.HTTP.Client.MultipartFormData as NH -import qualified Network.HTTP.Types as NH -import qualified Prelude as P -import qualified Web.FormUrlEncoded as WH -import qualified Web.HttpApiData as WH -import qualified Text.Printf as T - -import Control.Applicative ((<|>)) -import Control.Applicative (Alternative) -import Data.Function ((&)) -import Data.Foldable(foldlM) -import Data.Monoid ((<>)) -import Data.Text (Text) -import Prelude (($), (.), (<$>), (<*>), Maybe(..), Bool(..), Char, String, fmap, mempty, pure, return, show, IO, Monad, Functor) - --- * SwaggerPetstoreConfig - --- | -data SwaggerPetstoreConfig = SwaggerPetstoreConfig - { configHost :: BCL.ByteString -- ^ host supplied in the Request - , configUserAgent :: Text -- ^ user-agent supplied in the Request - , configLogExecWithContext :: LogExecWithContext -- ^ Run a block using a Logger instance - , configLogContext :: LogContext -- ^ Configures the logger - , configAuthMethods :: [AnyAuthMethod] -- ^ List of configured auth methods - , configValidateAuthMethods :: Bool -- ^ throw exceptions if auth methods are not configured - } - --- | display the config -instance P.Show SwaggerPetstoreConfig where - show c = - T.printf - "{ configHost = %v, configUserAgent = %v, ..}" - (show (configHost c)) - (show (configUserAgent c)) - --- | constructs a default SwaggerPetstoreConfig --- --- configHost: --- --- @http://petstore.swagger.io:80/v2@ --- --- configUserAgent: --- --- @"swagger-haskell-http-client/1.0.0"@ --- -newConfig :: IO SwaggerPetstoreConfig -newConfig = do - logCxt <- initLogContext - return $ SwaggerPetstoreConfig - { configHost = "http://petstore.swagger.io:80/v2" - , configUserAgent = "swagger-haskell-http-client/1.0.0" - , configLogExecWithContext = runDefaultLogExecWithContext - , configLogContext = logCxt - , configAuthMethods = [] - , configValidateAuthMethods = True - } - --- | updates config use AuthMethod on matching requests -addAuthMethod :: AuthMethod auth => SwaggerPetstoreConfig -> auth -> SwaggerPetstoreConfig -addAuthMethod config@SwaggerPetstoreConfig {configAuthMethods = as} a = - config { configAuthMethods = AnyAuthMethod a : as} - --- | updates the config to use stdout logging -withStdoutLogging :: SwaggerPetstoreConfig -> IO SwaggerPetstoreConfig -withStdoutLogging p = do - logCxt <- stdoutLoggingContext (configLogContext p) - return $ p { configLogExecWithContext = stdoutLoggingExec, configLogContext = logCxt } - --- | updates the config to use stderr logging -withStderrLogging :: SwaggerPetstoreConfig -> IO SwaggerPetstoreConfig -withStderrLogging p = do - logCxt <- stderrLoggingContext (configLogContext p) - return $ p { configLogExecWithContext = stderrLoggingExec, configLogContext = logCxt } - --- | updates the config to disable logging -withNoLogging :: SwaggerPetstoreConfig -> SwaggerPetstoreConfig -withNoLogging p = p { configLogExecWithContext = runNullLogExec} - --- * SwaggerPetstoreRequest - --- | Represents a request. The "req" type variable is the request type. The "res" type variable is the response type. -data SwaggerPetstoreRequest req contentType res = SwaggerPetstoreRequest - { rMethod :: NH.Method -- ^ Method of SwaggerPetstoreRequest - , rUrlPath :: [BCL.ByteString] -- ^ Endpoint of SwaggerPetstoreRequest - , rParams :: Params -- ^ params of SwaggerPetstoreRequest - , rAuthTypes :: [P.TypeRep] -- ^ types of auth methods - } - deriving (P.Show) - --- | 'rMethod' Lens -rMethodL :: Lens_' (SwaggerPetstoreRequest req contentType res) NH.Method -rMethodL f SwaggerPetstoreRequest{..} = (\rMethod -> SwaggerPetstoreRequest { rMethod, ..} ) <$> f rMethod -{-# INLINE rMethodL #-} - --- | 'rUrlPath' Lens -rUrlPathL :: Lens_' (SwaggerPetstoreRequest req contentType res) [BCL.ByteString] -rUrlPathL f SwaggerPetstoreRequest{..} = (\rUrlPath -> SwaggerPetstoreRequest { rUrlPath, ..} ) <$> f rUrlPath -{-# INLINE rUrlPathL #-} - --- | 'rParams' Lens -rParamsL :: Lens_' (SwaggerPetstoreRequest req contentType res) Params -rParamsL f SwaggerPetstoreRequest{..} = (\rParams -> SwaggerPetstoreRequest { rParams, ..} ) <$> f rParams -{-# INLINE rParamsL #-} - --- | 'rParams' Lens -rAuthTypesL :: Lens_' (SwaggerPetstoreRequest req contentType res) [P.TypeRep] -rAuthTypesL f SwaggerPetstoreRequest{..} = (\rAuthTypes -> SwaggerPetstoreRequest { rAuthTypes, ..} ) <$> f rAuthTypes -{-# INLINE rAuthTypesL #-} - --- * HasBodyParam - --- | Designates the body parameter of a request -class HasBodyParam req param where - setBodyParam :: forall contentType res. (Consumes req contentType, MimeRender contentType param) => SwaggerPetstoreRequest req contentType res -> param -> SwaggerPetstoreRequest req contentType res - setBodyParam req xs = - req `_setBodyLBS` mimeRender (P.Proxy :: P.Proxy contentType) xs & _setContentTypeHeader +import qualified Control.Exception.Safe as E +import qualified Data.Aeson as A +import qualified Data.ByteString as B +import qualified Data.ByteString.Base64.Lazy as BL64 +import qualified Data.ByteString.Builder as BB +import qualified Data.ByteString.Char8 as BC +import qualified Data.ByteString.Lazy as BL +import qualified Data.ByteString.Lazy.Char8 as BCL +import qualified Data.CaseInsensitive as CI +import qualified Data.Data as P (Data, Typeable, TypeRep, typeRep) +import qualified Data.Foldable as P +import qualified Data.Ix as P +import qualified Data.Maybe as P +import qualified Data.Proxy as P (Proxy(..)) +import qualified Data.Text as T +import qualified Data.Text.Encoding as T +import qualified Data.Time as TI +import qualified Data.Time.ISO8601 as TI +import qualified GHC.Base as P (Alternative) +import qualified Lens.Micro as L +import qualified Network.HTTP.Client.MultipartFormData as NH +import qualified Network.HTTP.Types as NH +import qualified Prelude as P +import qualified Web.FormUrlEncoded as WH +import qualified Web.HttpApiData as WH +import qualified Text.Printf as T + +import Control.Applicative ((<|>)) +import Control.Applicative (Alternative) +import Data.Function ((&)) +import Data.Foldable(foldlM) +import Data.Monoid ((<>)) +import Data.Text (Text) +import Prelude (($), (.), (<$>), (<*>), Maybe(..), Bool(..), Char, String, fmap, mempty, pure, return, show, IO, Monad, Functor) + +-- * SwaggerPetstoreConfig + +-- | +data SwaggerPetstoreConfig = SwaggerPetstoreConfig + { configHost :: BCL.ByteString -- ^ host supplied in the Request + , configUserAgent :: Text -- ^ user-agent supplied in the Request + , configLogExecWithContext :: LogExecWithContext -- ^ Run a block using a Logger instance + , configLogContext :: LogContext -- ^ Configures the logger + , configAuthMethods :: [AnyAuthMethod] -- ^ List of configured auth methods + , configValidateAuthMethods :: Bool -- ^ throw exceptions if auth methods are not configured + } + +-- | display the config +instance P.Show SwaggerPetstoreConfig where + show c = + T.printf + "{ configHost = %v, configUserAgent = %v, ..}" + (show (configHost c)) + (show (configUserAgent c)) + +-- | constructs a default SwaggerPetstoreConfig +-- +-- configHost: +-- +-- @http://petstore.swagger.io:80/v2@ +-- +-- configUserAgent: +-- +-- @"swagger-haskell-http-client/1.0.0"@ +-- +newConfig :: IO SwaggerPetstoreConfig +newConfig = do + logCxt <- initLogContext + return $ SwaggerPetstoreConfig + { configHost = "http://petstore.swagger.io:80/v2" + , configUserAgent = "swagger-haskell-http-client/1.0.0" + , configLogExecWithContext = runDefaultLogExecWithContext + , configLogContext = logCxt + , configAuthMethods = [] + , configValidateAuthMethods = True + } + +-- | updates config use AuthMethod on matching requests +addAuthMethod :: AuthMethod auth => SwaggerPetstoreConfig -> auth -> SwaggerPetstoreConfig +addAuthMethod config@SwaggerPetstoreConfig {configAuthMethods = as} a = + config { configAuthMethods = AnyAuthMethod a : as} + +-- | updates the config to use stdout logging +withStdoutLogging :: SwaggerPetstoreConfig -> IO SwaggerPetstoreConfig +withStdoutLogging p = do + logCxt <- stdoutLoggingContext (configLogContext p) + return $ p { configLogExecWithContext = stdoutLoggingExec, configLogContext = logCxt } + +-- | updates the config to use stderr logging +withStderrLogging :: SwaggerPetstoreConfig -> IO SwaggerPetstoreConfig +withStderrLogging p = do + logCxt <- stderrLoggingContext (configLogContext p) + return $ p { configLogExecWithContext = stderrLoggingExec, configLogContext = logCxt } + +-- | updates the config to disable logging +withNoLogging :: SwaggerPetstoreConfig -> SwaggerPetstoreConfig +withNoLogging p = p { configLogExecWithContext = runNullLogExec} + +-- * SwaggerPetstoreRequest + +-- | Represents a request. +-- +-- Type Variables: +-- +-- * req - request operation +-- * contentType - 'MimeType' associated with request body +-- * res - response model +-- * accept - 'MimeType' associated with response body +data SwaggerPetstoreRequest req contentType res accept = SwaggerPetstoreRequest + { rMethod :: NH.Method -- ^ Method of SwaggerPetstoreRequest + , rUrlPath :: [BCL.ByteString] -- ^ Endpoint of SwaggerPetstoreRequest + , rParams :: Params -- ^ params of SwaggerPetstoreRequest + , rAuthTypes :: [P.TypeRep] -- ^ types of auth methods + } + deriving (P.Show) + +-- | 'rMethod' Lens +rMethodL :: Lens_' (SwaggerPetstoreRequest req contentType res accept) NH.Method +rMethodL f SwaggerPetstoreRequest{..} = (\rMethod -> SwaggerPetstoreRequest { rMethod, ..} ) <$> f rMethod +{-# INLINE rMethodL #-} + +-- | 'rUrlPath' Lens +rUrlPathL :: Lens_' (SwaggerPetstoreRequest req contentType res accept) [BCL.ByteString] +rUrlPathL f SwaggerPetstoreRequest{..} = (\rUrlPath -> SwaggerPetstoreRequest { rUrlPath, ..} ) <$> f rUrlPath +{-# INLINE rUrlPathL #-} + +-- | 'rParams' Lens +rParamsL :: Lens_' (SwaggerPetstoreRequest req contentType res accept) Params +rParamsL f SwaggerPetstoreRequest{..} = (\rParams -> SwaggerPetstoreRequest { rParams, ..} ) <$> f rParams +{-# INLINE rParamsL #-} + +-- | 'rParams' Lens +rAuthTypesL :: Lens_' (SwaggerPetstoreRequest req contentType res accept) [P.TypeRep] +rAuthTypesL f SwaggerPetstoreRequest{..} = (\rAuthTypes -> SwaggerPetstoreRequest { rAuthTypes, ..} ) <$> f rAuthTypes +{-# INLINE rAuthTypesL #-} --- * HasOptionalParam +-- * HasBodyParam --- | Designates the optional parameters of a request -class HasOptionalParam req param where - {-# MINIMAL applyOptionalParam | (-&-) #-} - - -- | Apply an optional parameter to a request - applyOptionalParam :: SwaggerPetstoreRequest req contentType res -> param -> SwaggerPetstoreRequest req contentType res - applyOptionalParam = (-&-) - {-# INLINE applyOptionalParam #-} - - -- | infix operator \/ alias for 'addOptionalParam' - (-&-) :: SwaggerPetstoreRequest req contentType res -> param -> SwaggerPetstoreRequest req contentType res - (-&-) = applyOptionalParam - {-# INLINE (-&-) #-} - -infixl 2 -&- - --- | Request Params -data Params = Params - { paramsQuery :: NH.Query - , paramsHeaders :: NH.RequestHeaders - , paramsBody :: ParamBody - } - deriving (P.Show) +-- | Designates the body parameter of a request +class HasBodyParam req param where + setBodyParam :: forall contentType res accept. (Consumes req contentType, MimeRender contentType param) => SwaggerPetstoreRequest req contentType res accept -> param -> SwaggerPetstoreRequest req contentType res accept + setBodyParam req xs = + req `_setBodyLBS` mimeRender (P.Proxy :: P.Proxy contentType) xs & _setContentTypeHeader + +-- * HasOptionalParam + +-- | Designates the optional parameters of a request +class HasOptionalParam req param where + {-# MINIMAL applyOptionalParam | (-&-) #-} + + -- | Apply an optional parameter to a request + applyOptionalParam :: SwaggerPetstoreRequest req contentType res accept -> param -> SwaggerPetstoreRequest req contentType res accept + applyOptionalParam = (-&-) + {-# INLINE applyOptionalParam #-} + + -- | infix operator \/ alias for 'addOptionalParam' + (-&-) :: SwaggerPetstoreRequest req contentType res accept -> param -> SwaggerPetstoreRequest req contentType res accept + (-&-) = applyOptionalParam + {-# INLINE (-&-) #-} + +infixl 2 -&- --- | 'paramsQuery' Lens -paramsQueryL :: Lens_' Params NH.Query -paramsQueryL f Params{..} = (\paramsQuery -> Params { paramsQuery, ..} ) <$> f paramsQuery -{-# INLINE paramsQueryL #-} - --- | 'paramsHeaders' Lens -paramsHeadersL :: Lens_' Params NH.RequestHeaders -paramsHeadersL f Params{..} = (\paramsHeaders -> Params { paramsHeaders, ..} ) <$> f paramsHeaders -{-# INLINE paramsHeadersL #-} - --- | 'paramsBody' Lens -paramsBodyL :: Lens_' Params ParamBody -paramsBodyL f Params{..} = (\paramsBody -> Params { paramsBody, ..} ) <$> f paramsBody -{-# INLINE paramsBodyL #-} - --- | Request Body -data ParamBody - = ParamBodyNone - | ParamBodyB B.ByteString - | ParamBodyBL BL.ByteString - | ParamBodyFormUrlEncoded WH.Form - | ParamBodyMultipartFormData [NH.Part] - deriving (P.Show) - --- ** SwaggerPetstoreRequest Utils - -_mkRequest :: NH.Method -- ^ Method - -> [BCL.ByteString] -- ^ Endpoint - -> SwaggerPetstoreRequest req contentType res -- ^ req: Request Type, res: Response Type -_mkRequest m u = SwaggerPetstoreRequest m u _mkParams [] - -_mkParams :: Params -_mkParams = Params [] [] ParamBodyNone +-- | Request Params +data Params = Params + { paramsQuery :: NH.Query + , paramsHeaders :: NH.RequestHeaders + , paramsBody :: ParamBody + } + deriving (P.Show) + +-- | 'paramsQuery' Lens +paramsQueryL :: Lens_' Params NH.Query +paramsQueryL f Params{..} = (\paramsQuery -> Params { paramsQuery, ..} ) <$> f paramsQuery +{-# INLINE paramsQueryL #-} + +-- | 'paramsHeaders' Lens +paramsHeadersL :: Lens_' Params NH.RequestHeaders +paramsHeadersL f Params{..} = (\paramsHeaders -> Params { paramsHeaders, ..} ) <$> f paramsHeaders +{-# INLINE paramsHeadersL #-} + +-- | 'paramsBody' Lens +paramsBodyL :: Lens_' Params ParamBody +paramsBodyL f Params{..} = (\paramsBody -> Params { paramsBody, ..} ) <$> f paramsBody +{-# INLINE paramsBodyL #-} + +-- | Request Body +data ParamBody + = ParamBodyNone + | ParamBodyB B.ByteString + | ParamBodyBL BL.ByteString + | ParamBodyFormUrlEncoded WH.Form + | ParamBodyMultipartFormData [NH.Part] + deriving (P.Show) + +-- ** SwaggerPetstoreRequest Utils -setHeader :: SwaggerPetstoreRequest req contentType res -> [NH.Header] -> SwaggerPetstoreRequest req contentType res -setHeader req header = - req `removeHeader` P.fmap P.fst header & - L.over (rParamsL . paramsHeadersL) (header P.++) +_mkRequest :: NH.Method -- ^ Method + -> [BCL.ByteString] -- ^ Endpoint + -> SwaggerPetstoreRequest req contentType res accept -- ^ req: Request Type, res: Response Type +_mkRequest m u = SwaggerPetstoreRequest m u _mkParams [] -removeHeader :: SwaggerPetstoreRequest req contentType res -> [NH.HeaderName] -> SwaggerPetstoreRequest req contentType res -removeHeader req header = - req & - L.over - (rParamsL . paramsHeadersL) - (P.filter (\h -> cifst h `P.notElem` P.fmap CI.mk header)) - where - cifst = CI.mk . P.fst - - -_setContentTypeHeader :: forall req contentType res. MimeType contentType => SwaggerPetstoreRequest req contentType res -> SwaggerPetstoreRequest req contentType res -_setContentTypeHeader req = - case mimeType (P.Proxy :: P.Proxy contentType) of - Just m -> req `setHeader` [("content-type", BC.pack $ P.show m)] - Nothing -> req `removeHeader` ["content-type"] - -_setAcceptHeader :: forall req contentType res accept. MimeType accept => SwaggerPetstoreRequest req contentType res -> accept -> SwaggerPetstoreRequest req contentType res -_setAcceptHeader req accept = - case mimeType' accept of - Just m -> req `setHeader` [("accept", BC.pack $ P.show m)] - Nothing -> req `removeHeader` ["accept"] - -setQuery :: SwaggerPetstoreRequest req contentType res -> [NH.QueryItem] -> SwaggerPetstoreRequest req contentType res -setQuery req query = - req & - L.over - (rParamsL . paramsQueryL) - ((query P.++) . P.filter (\q -> cifst q `P.notElem` P.fmap cifst query)) - where - cifst = CI.mk . P.fst - -addForm :: SwaggerPetstoreRequest req contentType res -> WH.Form -> SwaggerPetstoreRequest req contentType res -addForm req newform = - let form = case paramsBody (rParams req) of - ParamBodyFormUrlEncoded _form -> _form - _ -> mempty - in req & L.set (rParamsL . paramsBodyL) (ParamBodyFormUrlEncoded (newform <> form)) - -_addMultiFormPart :: SwaggerPetstoreRequest req contentType res -> NH.Part -> SwaggerPetstoreRequest req contentType res -_addMultiFormPart req newpart = - let parts = case paramsBody (rParams req) of - ParamBodyMultipartFormData _parts -> _parts - _ -> [] - in req & L.set (rParamsL . paramsBodyL) (ParamBodyMultipartFormData (newpart : parts)) - -_setBodyBS :: SwaggerPetstoreRequest req contentType res -> B.ByteString -> SwaggerPetstoreRequest req contentType res -_setBodyBS req body = - req & L.set (rParamsL . paramsBodyL) (ParamBodyB body) - -_setBodyLBS :: SwaggerPetstoreRequest req contentType res -> BL.ByteString -> SwaggerPetstoreRequest req contentType res -_setBodyLBS req body = - req & L.set (rParamsL . paramsBodyL) (ParamBodyBL body) +_mkParams :: Params +_mkParams = Params [] [] ParamBodyNone + +setHeader :: SwaggerPetstoreRequest req contentType res accept -> [NH.Header] -> SwaggerPetstoreRequest req contentType res accept +setHeader req header = + req `removeHeader` P.fmap P.fst header & + L.over (rParamsL . paramsHeadersL) (header P.++) + +removeHeader :: SwaggerPetstoreRequest req contentType res accept -> [NH.HeaderName] -> SwaggerPetstoreRequest req contentType res accept +removeHeader req header = + req & + L.over + (rParamsL . paramsHeadersL) + (P.filter (\h -> cifst h `P.notElem` P.fmap CI.mk header)) + where + cifst = CI.mk . P.fst + + +_setContentTypeHeader :: forall req contentType res accept. MimeType contentType => SwaggerPetstoreRequest req contentType res accept -> SwaggerPetstoreRequest req contentType res accept +_setContentTypeHeader req = + case mimeType (P.Proxy :: P.Proxy contentType) of + Just m -> req `setHeader` [("content-type", BC.pack $ P.show m)] + Nothing -> req `removeHeader` ["content-type"] + +_setAcceptHeader :: forall req contentType res accept. MimeType accept => SwaggerPetstoreRequest req contentType res accept -> SwaggerPetstoreRequest req contentType res accept +_setAcceptHeader req = + case mimeType (P.Proxy :: P.Proxy accept) of + Just m -> req `setHeader` [("accept", BC.pack $ P.show m)] + Nothing -> req `removeHeader` ["accept"] + +setQuery :: SwaggerPetstoreRequest req contentType res accept -> [NH.QueryItem] -> SwaggerPetstoreRequest req contentType res accept +setQuery req query = + req & + L.over + (rParamsL . paramsQueryL) + ((query P.++) . P.filter (\q -> cifst q `P.notElem` P.fmap cifst query)) + where + cifst = CI.mk . P.fst + +addForm :: SwaggerPetstoreRequest req contentType res accept -> WH.Form -> SwaggerPetstoreRequest req contentType res accept +addForm req newform = + let form = case paramsBody (rParams req) of + ParamBodyFormUrlEncoded _form -> _form + _ -> mempty + in req & L.set (rParamsL . paramsBodyL) (ParamBodyFormUrlEncoded (newform <> form)) + +_addMultiFormPart :: SwaggerPetstoreRequest req contentType res accept -> NH.Part -> SwaggerPetstoreRequest req contentType res accept +_addMultiFormPart req newpart = + let parts = case paramsBody (rParams req) of + ParamBodyMultipartFormData _parts -> _parts + _ -> [] + in req & L.set (rParamsL . paramsBodyL) (ParamBodyMultipartFormData (newpart : parts)) -_hasAuthType :: AuthMethod authMethod => SwaggerPetstoreRequest req contentType res -> P.Proxy authMethod -> SwaggerPetstoreRequest req contentType res -_hasAuthType req proxy = - req & L.over rAuthTypesL (P.typeRep proxy :) +_setBodyBS :: SwaggerPetstoreRequest req contentType res accept -> B.ByteString -> SwaggerPetstoreRequest req contentType res accept +_setBodyBS req body = + req & L.set (rParamsL . paramsBodyL) (ParamBodyB body) --- ** Params Utils - -toPath - :: WH.ToHttpApiData a - => a -> BCL.ByteString -toPath = BB.toLazyByteString . WH.toEncodedUrlPiece - -toHeader :: WH.ToHttpApiData a => (NH.HeaderName, a) -> [NH.Header] -toHeader x = [fmap WH.toHeader x] +_setBodyLBS :: SwaggerPetstoreRequest req contentType res accept -> BL.ByteString -> SwaggerPetstoreRequest req contentType res accept +_setBodyLBS req body = + req & L.set (rParamsL . paramsBodyL) (ParamBodyBL body) + +_hasAuthType :: AuthMethod authMethod => SwaggerPetstoreRequest req contentType res accept -> P.Proxy authMethod -> SwaggerPetstoreRequest req contentType res accept +_hasAuthType req proxy = + req & L.over rAuthTypesL (P.typeRep proxy :) + +-- ** Params Utils -toForm :: WH.ToHttpApiData v => (BC.ByteString, v) -> WH.Form -toForm (k,v) = WH.toForm [(BC.unpack k,v)] - -toQuery :: WH.ToHttpApiData a => (BC.ByteString, Maybe a) -> [NH.QueryItem] -toQuery x = [(fmap . fmap) toQueryParam x] - where toQueryParam = T.encodeUtf8 . WH.toQueryParam - --- *** Swagger `CollectionFormat` Utils - --- | Determines the format of the array if type array is used. -data CollectionFormat - = CommaSeparated -- ^ CSV format for multiple parameters. - | SpaceSeparated -- ^ Also called "SSV" - | TabSeparated -- ^ Also called "TSV" - | PipeSeparated -- ^ `value1|value2|value2` - | MultiParamArray -- ^ Using multiple GET parameters, e.g. `foo=bar&foo=baz`. This is valid only for parameters in "query" ('NH.Query') or "formData" ('WH.Form') +toPath + :: WH.ToHttpApiData a + => a -> BCL.ByteString +toPath = BB.toLazyByteString . WH.toEncodedUrlPiece + +toHeader :: WH.ToHttpApiData a => (NH.HeaderName, a) -> [NH.Header] +toHeader x = [fmap WH.toHeader x] + +toForm :: WH.ToHttpApiData v => (BC.ByteString, v) -> WH.Form +toForm (k,v) = WH.toForm [(BC.unpack k,v)] + +toQuery :: WH.ToHttpApiData a => (BC.ByteString, Maybe a) -> [NH.QueryItem] +toQuery x = [(fmap . fmap) toQueryParam x] + where toQueryParam = T.encodeUtf8 . WH.toQueryParam + +-- *** Swagger `CollectionFormat` Utils -toHeaderColl :: WH.ToHttpApiData a => CollectionFormat -> (NH.HeaderName, [a]) -> [NH.Header] -toHeaderColl c xs = _toColl c toHeader xs - -toFormColl :: WH.ToHttpApiData v => CollectionFormat -> (BC.ByteString, [v]) -> WH.Form -toFormColl c xs = WH.toForm $ fmap unpack $ _toColl c toHeader $ pack xs - where - pack (k,v) = (CI.mk k, v) - unpack (k,v) = (BC.unpack (CI.original k), BC.unpack v) - -toQueryColl :: WH.ToHttpApiData a => CollectionFormat -> (BC.ByteString, Maybe [a]) -> NH.Query -toQueryColl c xs = _toCollA c toQuery xs - -_toColl :: P.Traversable f => CollectionFormat -> (f a -> [(b, BC.ByteString)]) -> f [a] -> [(b, BC.ByteString)] -_toColl c encode xs = fmap (fmap P.fromJust) (_toCollA' c fencode BC.singleton (fmap Just xs)) - where fencode = fmap (fmap Just) . encode . fmap P.fromJust - {-# INLINE fencode #-} +-- | Determines the format of the array if type array is used. +data CollectionFormat + = CommaSeparated -- ^ CSV format for multiple parameters. + | SpaceSeparated -- ^ Also called "SSV" + | TabSeparated -- ^ Also called "TSV" + | PipeSeparated -- ^ `value1|value2|value2` + | MultiParamArray -- ^ Using multiple GET parameters, e.g. `foo=bar&foo=baz`. This is valid only for parameters in "query" ('NH.Query') or "formData" ('WH.Form') + +toHeaderColl :: WH.ToHttpApiData a => CollectionFormat -> (NH.HeaderName, [a]) -> [NH.Header] +toHeaderColl c xs = _toColl c toHeader xs + +toFormColl :: WH.ToHttpApiData v => CollectionFormat -> (BC.ByteString, [v]) -> WH.Form +toFormColl c xs = WH.toForm $ fmap unpack $ _toColl c toHeader $ pack xs + where + pack (k,v) = (CI.mk k, v) + unpack (k,v) = (BC.unpack (CI.original k), BC.unpack v) -_toCollA :: (P.Traversable f, P.Traversable t, P.Alternative t) => CollectionFormat -> (f (t a) -> [(b, t BC.ByteString)]) -> f (t [a]) -> [(b, t BC.ByteString)] -_toCollA c encode xs = _toCollA' c encode BC.singleton xs +toQueryColl :: WH.ToHttpApiData a => CollectionFormat -> (BC.ByteString, Maybe [a]) -> NH.Query +toQueryColl c xs = _toCollA c toQuery xs -_toCollA' :: (P.Monoid c, P.Traversable f, P.Traversable t, P.Alternative t) => CollectionFormat -> (f (t a) -> [(b, t c)]) -> (Char -> c) -> f (t [a]) -> [(b, t c)] -_toCollA' c encode one xs = case c of - CommaSeparated -> go (one ',') - SpaceSeparated -> go (one ' ') - TabSeparated -> go (one '\t') - PipeSeparated -> go (one '|') - MultiParamArray -> expandList - where - go sep = - [P.foldl1 (\(sk, sv) (_, v) -> (sk, (combine sep <$> sv <*> v) <|> sv <|> v)) expandList] - combine sep x y = x <> sep <> y - expandList = (P.concatMap encode . (P.traverse . P.traverse) P.toList) xs - {-# INLINE go #-} - {-# INLINE expandList #-} - {-# INLINE combine #-} - --- * AuthMethods - --- | Provides a method to apply auth methods to requests -class P.Typeable a => - AuthMethod a where - applyAuthMethod - :: SwaggerPetstoreConfig - -> a - -> SwaggerPetstoreRequest req contentType res - -> IO (SwaggerPetstoreRequest req contentType res) - --- | An existential wrapper for any AuthMethod -data AnyAuthMethod = forall a. AuthMethod a => AnyAuthMethod a deriving (P.Typeable) - -instance AuthMethod AnyAuthMethod where applyAuthMethod config (AnyAuthMethod a) req = applyAuthMethod config a req - --- | apply all matching AuthMethods in config to request -_applyAuthMethods - :: SwaggerPetstoreRequest req contentType res - -> SwaggerPetstoreConfig - -> IO (SwaggerPetstoreRequest req contentType res) -_applyAuthMethods req config@(SwaggerPetstoreConfig {configAuthMethods = as}) = - foldlM go req as - where - go r (AnyAuthMethod a) = applyAuthMethod config a r - --- * Utils - --- | Removes Null fields. (OpenAPI-Specification 2.0 does not allow Null in JSON) -_omitNulls :: [(Text, A.Value)] -> A.Value -_omitNulls = A.object . P.filter notNull - where - notNull (_, A.Null) = False - notNull _ = True - --- | Encodes fields using WH.toQueryParam -_toFormItem :: (WH.ToHttpApiData a, Functor f) => t -> f a -> f (t, [Text]) -_toFormItem name x = (name,) . (:[]) . WH.toQueryParam <$> x - --- | Collapse (Just "") to Nothing -_emptyToNothing :: Maybe String -> Maybe String -_emptyToNothing (Just "") = Nothing -_emptyToNothing x = x -{-# INLINE _emptyToNothing #-} - --- | Collapse (Just mempty) to Nothing -_memptyToNothing :: (P.Monoid a, P.Eq a) => Maybe a -> Maybe a -_memptyToNothing (Just x) | x P.== P.mempty = Nothing -_memptyToNothing x = x -{-# INLINE _memptyToNothing #-} - --- * DateTime Formatting - -newtype DateTime = DateTime { unDateTime :: TI.UTCTime } - deriving (P.Eq,P.Data,P.Ord,P.Typeable,NF.NFData,TI.ParseTime,TI.FormatTime) -instance A.FromJSON DateTime where - parseJSON = A.withText "DateTime" (_readDateTime . T.unpack) -instance A.ToJSON DateTime where - toJSON (DateTime t) = A.toJSON (_showDateTime t) -instance WH.FromHttpApiData DateTime where - parseUrlPiece = P.left T.pack . _readDateTime . T.unpack -instance WH.ToHttpApiData DateTime where - toUrlPiece (DateTime t) = T.pack (_showDateTime t) -instance P.Show DateTime where - show (DateTime t) = _showDateTime t -instance MimeRender MimeMultipartFormData DateTime where - mimeRender _ = mimeRenderDefaultMultipartFormData - --- | @_parseISO8601@ -_readDateTime :: (TI.ParseTime t, Monad m, Alternative m) => String -> m t -_readDateTime = - _parseISO8601 -{-# INLINE _readDateTime #-} - --- | @TI.formatISO8601Millis@ -_showDateTime :: (t ~ TI.UTCTime, TI.FormatTime t) => t -> String -_showDateTime = - TI.formatISO8601Millis -{-# INLINE _showDateTime #-} - --- | parse an ISO8601 date-time string -_parseISO8601 :: (TI.ParseTime t, Monad m, Alternative m) => String -> m t -_parseISO8601 t = - P.asum $ - P.flip (TI.parseTimeM True TI.defaultTimeLocale) t <$> - ["%FT%T%QZ", "%FT%T%Q%z", "%FT%T%Q%Z"] -{-# INLINE _parseISO8601 #-} - --- * Date Formatting - -newtype Date = Date { unDate :: TI.Day } - deriving (P.Enum,P.Eq,P.Data,P.Ord,P.Ix,NF.NFData,TI.ParseTime,TI.FormatTime) -instance A.FromJSON Date where - parseJSON = A.withText "Date" (_readDate . T.unpack) -instance A.ToJSON Date where - toJSON (Date t) = A.toJSON (_showDate t) -instance WH.FromHttpApiData Date where - parseUrlPiece = P.left T.pack . _readDate . T.unpack -instance WH.ToHttpApiData Date where - toUrlPiece (Date t) = T.pack (_showDate t) -instance P.Show Date where - show (Date t) = _showDate t -instance MimeRender MimeMultipartFormData Date where - mimeRender _ = mimeRenderDefaultMultipartFormData - --- | @TI.parseTimeM True TI.defaultTimeLocale "%Y-%m-%d"@ -_readDate :: (TI.ParseTime t, Monad m) => String -> m t -_readDate = - TI.parseTimeM True TI.defaultTimeLocale "%Y-%m-%d" -{-# INLINE _readDate #-} - --- | @TI.formatTime TI.defaultTimeLocale "%Y-%m-%d"@ -_showDate :: TI.FormatTime t => t -> String -_showDate = - TI.formatTime TI.defaultTimeLocale "%Y-%m-%d" -{-# INLINE _showDate #-} - --- * Byte/Binary Formatting - - --- | base64 encoded characters -newtype ByteArray = ByteArray { unByteArray :: BL.ByteString } - deriving (P.Eq,P.Data,P.Ord,P.Typeable,NF.NFData) +_toColl :: P.Traversable f => CollectionFormat -> (f a -> [(b, BC.ByteString)]) -> f [a] -> [(b, BC.ByteString)] +_toColl c encode xs = fmap (fmap P.fromJust) (_toCollA' c fencode BC.singleton (fmap Just xs)) + where fencode = fmap (fmap Just) . encode . fmap P.fromJust + {-# INLINE fencode #-} + +_toCollA :: (P.Traversable f, P.Traversable t, P.Alternative t) => CollectionFormat -> (f (t a) -> [(b, t BC.ByteString)]) -> f (t [a]) -> [(b, t BC.ByteString)] +_toCollA c encode xs = _toCollA' c encode BC.singleton xs + +_toCollA' :: (P.Monoid c, P.Traversable f, P.Traversable t, P.Alternative t) => CollectionFormat -> (f (t a) -> [(b, t c)]) -> (Char -> c) -> f (t [a]) -> [(b, t c)] +_toCollA' c encode one xs = case c of + CommaSeparated -> go (one ',') + SpaceSeparated -> go (one ' ') + TabSeparated -> go (one '\t') + PipeSeparated -> go (one '|') + MultiParamArray -> expandList + where + go sep = + [P.foldl1 (\(sk, sv) (_, v) -> (sk, (combine sep <$> sv <*> v) <|> sv <|> v)) expandList] + combine sep x y = x <> sep <> y + expandList = (P.concatMap encode . (P.traverse . P.traverse) P.toList) xs + {-# INLINE go #-} + {-# INLINE expandList #-} + {-# INLINE combine #-} + +-- * AuthMethods + +-- | Provides a method to apply auth methods to requests +class P.Typeable a => + AuthMethod a where + applyAuthMethod + :: SwaggerPetstoreConfig + -> a + -> SwaggerPetstoreRequest req contentType res accept + -> IO (SwaggerPetstoreRequest req contentType res accept) + +-- | An existential wrapper for any AuthMethod +data AnyAuthMethod = forall a. AuthMethod a => AnyAuthMethod a deriving (P.Typeable) + +instance AuthMethod AnyAuthMethod where applyAuthMethod config (AnyAuthMethod a) req = applyAuthMethod config a req + +-- | indicates exceptions related to AuthMethods +data AuthMethodException = AuthMethodException String deriving (P.Show, P.Typeable) + +instance E.Exception AuthMethodException + +-- | apply all matching AuthMethods in config to request +_applyAuthMethods + :: SwaggerPetstoreRequest req contentType res accept + -> SwaggerPetstoreConfig + -> IO (SwaggerPetstoreRequest req contentType res accept) +_applyAuthMethods req config@(SwaggerPetstoreConfig {configAuthMethods = as}) = + foldlM go req as + where + go r (AnyAuthMethod a) = applyAuthMethod config a r + +-- * Utils + +-- | Removes Null fields. (OpenAPI-Specification 2.0 does not allow Null in JSON) +_omitNulls :: [(Text, A.Value)] -> A.Value +_omitNulls = A.object . P.filter notNull + where + notNull (_, A.Null) = False + notNull _ = True + +-- | Encodes fields using WH.toQueryParam +_toFormItem :: (WH.ToHttpApiData a, Functor f) => t -> f a -> f (t, [Text]) +_toFormItem name x = (name,) . (:[]) . WH.toQueryParam <$> x + +-- | Collapse (Just "") to Nothing +_emptyToNothing :: Maybe String -> Maybe String +_emptyToNothing (Just "") = Nothing +_emptyToNothing x = x +{-# INLINE _emptyToNothing #-} + +-- | Collapse (Just mempty) to Nothing +_memptyToNothing :: (P.Monoid a, P.Eq a) => Maybe a -> Maybe a +_memptyToNothing (Just x) | x P.== P.mempty = Nothing +_memptyToNothing x = x +{-# INLINE _memptyToNothing #-} + +-- * DateTime Formatting + +newtype DateTime = DateTime { unDateTime :: TI.UTCTime } + deriving (P.Eq,P.Data,P.Ord,P.Typeable,NF.NFData,TI.ParseTime,TI.FormatTime) +instance A.FromJSON DateTime where + parseJSON = A.withText "DateTime" (_readDateTime . T.unpack) +instance A.ToJSON DateTime where + toJSON (DateTime t) = A.toJSON (_showDateTime t) +instance WH.FromHttpApiData DateTime where + parseUrlPiece = P.left T.pack . _readDateTime . T.unpack +instance WH.ToHttpApiData DateTime where + toUrlPiece (DateTime t) = T.pack (_showDateTime t) +instance P.Show DateTime where + show (DateTime t) = _showDateTime t +instance MimeRender MimeMultipartFormData DateTime where + mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | @_parseISO8601@ +_readDateTime :: (TI.ParseTime t, Monad m, Alternative m) => String -> m t +_readDateTime = + _parseISO8601 +{-# INLINE _readDateTime #-} + +-- | @TI.formatISO8601Millis@ +_showDateTime :: (t ~ TI.UTCTime, TI.FormatTime t) => t -> String +_showDateTime = + TI.formatISO8601Millis +{-# INLINE _showDateTime #-} + +-- | parse an ISO8601 date-time string +_parseISO8601 :: (TI.ParseTime t, Monad m, Alternative m) => String -> m t +_parseISO8601 t = + P.asum $ + P.flip (TI.parseTimeM True TI.defaultTimeLocale) t <$> + ["%FT%T%QZ", "%FT%T%Q%z", "%FT%T%Q%Z"] +{-# INLINE _parseISO8601 #-} + +-- * Date Formatting + +newtype Date = Date { unDate :: TI.Day } + deriving (P.Enum,P.Eq,P.Data,P.Ord,P.Ix,NF.NFData,TI.ParseTime,TI.FormatTime) +instance A.FromJSON Date where + parseJSON = A.withText "Date" (_readDate . T.unpack) +instance A.ToJSON Date where + toJSON (Date t) = A.toJSON (_showDate t) +instance WH.FromHttpApiData Date where + parseUrlPiece = P.left T.pack . _readDate . T.unpack +instance WH.ToHttpApiData Date where + toUrlPiece (Date t) = T.pack (_showDate t) +instance P.Show Date where + show (Date t) = _showDate t +instance MimeRender MimeMultipartFormData Date where + mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | @TI.parseTimeM True TI.defaultTimeLocale "%Y-%m-%d"@ +_readDate :: (TI.ParseTime t, Monad m) => String -> m t +_readDate = + TI.parseTimeM True TI.defaultTimeLocale "%Y-%m-%d" +{-# INLINE _readDate #-} -instance A.FromJSON ByteArray where - parseJSON = A.withText "ByteArray" _readByteArray -instance A.ToJSON ByteArray where - toJSON = A.toJSON . _showByteArray -instance WH.FromHttpApiData ByteArray where - parseUrlPiece = P.left T.pack . _readByteArray -instance WH.ToHttpApiData ByteArray where - toUrlPiece = _showByteArray -instance P.Show ByteArray where - show = T.unpack . _showByteArray -instance MimeRender MimeMultipartFormData ByteArray where - mimeRender _ = mimeRenderDefaultMultipartFormData +-- | @TI.formatTime TI.defaultTimeLocale "%Y-%m-%d"@ +_showDate :: TI.FormatTime t => t -> String +_showDate = + TI.formatTime TI.defaultTimeLocale "%Y-%m-%d" +{-# INLINE _showDate #-} + +-- * Byte/Binary Formatting + + +-- | base64 encoded characters +newtype ByteArray = ByteArray { unByteArray :: BL.ByteString } + deriving (P.Eq,P.Data,P.Ord,P.Typeable,NF.NFData) --- | read base64 encoded characters -_readByteArray :: Monad m => Text -> m ByteArray -_readByteArray = P.either P.fail (pure . ByteArray) . BL64.decode . BL.fromStrict . T.encodeUtf8 -{-# INLINE _readByteArray #-} - --- | show base64 encoded characters -_showByteArray :: ByteArray -> Text -_showByteArray = T.decodeUtf8 . BL.toStrict . BL64.encode . unByteArray -{-# INLINE _showByteArray #-} - --- | any sequence of octets -newtype Binary = Binary { unBinary :: BL.ByteString } - deriving (P.Eq,P.Data,P.Ord,P.Typeable,NF.NFData) - -instance A.FromJSON Binary where - parseJSON = A.withText "Binary" _readBinaryBase64 -instance A.ToJSON Binary where - toJSON = A.toJSON . _showBinaryBase64 -instance WH.FromHttpApiData Binary where - parseUrlPiece = P.left T.pack . _readBinaryBase64 -instance WH.ToHttpApiData Binary where - toUrlPiece = _showBinaryBase64 -instance P.Show Binary where - show = T.unpack . _showBinaryBase64 -instance MimeRender MimeMultipartFormData Binary where - mimeRender _ = unBinary +instance A.FromJSON ByteArray where + parseJSON = A.withText "ByteArray" _readByteArray +instance A.ToJSON ByteArray where + toJSON = A.toJSON . _showByteArray +instance WH.FromHttpApiData ByteArray where + parseUrlPiece = P.left T.pack . _readByteArray +instance WH.ToHttpApiData ByteArray where + toUrlPiece = _showByteArray +instance P.Show ByteArray where + show = T.unpack . _showByteArray +instance MimeRender MimeMultipartFormData ByteArray where + mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | read base64 encoded characters +_readByteArray :: Monad m => Text -> m ByteArray +_readByteArray = P.either P.fail (pure . ByteArray) . BL64.decode . BL.fromStrict . T.encodeUtf8 +{-# INLINE _readByteArray #-} + +-- | show base64 encoded characters +_showByteArray :: ByteArray -> Text +_showByteArray = T.decodeUtf8 . BL.toStrict . BL64.encode . unByteArray +{-# INLINE _showByteArray #-} + +-- | any sequence of octets +newtype Binary = Binary { unBinary :: BL.ByteString } + deriving (P.Eq,P.Data,P.Ord,P.Typeable,NF.NFData) -_readBinaryBase64 :: Monad m => Text -> m Binary -_readBinaryBase64 = P.either P.fail (pure . Binary) . BL64.decode . BL.fromStrict . T.encodeUtf8 -{-# INLINE _readBinaryBase64 #-} - -_showBinaryBase64 :: Binary -> Text -_showBinaryBase64 = T.decodeUtf8 . BL.toStrict . BL64.encode . unBinary -{-# INLINE _showBinaryBase64 #-} - --- * Lens Type Aliases - -type Lens_' s a = Lens_ s s a a -type Lens_ s t a b = forall (f :: * -> *). Functor f => (a -> f b) -> s -> f t - \ No newline at end of file +instance A.FromJSON Binary where + parseJSON = A.withText "Binary" _readBinaryBase64 +instance A.ToJSON Binary where + toJSON = A.toJSON . _showBinaryBase64 +instance WH.FromHttpApiData Binary where + parseUrlPiece = P.left T.pack . _readBinaryBase64 +instance WH.ToHttpApiData Binary where + toUrlPiece = _showBinaryBase64 +instance P.Show Binary where + show = T.unpack . _showBinaryBase64 +instance MimeRender MimeMultipartFormData Binary where + mimeRender _ = unBinary + +_readBinaryBase64 :: Monad m => Text -> m Binary +_readBinaryBase64 = P.either P.fail (pure . Binary) . BL64.decode . BL.fromStrict . T.encodeUtf8 +{-# INLINE _readBinaryBase64 #-} + +_showBinaryBase64 :: Binary -> Text +_showBinaryBase64 = T.decodeUtf8 . BL.toStrict . BL64.encode . unBinary +{-# INLINE _showBinaryBase64 #-} + +-- * Lens Type Aliases + +type Lens_' s a = Lens_ s s a a +type Lens_ s t a b = forall (f :: * -> *). Functor f => (a -> f b) -> s -> f t + \ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.Logging.html b/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.Logging.html index 3db61663db1..a24fdae3d7a 100644 --- a/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.Logging.html +++ b/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.Logging.html @@ -35,11 +35,11 @@ Katip Logging functions -- * Type Aliases (for compatability) -- | Runs a Katip logging block with the Log environment -type LogExecWithContext = forall m. P.MonadIO m => - LogContext -> LogExec m +type LogExecWithContext = forall m. P.MonadIO m => + LogContext -> LogExec m -- | A Katip logging block -type LogExec m = forall a. LG.KatipT m a -> m a +type LogExec m = forall a. LG.KatipT m a -> m a -- | A Katip Log environment type LogContext = LG.LogEnv @@ -65,9 +65,9 @@ Katip Logging functions -- | A Katip Log environment which targets stdout stdoutLoggingContext :: LogContext -> IO LogContext -stdoutLoggingContext cxt = do - handleScribe <- LG.mkHandleScribe LG.ColorIfTerminal IO.stdout LG.InfoS LG.V2 - LG.registerScribe "stdout" handleScribe LG.defaultScribeSettings cxt +stdoutLoggingContext cxt = do + handleScribe <- LG.mkHandleScribe LG.ColorIfTerminal IO.stdout LG.InfoS LG.V2 + LG.registerScribe "stdout" handleScribe LG.defaultScribeSettings cxt -- * stderr logger @@ -77,34 +77,34 @@ Katip Logging functions -- | A Katip Log environment which targets stderr stderrLoggingContext :: LogContext -> IO LogContext -stderrLoggingContext cxt = do - handleScribe <- LG.mkHandleScribe LG.ColorIfTerminal IO.stderr LG.InfoS LG.V2 - LG.registerScribe "stderr" handleScribe LG.defaultScribeSettings cxt +stderrLoggingContext cxt = do + handleScribe <- LG.mkHandleScribe LG.ColorIfTerminal IO.stderr LG.InfoS LG.V2 + LG.registerScribe "stderr" handleScribe LG.defaultScribeSettings cxt -- * Null logger -- | Disables Katip logging runNullLogExec :: LogExecWithContext -runNullLogExec le (LG.KatipT f) = P.runReaderT f (L.set LG.logEnvScribes mempty le) +runNullLogExec le (LG.KatipT f) = P.runReaderT f (L.set LG.logEnvScribes mempty le) -- * Log Msg -- | Log a katip message -_log :: (Applicative m, LG.Katip m) => Text -> LogLevel -> Text -> m () -_log src level msg = do - LG.logMsg (fromString $ T.unpack src) level (LG.logStr msg) +_log :: (Applicative m, LG.Katip m) => Text -> LogLevel -> Text -> m () +_log src level msg = do + LG.logMsg (fromString $ T.unpack src) level (LG.logStr msg) -- * Log Exceptions -- | re-throws exceptions after logging them logExceptions - :: (LG.Katip m, E.MonadCatch m, Applicative m) - => Text -> m a -> m a -logExceptions src = + :: (LG.Katip m, E.MonadCatch m, Applicative m) + => Text -> m a -> m a +logExceptions src = E.handle - (\(e :: E.SomeException) -> do - _log src LG.ErrorS ((T.pack . show) e) - E.throw e) + (\(e :: E.SomeException) -> do + _log src LG.ErrorS ((T.pack . show) e) + E.throw e) -- * Log Level diff --git a/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.MimeTypes.html b/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.MimeTypes.html index 99e0a171a3c..65b6f669651 100644 --- a/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.MimeTypes.html +++ b/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.MimeTypes.html @@ -14,181 +14,190 @@ Module : SwaggerPetstore.MimeTypes -} {-# LANGUAGE ConstraintKinds #-} -{-# LANGUAGE FlexibleContexts #-} -{-# LANGUAGE FlexibleInstances #-} -{-# LANGUAGE MultiParamTypeClasses #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE ScopedTypeVariables #-} -{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-imports #-} - -module SwaggerPetstore.MimeTypes where - -import qualified Control.Arrow as P (left) -import qualified Data.Aeson as A -import qualified Data.ByteString as B -import qualified Data.ByteString.Builder as BB -import qualified Data.ByteString.Char8 as BC -import qualified Data.ByteString.Lazy as BL -import qualified Data.ByteString.Lazy.Char8 as BCL -import qualified Data.Data as P (Typeable) -import qualified Data.Proxy as P (Proxy(..)) -import qualified Data.String as P -import qualified Data.Text as T -import qualified Data.Text.Encoding as T -import qualified Network.HTTP.Media as ME -import qualified Web.FormUrlEncoded as WH -import qualified Web.HttpApiData as WH - -import Prelude (($), (.),(<$>),(<*>),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty) -import qualified Prelude as P - +{-# LANGUAGE ExistentialQuantification #-} +{-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-imports #-} + +module SwaggerPetstore.MimeTypes where + +import qualified Control.Arrow as P (left) +import qualified Data.Aeson as A +import qualified Data.ByteString as B +import qualified Data.ByteString.Builder as BB +import qualified Data.ByteString.Char8 as BC +import qualified Data.ByteString.Lazy as BL +import qualified Data.ByteString.Lazy.Char8 as BCL +import qualified Data.Data as P (Typeable) +import qualified Data.Proxy as P (Proxy(..)) +import qualified Data.String as P +import qualified Data.Text as T +import qualified Data.Text.Encoding as T +import qualified Network.HTTP.Media as ME +import qualified Web.FormUrlEncoded as WH +import qualified Web.HttpApiData as WH + +import Prelude (($), (.),(<$>),(<*>),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty) +import qualified Prelude as P --- * Consumes Class +-- * ContentType MimeType -class MimeType mtype => Consumes req mtype where +data ContentType a = MimeType a => ContentType { unContentType :: a } --- * Produces Class +-- * Accept MimeType -class MimeType mtype => Produces req mtype where +data Accept a = MimeType a => Accept { unAccept :: a } --- * Default Mime Types +-- * Consumes Class -data MimeJSON = MimeJSON deriving (P.Typeable) -data MimeXML = MimeXML deriving (P.Typeable) -data MimePlainText = MimePlainText deriving (P.Typeable) -data MimeFormUrlEncoded = MimeFormUrlEncoded deriving (P.Typeable) -data MimeMultipartFormData = MimeMultipartFormData deriving (P.Typeable) -data MimeOctetStream = MimeOctetStream deriving (P.Typeable) -data MimeNoContent = MimeNoContent deriving (P.Typeable) -data MimeAny = MimeAny deriving (P.Typeable) - --- | A type for responses without content-body. -data NoContent = NoContent - deriving (P.Show, P.Eq, P.Typeable) - - --- * MimeType Class - -class P.Typeable mtype => MimeType mtype where - {-# MINIMAL mimeType | mimeTypes #-} - - mimeTypes :: P.Proxy mtype -> [ME.MediaType] - mimeTypes p = - case mimeType p of - Just x -> [x] - Nothing -> [] - - mimeType :: P.Proxy mtype -> Maybe ME.MediaType - mimeType p = - case mimeTypes p of - [] -> Nothing - (x:_) -> Just x - - mimeType' :: mtype -> Maybe ME.MediaType - mimeType' _ = mimeType (P.Proxy :: P.Proxy mtype) - mimeTypes' :: mtype -> [ME.MediaType] - mimeTypes' _ = mimeTypes (P.Proxy :: P.Proxy mtype) - --- Default MimeType Instances - --- | @application/json; charset=utf-8@ -instance MimeType MimeJSON where - mimeType _ = Just $ P.fromString "application/json" --- | @application/xml; charset=utf-8@ -instance MimeType MimeXML where - mimeType _ = Just $ P.fromString "application/xml" --- | @application/x-www-form-urlencoded@ -instance MimeType MimeFormUrlEncoded where - mimeType _ = Just $ P.fromString "application/x-www-form-urlencoded" --- | @multipart/form-data@ -instance MimeType MimeMultipartFormData where - mimeType _ = Just $ P.fromString "multipart/form-data" --- | @text/plain; charset=utf-8@ -instance MimeType MimePlainText where - mimeType _ = Just $ P.fromString "text/plain" --- | @application/octet-stream@ -instance MimeType MimeOctetStream where - mimeType _ = Just $ P.fromString "application/octet-stream" --- | @"*/*"@ -instance MimeType MimeAny where - mimeType _ = Just $ P.fromString "*/*" -instance MimeType MimeNoContent where - mimeType _ = Nothing - --- * MimeRender Class - -class MimeType mtype => MimeRender mtype x where - mimeRender :: P.Proxy mtype -> x -> BL.ByteString - mimeRender' :: mtype -> x -> BL.ByteString - mimeRender' _ x = mimeRender (P.Proxy :: P.Proxy mtype) x - +class MimeType mtype => Consumes req mtype where + +-- * Produces Class + +class MimeType mtype => Produces req mtype where + +-- * Default Mime Types + +data MimeJSON = MimeJSON deriving (P.Typeable) +data MimeXML = MimeXML deriving (P.Typeable) +data MimePlainText = MimePlainText deriving (P.Typeable) +data MimeFormUrlEncoded = MimeFormUrlEncoded deriving (P.Typeable) +data MimeMultipartFormData = MimeMultipartFormData deriving (P.Typeable) +data MimeOctetStream = MimeOctetStream deriving (P.Typeable) +data MimeNoContent = MimeNoContent deriving (P.Typeable) +data MimeAny = MimeAny deriving (P.Typeable) + +-- | A type for responses without content-body. +data NoContent = NoContent + deriving (P.Show, P.Eq, P.Typeable) + + +-- * MimeType Class + +class P.Typeable mtype => MimeType mtype where + {-# MINIMAL mimeType | mimeTypes #-} + + mimeTypes :: P.Proxy mtype -> [ME.MediaType] + mimeTypes p = + case mimeType p of + Just x -> [x] + Nothing -> [] + + mimeType :: P.Proxy mtype -> Maybe ME.MediaType + mimeType p = + case mimeTypes p of + [] -> Nothing + (x:_) -> Just x + + mimeType' :: mtype -> Maybe ME.MediaType + mimeType' _ = mimeType (P.Proxy :: P.Proxy mtype) + mimeTypes' :: mtype -> [ME.MediaType] + mimeTypes' _ = mimeTypes (P.Proxy :: P.Proxy mtype) + +-- Default MimeType Instances + +-- | @application/json; charset=utf-8@ +instance MimeType MimeJSON where + mimeType _ = Just $ P.fromString "application/json" +-- | @application/xml; charset=utf-8@ +instance MimeType MimeXML where + mimeType _ = Just $ P.fromString "application/xml" +-- | @application/x-www-form-urlencoded@ +instance MimeType MimeFormUrlEncoded where + mimeType _ = Just $ P.fromString "application/x-www-form-urlencoded" +-- | @multipart/form-data@ +instance MimeType MimeMultipartFormData where + mimeType _ = Just $ P.fromString "multipart/form-data" +-- | @text/plain; charset=utf-8@ +instance MimeType MimePlainText where + mimeType _ = Just $ P.fromString "text/plain" +-- | @application/octet-stream@ +instance MimeType MimeOctetStream where + mimeType _ = Just $ P.fromString "application/octet-stream" +-- | @"*/*"@ +instance MimeType MimeAny where + mimeType _ = Just $ P.fromString "*/*" +instance MimeType MimeNoContent where + mimeType _ = Nothing -mimeRenderDefaultMultipartFormData :: WH.ToHttpApiData a => a -> BL.ByteString -mimeRenderDefaultMultipartFormData = BL.fromStrict . T.encodeUtf8 . WH.toQueryParam - --- Default MimeRender Instances - --- | `A.encode` -instance A.ToJSON a => MimeRender MimeJSON a where mimeRender _ = A.encode --- | @WH.urlEncodeAsForm@ -instance WH.ToForm a => MimeRender MimeFormUrlEncoded a where mimeRender _ = WH.urlEncodeAsForm - --- | @P.id@ -instance MimeRender MimePlainText BL.ByteString where mimeRender _ = P.id --- | @BL.fromStrict . T.encodeUtf8@ -instance MimeRender MimePlainText T.Text where mimeRender _ = BL.fromStrict . T.encodeUtf8 --- | @BCL.pack@ -instance MimeRender MimePlainText String where mimeRender _ = BCL.pack - --- | @P.id@ -instance MimeRender MimeOctetStream BL.ByteString where mimeRender _ = P.id --- | @BL.fromStrict . T.encodeUtf8@ -instance MimeRender MimeOctetStream T.Text where mimeRender _ = BL.fromStrict . T.encodeUtf8 --- | @BCL.pack@ -instance MimeRender MimeOctetStream String where mimeRender _ = BCL.pack - -instance MimeRender MimeMultipartFormData BL.ByteString where mimeRender _ = P.id - -instance MimeRender MimeMultipartFormData Bool where mimeRender _ = mimeRenderDefaultMultipartFormData -instance MimeRender MimeMultipartFormData Char where mimeRender _ = mimeRenderDefaultMultipartFormData -instance MimeRender MimeMultipartFormData Double where mimeRender _ = mimeRenderDefaultMultipartFormData -instance MimeRender MimeMultipartFormData Float where mimeRender _ = mimeRenderDefaultMultipartFormData -instance MimeRender MimeMultipartFormData Int where mimeRender _ = mimeRenderDefaultMultipartFormData -instance MimeRender MimeMultipartFormData Integer where mimeRender _ = mimeRenderDefaultMultipartFormData -instance MimeRender MimeMultipartFormData String where mimeRender _ = mimeRenderDefaultMultipartFormData -instance MimeRender MimeMultipartFormData T.Text where mimeRender _ = mimeRenderDefaultMultipartFormData - --- | @P.Right . P.const NoContent@ -instance MimeRender MimeNoContent NoContent where mimeRender _ = P.const BCL.empty - - --- * MimeUnrender Class - -class MimeType mtype => MimeUnrender mtype o where - mimeUnrender :: P.Proxy mtype -> BL.ByteString -> P.Either String o - mimeUnrender' :: mtype -> BL.ByteString -> P.Either String o - mimeUnrender' _ x = mimeUnrender (P.Proxy :: P.Proxy mtype) x +-- * MimeRender Class + +class MimeType mtype => MimeRender mtype x where + mimeRender :: P.Proxy mtype -> x -> BL.ByteString + mimeRender' :: mtype -> x -> BL.ByteString + mimeRender' _ x = mimeRender (P.Proxy :: P.Proxy mtype) x + + +mimeRenderDefaultMultipartFormData :: WH.ToHttpApiData a => a -> BL.ByteString +mimeRenderDefaultMultipartFormData = BL.fromStrict . T.encodeUtf8 . WH.toQueryParam + +-- Default MimeRender Instances + +-- | `A.encode` +instance A.ToJSON a => MimeRender MimeJSON a where mimeRender _ = A.encode +-- | @WH.urlEncodeAsForm@ +instance WH.ToForm a => MimeRender MimeFormUrlEncoded a where mimeRender _ = WH.urlEncodeAsForm + +-- | @P.id@ +instance MimeRender MimePlainText BL.ByteString where mimeRender _ = P.id +-- | @BL.fromStrict . T.encodeUtf8@ +instance MimeRender MimePlainText T.Text where mimeRender _ = BL.fromStrict . T.encodeUtf8 +-- | @BCL.pack@ +instance MimeRender MimePlainText String where mimeRender _ = BCL.pack + +-- | @P.id@ +instance MimeRender MimeOctetStream BL.ByteString where mimeRender _ = P.id +-- | @BL.fromStrict . T.encodeUtf8@ +instance MimeRender MimeOctetStream T.Text where mimeRender _ = BL.fromStrict . T.encodeUtf8 +-- | @BCL.pack@ +instance MimeRender MimeOctetStream String where mimeRender _ = BCL.pack + +instance MimeRender MimeMultipartFormData BL.ByteString where mimeRender _ = P.id + +instance MimeRender MimeMultipartFormData Bool where mimeRender _ = mimeRenderDefaultMultipartFormData +instance MimeRender MimeMultipartFormData Char where mimeRender _ = mimeRenderDefaultMultipartFormData +instance MimeRender MimeMultipartFormData Double where mimeRender _ = mimeRenderDefaultMultipartFormData +instance MimeRender MimeMultipartFormData Float where mimeRender _ = mimeRenderDefaultMultipartFormData +instance MimeRender MimeMultipartFormData Int where mimeRender _ = mimeRenderDefaultMultipartFormData +instance MimeRender MimeMultipartFormData Integer where mimeRender _ = mimeRenderDefaultMultipartFormData +instance MimeRender MimeMultipartFormData String where mimeRender _ = mimeRenderDefaultMultipartFormData +instance MimeRender MimeMultipartFormData T.Text where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | @P.Right . P.const NoContent@ +instance MimeRender MimeNoContent NoContent where mimeRender _ = P.const BCL.empty --- Default MimeUnrender Instances - --- | @A.eitherDecode@ -instance A.FromJSON a => MimeUnrender MimeJSON a where mimeUnrender _ = A.eitherDecode --- | @P.left T.unpack . WH.urlDecodeAsForm@ -instance WH.FromForm a => MimeUnrender MimeFormUrlEncoded a where mimeUnrender _ = P.left T.unpack . WH.urlDecodeAsForm --- | @P.Right . P.id@ + +-- * MimeUnrender Class + +class MimeType mtype => MimeUnrender mtype o where + mimeUnrender :: P.Proxy mtype -> BL.ByteString -> P.Either String o + mimeUnrender' :: mtype -> BL.ByteString -> P.Either String o + mimeUnrender' _ x = mimeUnrender (P.Proxy :: P.Proxy mtype) x -instance MimeUnrender MimePlainText BL.ByteString where mimeUnrender _ = P.Right . P.id --- | @P.left P.show . TL.decodeUtf8'@ -instance MimeUnrender MimePlainText T.Text where mimeUnrender _ = P.left P.show . T.decodeUtf8' . BL.toStrict --- | @P.Right . BCL.unpack@ -instance MimeUnrender MimePlainText String where mimeUnrender _ = P.Right . BCL.unpack - +-- Default MimeUnrender Instances + +-- | @A.eitherDecode@ +instance A.FromJSON a => MimeUnrender MimeJSON a where mimeUnrender _ = A.eitherDecode +-- | @P.left T.unpack . WH.urlDecodeAsForm@ +instance WH.FromForm a => MimeUnrender MimeFormUrlEncoded a where mimeUnrender _ = P.left T.unpack . WH.urlDecodeAsForm -- | @P.Right . P.id@ -instance MimeUnrender MimeOctetStream BL.ByteString where mimeUnrender _ = P.Right . P.id --- | @P.left P.show . T.decodeUtf8' . BL.toStrict@ -instance MimeUnrender MimeOctetStream T.Text where mimeUnrender _ = P.left P.show . T.decodeUtf8' . BL.toStrict --- | @P.Right . BCL.unpack@ -instance MimeUnrender MimeOctetStream String where mimeUnrender _ = P.Right . BCL.unpack - --- | @P.Right . P.const NoContent@ -instance MimeUnrender MimeNoContent NoContent where mimeUnrender _ = P.Right . P.const NoContent \ No newline at end of file + +instance MimeUnrender MimePlainText BL.ByteString where mimeUnrender _ = P.Right . P.id +-- | @P.left P.show . TL.decodeUtf8'@ +instance MimeUnrender MimePlainText T.Text where mimeUnrender _ = P.left P.show . T.decodeUtf8' . BL.toStrict +-- | @P.Right . BCL.unpack@ +instance MimeUnrender MimePlainText String where mimeUnrender _ = P.Right . BCL.unpack + +-- | @P.Right . P.id@ +instance MimeUnrender MimeOctetStream BL.ByteString where mimeUnrender _ = P.Right . P.id +-- | @P.left P.show . T.decodeUtf8' . BL.toStrict@ +instance MimeUnrender MimeOctetStream T.Text where mimeUnrender _ = P.left P.show . T.decodeUtf8' . BL.toStrict +-- | @P.Right . BCL.unpack@ +instance MimeUnrender MimeOctetStream String where mimeUnrender _ = P.Right . BCL.unpack + +-- | @P.Right . P.const NoContent@ +instance MimeUnrender MimeNoContent NoContent where mimeUnrender _ = P.Right . P.const NoContent + \ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.Model.html b/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.Model.html index 8701470671b..bd9353ce6f0 100644 --- a/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.Model.html +++ b/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.Model.html @@ -18,178 +18,178 @@ Module : SwaggerPetstore.Model {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} -{-# LANGUAGE NamedFieldPuns #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE RecordWildCards #-} -{-# LANGUAGE TupleSections #-} -{-# LANGUAGE TypeFamilies #-} -{-# OPTIONS_GHC -fno-warn-unused-matches -fno-warn-unused-binds -fno-warn-unused-imports #-} - -module SwaggerPetstore.Model where +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE RecordWildCards #-} +{-# LANGUAGE TupleSections #-} +{-# LANGUAGE TypeFamilies #-} +{-# OPTIONS_GHC -fno-warn-unused-matches -fno-warn-unused-binds -fno-warn-unused-imports #-} -import SwaggerPetstore.Core +module SwaggerPetstore.Model where -import Data.Aeson ((.:),(.:!),(.:?),(.=)) - -import qualified Data.Aeson as A -import qualified Data.ByteString as B -import qualified Data.ByteString.Lazy as BL -import qualified Data.Data as P (Data, Typeable) -import qualified Data.Foldable as P -import qualified Data.HashMap.Lazy as HM -import qualified Data.Map as Map -import qualified Data.Maybe as P -import qualified Data.Set as Set -import qualified Data.Text as T -import qualified Data.Text.Encoding as T -import qualified Data.Time as TI -import qualified Web.FormUrlEncoded as WH -import qualified Web.HttpApiData as WH - -import Control.Applicative ((<|>)) -import Control.Applicative (Alternative) -import Data.Text (Text) -import Prelude (($), (.),(<$>),(<*>),(>>=),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty,maybe,pure,Monad,Applicative,Functor) - -import qualified Prelude as P - - +import SwaggerPetstore.Core +import SwaggerPetstore.MimeTypes + +import Data.Aeson ((.:),(.:!),(.:?),(.=)) + +import qualified Control.Arrow as P (left) +import qualified Data.Aeson as A +import qualified Data.ByteString as B +import qualified Data.ByteString.Lazy as BL +import qualified Data.Data as P (Data, Typeable) +import qualified Data.Foldable as P +import qualified Data.HashMap.Lazy as HM +import qualified Data.Map as Map +import qualified Data.Maybe as P +import qualified Data.Set as Set +import qualified Data.Text as T +import qualified Data.Text.Encoding as T +import qualified Data.Time as TI +import qualified Web.FormUrlEncoded as WH +import qualified Web.HttpApiData as WH + +import Control.Applicative ((<|>)) +import Control.Applicative (Alternative) +import Data.Text (Text) +import Prelude (($), (.),(<$>),(<*>),(>>=),(=<<),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty,maybe,pure,Monad,Applicative,Functor) --- * Models +import qualified Prelude as P --- ** AdditionalPropertiesClass --- | AdditionalPropertiesClass -data AdditionalPropertiesClass = AdditionalPropertiesClass - { additionalPropertiesClassMapProperty :: !(Maybe (Map.Map String Text)) -- ^ "map_property" - , additionalPropertiesClassMapOfMapProperty :: !(Maybe (Map.Map String (Map.Map String Text))) -- ^ "map_of_map_property" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON AdditionalPropertiesClass -instance A.FromJSON AdditionalPropertiesClass where - parseJSON = A.withObject "AdditionalPropertiesClass" $ \o -> - AdditionalPropertiesClass - <$> (o .:? "map_property") - <*> (o .:? "map_of_map_property") - --- | ToJSON AdditionalPropertiesClass -instance A.ToJSON AdditionalPropertiesClass where - toJSON AdditionalPropertiesClass {..} = - _omitNulls - [ "map_property" .= additionalPropertiesClassMapProperty - , "map_of_map_property" .= additionalPropertiesClassMapOfMapProperty - ] - - --- | Construct a value of type 'AdditionalPropertiesClass' (by applying it's required fields, if any) -mkAdditionalPropertiesClass - :: AdditionalPropertiesClass -mkAdditionalPropertiesClass = - AdditionalPropertiesClass - { additionalPropertiesClassMapProperty = Nothing - , additionalPropertiesClassMapOfMapProperty = Nothing - } - - --- ** Animal --- | Animal -data Animal = Animal - { animalClassName :: !(Text) -- ^ /Required/ "className" - , animalColor :: !(Maybe Text) -- ^ "color" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON Animal -instance A.FromJSON Animal where - parseJSON = A.withObject "Animal" $ \o -> - Animal - <$> (o .: "className") - <*> (o .:? "color") - --- | ToJSON Animal -instance A.ToJSON Animal where - toJSON Animal {..} = - _omitNulls - [ "className" .= animalClassName - , "color" .= animalColor - ] - - --- | Construct a value of type 'Animal' (by applying it's required fields, if any) -mkAnimal - :: Text -- ^ 'animalClassName' - -> Animal -mkAnimal animalClassName = - Animal - { animalClassName - , animalColor = Nothing - } - - --- ** AnimalFarm --- | AnimalFarm -data AnimalFarm = AnimalFarm - { - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON AnimalFarm -instance A.FromJSON AnimalFarm where - parseJSON = A.withObject "AnimalFarm" $ \o -> - pure AnimalFarm - - --- | ToJSON AnimalFarm -instance A.ToJSON AnimalFarm where - toJSON AnimalFarm = - _omitNulls - [ - ] - - --- | Construct a value of type 'AnimalFarm' (by applying it's required fields, if any) -mkAnimalFarm - :: AnimalFarm -mkAnimalFarm = - AnimalFarm - { - } - - --- ** ApiResponse --- | ApiResponse -data ApiResponse = ApiResponse - { apiResponseCode :: !(Maybe Int) -- ^ "code" - , apiResponseType :: !(Maybe Text) -- ^ "type" - , apiResponseMessage :: !(Maybe Text) -- ^ "message" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON ApiResponse -instance A.FromJSON ApiResponse where - parseJSON = A.withObject "ApiResponse" $ \o -> - ApiResponse - <$> (o .:? "code") - <*> (o .:? "type") - <*> (o .:? "message") - --- | ToJSON ApiResponse -instance A.ToJSON ApiResponse where - toJSON ApiResponse {..} = - _omitNulls - [ "code" .= apiResponseCode - , "type" .= apiResponseType - , "message" .= apiResponseMessage - ] - + +-- * Models + + +-- ** AdditionalPropertiesClass +-- | AdditionalPropertiesClass +data AdditionalPropertiesClass = AdditionalPropertiesClass + { additionalPropertiesClassMapProperty :: !(Maybe (Map.Map String Text)) -- ^ "map_property" + , additionalPropertiesClassMapOfMapProperty :: !(Maybe (Map.Map String (Map.Map String Text))) -- ^ "map_of_map_property" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON AdditionalPropertiesClass +instance A.FromJSON AdditionalPropertiesClass where + parseJSON = A.withObject "AdditionalPropertiesClass" $ \o -> + AdditionalPropertiesClass + <$> (o .:? "map_property") + <*> (o .:? "map_of_map_property") + +-- | ToJSON AdditionalPropertiesClass +instance A.ToJSON AdditionalPropertiesClass where + toJSON AdditionalPropertiesClass {..} = + _omitNulls + [ "map_property" .= additionalPropertiesClassMapProperty + , "map_of_map_property" .= additionalPropertiesClassMapOfMapProperty + ] + + +-- | Construct a value of type 'AdditionalPropertiesClass' (by applying it's required fields, if any) +mkAdditionalPropertiesClass + :: AdditionalPropertiesClass +mkAdditionalPropertiesClass = + AdditionalPropertiesClass + { additionalPropertiesClassMapProperty = Nothing + , additionalPropertiesClassMapOfMapProperty = Nothing + } + +-- ** Animal +-- | Animal +data Animal = Animal + { animalClassName :: !(Text) -- ^ /Required/ "className" + , animalColor :: !(Maybe Text) -- ^ "color" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON Animal +instance A.FromJSON Animal where + parseJSON = A.withObject "Animal" $ \o -> + Animal + <$> (o .: "className") + <*> (o .:? "color") + +-- | ToJSON Animal +instance A.ToJSON Animal where + toJSON Animal {..} = + _omitNulls + [ "className" .= animalClassName + , "color" .= animalColor + ] + + +-- | Construct a value of type 'Animal' (by applying it's required fields, if any) +mkAnimal + :: Text -- ^ 'animalClassName' + -> Animal +mkAnimal animalClassName = + Animal + { animalClassName + , animalColor = Nothing + } + +-- ** AnimalFarm +-- | AnimalFarm +data AnimalFarm = AnimalFarm + { + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON AnimalFarm +instance A.FromJSON AnimalFarm where + parseJSON = A.withObject "AnimalFarm" $ \o -> + pure AnimalFarm + + +-- | ToJSON AnimalFarm +instance A.ToJSON AnimalFarm where + toJSON AnimalFarm = + _omitNulls + [ + ] + + +-- | Construct a value of type 'AnimalFarm' (by applying it's required fields, if any) +mkAnimalFarm + :: AnimalFarm +mkAnimalFarm = + AnimalFarm + { + } + +-- ** ApiResponse +-- | ApiResponse +data ApiResponse = ApiResponse + { apiResponseCode :: !(Maybe Int) -- ^ "code" + , apiResponseType :: !(Maybe Text) -- ^ "type" + , apiResponseMessage :: !(Maybe Text) -- ^ "message" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON ApiResponse +instance A.FromJSON ApiResponse where + parseJSON = A.withObject "ApiResponse" $ \o -> + ApiResponse + <$> (o .:? "code") + <*> (o .:? "type") + <*> (o .:? "message") + +-- | ToJSON ApiResponse +instance A.ToJSON ApiResponse where + toJSON ApiResponse {..} = + _omitNulls + [ "code" .= apiResponseCode + , "type" .= apiResponseType + , "message" .= apiResponseMessage + ] --- | Construct a value of type 'ApiResponse' (by applying it's required fields, if any) -mkApiResponse - :: ApiResponse -mkApiResponse = - ApiResponse - { apiResponseCode = Nothing - , apiResponseType = Nothing - , apiResponseMessage = Nothing - } - + +-- | Construct a value of type 'ApiResponse' (by applying it's required fields, if any) +mkApiResponse + :: ApiResponse +mkApiResponse = + ApiResponse + { apiResponseCode = Nothing + , apiResponseType = Nothing + , apiResponseMessage = Nothing + } -- ** ArrayOfArrayOfNumberOnly -- | ArrayOfArrayOfNumberOnly @@ -199,15 +199,15 @@ Module : SwaggerPetstore.Model -- | FromJSON ArrayOfArrayOfNumberOnly instance A.FromJSON ArrayOfArrayOfNumberOnly where - parseJSON = A.withObject "ArrayOfArrayOfNumberOnly" $ \o -> + parseJSON = A.withObject "ArrayOfArrayOfNumberOnly" $ \o -> ArrayOfArrayOfNumberOnly - <$> (o .:? "ArrayArrayNumber") + <$> (o .:? "ArrayArrayNumber") -- | ToJSON ArrayOfArrayOfNumberOnly instance A.ToJSON ArrayOfArrayOfNumberOnly where toJSON ArrayOfArrayOfNumberOnly {..} = _omitNulls - [ "ArrayArrayNumber" .= arrayOfArrayOfNumberOnlyArrayArrayNumber + [ "ArrayArrayNumber" .= arrayOfArrayOfNumberOnlyArrayArrayNumber ] @@ -219,1083 +219,1380 @@ Module : SwaggerPetstore.Model { arrayOfArrayOfNumberOnlyArrayArrayNumber = Nothing } - --- ** ArrayOfNumberOnly --- | ArrayOfNumberOnly -data ArrayOfNumberOnly = ArrayOfNumberOnly - { arrayOfNumberOnlyArrayNumber :: !(Maybe [Double]) -- ^ "ArrayNumber" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON ArrayOfNumberOnly -instance A.FromJSON ArrayOfNumberOnly where - parseJSON = A.withObject "ArrayOfNumberOnly" $ \o -> - ArrayOfNumberOnly - <$> (o .:? "ArrayNumber") - --- | ToJSON ArrayOfNumberOnly -instance A.ToJSON ArrayOfNumberOnly where - toJSON ArrayOfNumberOnly {..} = - _omitNulls - [ "ArrayNumber" .= arrayOfNumberOnlyArrayNumber - ] +-- ** ArrayOfNumberOnly +-- | ArrayOfNumberOnly +data ArrayOfNumberOnly = ArrayOfNumberOnly + { arrayOfNumberOnlyArrayNumber :: !(Maybe [Double]) -- ^ "ArrayNumber" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON ArrayOfNumberOnly +instance A.FromJSON ArrayOfNumberOnly where + parseJSON = A.withObject "ArrayOfNumberOnly" $ \o -> + ArrayOfNumberOnly + <$> (o .:? "ArrayNumber") + +-- | ToJSON ArrayOfNumberOnly +instance A.ToJSON ArrayOfNumberOnly where + toJSON ArrayOfNumberOnly {..} = + _omitNulls + [ "ArrayNumber" .= arrayOfNumberOnlyArrayNumber + ] + - --- | Construct a value of type 'ArrayOfNumberOnly' (by applying it's required fields, if any) -mkArrayOfNumberOnly - :: ArrayOfNumberOnly -mkArrayOfNumberOnly = - ArrayOfNumberOnly - { arrayOfNumberOnlyArrayNumber = Nothing - } - - --- ** ArrayTest --- | ArrayTest -data ArrayTest = ArrayTest - { arrayTestArrayOfString :: !(Maybe [Text]) -- ^ "array_of_string" - , arrayTestArrayArrayOfInteger :: !(Maybe [[Integer]]) -- ^ "array_array_of_integer" - , arrayTestArrayArrayOfModel :: !(Maybe [[ReadOnlyFirst]]) -- ^ "array_array_of_model" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON ArrayTest -instance A.FromJSON ArrayTest where - parseJSON = A.withObject "ArrayTest" $ \o -> - ArrayTest - <$> (o .:? "array_of_string") - <*> (o .:? "array_array_of_integer") - <*> (o .:? "array_array_of_model") - --- | ToJSON ArrayTest -instance A.ToJSON ArrayTest where - toJSON ArrayTest {..} = - _omitNulls - [ "array_of_string" .= arrayTestArrayOfString - , "array_array_of_integer" .= arrayTestArrayArrayOfInteger - , "array_array_of_model" .= arrayTestArrayArrayOfModel - ] - - --- | Construct a value of type 'ArrayTest' (by applying it's required fields, if any) -mkArrayTest - :: ArrayTest -mkArrayTest = - ArrayTest - { arrayTestArrayOfString = Nothing - , arrayTestArrayArrayOfInteger = Nothing - , arrayTestArrayArrayOfModel = Nothing - } - - --- ** Capitalization --- | Capitalization -data Capitalization = Capitalization - { capitalizationSmallCamel :: !(Maybe Text) -- ^ "smallCamel" - , capitalizationCapitalCamel :: !(Maybe Text) -- ^ "CapitalCamel" - , capitalizationSmallSnake :: !(Maybe Text) -- ^ "small_Snake" - , capitalizationCapitalSnake :: !(Maybe Text) -- ^ "Capital_Snake" - , capitalizationScaEthFlowPoints :: !(Maybe Text) -- ^ "SCA_ETH_Flow_Points" - , capitalizationAttName :: !(Maybe Text) -- ^ "ATT_NAME" - Name of the pet - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON Capitalization -instance A.FromJSON Capitalization where - parseJSON = A.withObject "Capitalization" $ \o -> - Capitalization - <$> (o .:? "smallCamel") - <*> (o .:? "CapitalCamel") - <*> (o .:? "small_Snake") - <*> (o .:? "Capital_Snake") - <*> (o .:? "SCA_ETH_Flow_Points") - <*> (o .:? "ATT_NAME") - --- | ToJSON Capitalization -instance A.ToJSON Capitalization where - toJSON Capitalization {..} = - _omitNulls - [ "smallCamel" .= capitalizationSmallCamel - , "CapitalCamel" .= capitalizationCapitalCamel - , "small_Snake" .= capitalizationSmallSnake - , "Capital_Snake" .= capitalizationCapitalSnake - , "SCA_ETH_Flow_Points" .= capitalizationScaEthFlowPoints - , "ATT_NAME" .= capitalizationAttName - ] - - --- | Construct a value of type 'Capitalization' (by applying it's required fields, if any) -mkCapitalization - :: Capitalization -mkCapitalization = - Capitalization - { capitalizationSmallCamel = Nothing - , capitalizationCapitalCamel = Nothing - , capitalizationSmallSnake = Nothing - , capitalizationCapitalSnake = Nothing - , capitalizationScaEthFlowPoints = Nothing - , capitalizationAttName = Nothing - } - - --- ** Category --- | Category -data Category = Category - { categoryId :: !(Maybe Integer) -- ^ "id" - , categoryName :: !(Maybe Text) -- ^ "name" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON Category -instance A.FromJSON Category where - parseJSON = A.withObject "Category" $ \o -> - Category - <$> (o .:? "id") - <*> (o .:? "name") - --- | ToJSON Category -instance A.ToJSON Category where - toJSON Category {..} = - _omitNulls - [ "id" .= categoryId - , "name" .= categoryName - ] - - --- | Construct a value of type 'Category' (by applying it's required fields, if any) -mkCategory - :: Category -mkCategory = - Category - { categoryId = Nothing - , categoryName = Nothing - } - - --- ** ClassModel --- | ClassModel --- Model for testing model with \"_class\" property -data ClassModel = ClassModel - { classModelClass :: !(Maybe Text) -- ^ "_class" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON ClassModel -instance A.FromJSON ClassModel where - parseJSON = A.withObject "ClassModel" $ \o -> - ClassModel - <$> (o .:? "_class") - --- | ToJSON ClassModel -instance A.ToJSON ClassModel where - toJSON ClassModel {..} = - _omitNulls - [ "_class" .= classModelClass - ] - - --- | Construct a value of type 'ClassModel' (by applying it's required fields, if any) -mkClassModel - :: ClassModel -mkClassModel = - ClassModel - { classModelClass = Nothing - } - +-- | Construct a value of type 'ArrayOfNumberOnly' (by applying it's required fields, if any) +mkArrayOfNumberOnly + :: ArrayOfNumberOnly +mkArrayOfNumberOnly = + ArrayOfNumberOnly + { arrayOfNumberOnlyArrayNumber = Nothing + } + +-- ** ArrayTest +-- | ArrayTest +data ArrayTest = ArrayTest + { arrayTestArrayOfString :: !(Maybe [Text]) -- ^ "array_of_string" + , arrayTestArrayArrayOfInteger :: !(Maybe [[Integer]]) -- ^ "array_array_of_integer" + , arrayTestArrayArrayOfModel :: !(Maybe [[ReadOnlyFirst]]) -- ^ "array_array_of_model" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON ArrayTest +instance A.FromJSON ArrayTest where + parseJSON = A.withObject "ArrayTest" $ \o -> + ArrayTest + <$> (o .:? "array_of_string") + <*> (o .:? "array_array_of_integer") + <*> (o .:? "array_array_of_model") + +-- | ToJSON ArrayTest +instance A.ToJSON ArrayTest where + toJSON ArrayTest {..} = + _omitNulls + [ "array_of_string" .= arrayTestArrayOfString + , "array_array_of_integer" .= arrayTestArrayArrayOfInteger + , "array_array_of_model" .= arrayTestArrayArrayOfModel + ] + + +-- | Construct a value of type 'ArrayTest' (by applying it's required fields, if any) +mkArrayTest + :: ArrayTest +mkArrayTest = + ArrayTest + { arrayTestArrayOfString = Nothing + , arrayTestArrayArrayOfInteger = Nothing + , arrayTestArrayArrayOfModel = Nothing + } + +-- ** Capitalization +-- | Capitalization +data Capitalization = Capitalization + { capitalizationSmallCamel :: !(Maybe Text) -- ^ "smallCamel" + , capitalizationCapitalCamel :: !(Maybe Text) -- ^ "CapitalCamel" + , capitalizationSmallSnake :: !(Maybe Text) -- ^ "small_Snake" + , capitalizationCapitalSnake :: !(Maybe Text) -- ^ "Capital_Snake" + , capitalizationScaEthFlowPoints :: !(Maybe Text) -- ^ "SCA_ETH_Flow_Points" + , capitalizationAttName :: !(Maybe Text) -- ^ "ATT_NAME" - Name of the pet + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON Capitalization +instance A.FromJSON Capitalization where + parseJSON = A.withObject "Capitalization" $ \o -> + Capitalization + <$> (o .:? "smallCamel") + <*> (o .:? "CapitalCamel") + <*> (o .:? "small_Snake") + <*> (o .:? "Capital_Snake") + <*> (o .:? "SCA_ETH_Flow_Points") + <*> (o .:? "ATT_NAME") + +-- | ToJSON Capitalization +instance A.ToJSON Capitalization where + toJSON Capitalization {..} = + _omitNulls + [ "smallCamel" .= capitalizationSmallCamel + , "CapitalCamel" .= capitalizationCapitalCamel + , "small_Snake" .= capitalizationSmallSnake + , "Capital_Snake" .= capitalizationCapitalSnake + , "SCA_ETH_Flow_Points" .= capitalizationScaEthFlowPoints + , "ATT_NAME" .= capitalizationAttName + ] + + +-- | Construct a value of type 'Capitalization' (by applying it's required fields, if any) +mkCapitalization + :: Capitalization +mkCapitalization = + Capitalization + { capitalizationSmallCamel = Nothing + , capitalizationCapitalCamel = Nothing + , capitalizationSmallSnake = Nothing + , capitalizationCapitalSnake = Nothing + , capitalizationScaEthFlowPoints = Nothing + , capitalizationAttName = Nothing + } + +-- ** Category +-- | Category +data Category = Category + { categoryId :: !(Maybe Integer) -- ^ "id" + , categoryName :: !(Maybe Text) -- ^ "name" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON Category +instance A.FromJSON Category where + parseJSON = A.withObject "Category" $ \o -> + Category + <$> (o .:? "id") + <*> (o .:? "name") + +-- | ToJSON Category +instance A.ToJSON Category where + toJSON Category {..} = + _omitNulls + [ "id" .= categoryId + , "name" .= categoryName + ] + + +-- | Construct a value of type 'Category' (by applying it's required fields, if any) +mkCategory + :: Category +mkCategory = + Category + { categoryId = Nothing + , categoryName = Nothing + } + +-- ** ClassModel +-- | ClassModel +-- Model for testing model with \"_class\" property +data ClassModel = ClassModel + { classModelClass :: !(Maybe Text) -- ^ "_class" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON ClassModel +instance A.FromJSON ClassModel where + parseJSON = A.withObject "ClassModel" $ \o -> + ClassModel + <$> (o .:? "_class") + +-- | ToJSON ClassModel +instance A.ToJSON ClassModel where + toJSON ClassModel {..} = + _omitNulls + [ "_class" .= classModelClass + ] + + +-- | Construct a value of type 'ClassModel' (by applying it's required fields, if any) +mkClassModel + :: ClassModel +mkClassModel = + ClassModel + { classModelClass = Nothing + } + +-- ** Client +-- | Client +data Client = Client + { clientClient :: !(Maybe Text) -- ^ "client" + } deriving (P.Show, P.Eq, P.Typeable) --- ** Client --- | Client -data Client = Client - { clientClient :: !(Maybe Text) -- ^ "client" - } deriving (P.Show, P.Eq, P.Typeable) +-- | FromJSON Client +instance A.FromJSON Client where + parseJSON = A.withObject "Client" $ \o -> + Client + <$> (o .:? "client") --- | FromJSON Client -instance A.FromJSON Client where - parseJSON = A.withObject "Client" $ \o -> - Client - <$> (o .:? "client") - --- | ToJSON Client -instance A.ToJSON Client where - toJSON Client {..} = - _omitNulls - [ "client" .= clientClient - ] - - --- | Construct a value of type 'Client' (by applying it's required fields, if any) -mkClient - :: Client -mkClient = - Client - { clientClient = Nothing - } - +-- | ToJSON Client +instance A.ToJSON Client where + toJSON Client {..} = + _omitNulls + [ "client" .= clientClient + ] + + +-- | Construct a value of type 'Client' (by applying it's required fields, if any) +mkClient + :: Client +mkClient = + Client + { clientClient = Nothing + } + +-- ** EnumArrays +-- | EnumArrays +data EnumArrays = EnumArrays + { enumArraysJustSymbol :: !(Maybe E'JustSymbol) -- ^ "just_symbol" + , enumArraysArrayEnum :: !(Maybe [E'ArrayEnum]) -- ^ "array_enum" + } deriving (P.Show, P.Eq, P.Typeable) --- ** EnumArrays --- | EnumArrays -data EnumArrays = EnumArrays - { enumArraysJustSymbol :: !(Maybe Text) -- ^ "just_symbol" - , enumArraysArrayEnum :: !(Maybe [Text]) -- ^ "array_enum" - } deriving (P.Show, P.Eq, P.Typeable) +-- | FromJSON EnumArrays +instance A.FromJSON EnumArrays where + parseJSON = A.withObject "EnumArrays" $ \o -> + EnumArrays + <$> (o .:? "just_symbol") + <*> (o .:? "array_enum") --- | FromJSON EnumArrays -instance A.FromJSON EnumArrays where - parseJSON = A.withObject "EnumArrays" $ \o -> - EnumArrays - <$> (o .:? "just_symbol") - <*> (o .:? "array_enum") - --- | ToJSON EnumArrays -instance A.ToJSON EnumArrays where - toJSON EnumArrays {..} = - _omitNulls - [ "just_symbol" .= enumArraysJustSymbol - , "array_enum" .= enumArraysArrayEnum - ] - - --- | Construct a value of type 'EnumArrays' (by applying it's required fields, if any) -mkEnumArrays - :: EnumArrays -mkEnumArrays = - EnumArrays - { enumArraysJustSymbol = Nothing - , enumArraysArrayEnum = Nothing - } - - --- ** EnumClass --- | EnumClass -data EnumClass = EnumClass - { - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON EnumClass -instance A.FromJSON EnumClass where - parseJSON = A.withObject "EnumClass" $ \o -> - pure EnumClass - - --- | ToJSON EnumClass -instance A.ToJSON EnumClass where - toJSON EnumClass = - _omitNulls - [ - ] - +-- | ToJSON EnumArrays +instance A.ToJSON EnumArrays where + toJSON EnumArrays {..} = + _omitNulls + [ "just_symbol" .= enumArraysJustSymbol + , "array_enum" .= enumArraysArrayEnum + ] + + +-- | Construct a value of type 'EnumArrays' (by applying it's required fields, if any) +mkEnumArrays + :: EnumArrays +mkEnumArrays = + EnumArrays + { enumArraysJustSymbol = Nothing + , enumArraysArrayEnum = Nothing + } + +-- ** EnumTest +-- | EnumTest +data EnumTest = EnumTest + { enumTestEnumString :: !(Maybe E'EnumString) -- ^ "enum_string" + , enumTestEnumInteger :: !(Maybe E'EnumInteger) -- ^ "enum_integer" + , enumTestEnumNumber :: !(Maybe E'EnumNumber) -- ^ "enum_number" + , enumTestOuterEnum :: !(Maybe OuterEnum) -- ^ "outerEnum" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON EnumTest +instance A.FromJSON EnumTest where + parseJSON = A.withObject "EnumTest" $ \o -> + EnumTest + <$> (o .:? "enum_string") + <*> (o .:? "enum_integer") + <*> (o .:? "enum_number") + <*> (o .:? "outerEnum") + +-- | ToJSON EnumTest +instance A.ToJSON EnumTest where + toJSON EnumTest {..} = + _omitNulls + [ "enum_string" .= enumTestEnumString + , "enum_integer" .= enumTestEnumInteger + , "enum_number" .= enumTestEnumNumber + , "outerEnum" .= enumTestOuterEnum + ] --- | Construct a value of type 'EnumClass' (by applying it's required fields, if any) -mkEnumClass - :: EnumClass -mkEnumClass = - EnumClass - { - } - - --- ** EnumTest --- | EnumTest -data EnumTest = EnumTest - { enumTestEnumString :: !(Maybe Text) -- ^ "enum_string" - , enumTestEnumInteger :: !(Maybe Int) -- ^ "enum_integer" - , enumTestEnumNumber :: !(Maybe Double) -- ^ "enum_number" - , enumTestOuterEnum :: !(Maybe OuterEnum) -- ^ "outerEnum" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON EnumTest -instance A.FromJSON EnumTest where - parseJSON = A.withObject "EnumTest" $ \o -> - EnumTest - <$> (o .:? "enum_string") - <*> (o .:? "enum_integer") - <*> (o .:? "enum_number") - <*> (o .:? "outerEnum") - --- | ToJSON EnumTest -instance A.ToJSON EnumTest where - toJSON EnumTest {..} = - _omitNulls - [ "enum_string" .= enumTestEnumString - , "enum_integer" .= enumTestEnumInteger - , "enum_number" .= enumTestEnumNumber - , "outerEnum" .= enumTestOuterEnum - ] - - --- | Construct a value of type 'EnumTest' (by applying it's required fields, if any) -mkEnumTest - :: EnumTest -mkEnumTest = - EnumTest - { enumTestEnumString = Nothing - , enumTestEnumInteger = Nothing - , enumTestEnumNumber = Nothing - , enumTestOuterEnum = Nothing - } - - --- ** FormatTest --- | FormatTest -data FormatTest = FormatTest - { formatTestInteger :: !(Maybe Int) -- ^ "integer" - , formatTestInt32 :: !(Maybe Int) -- ^ "int32" - , formatTestInt64 :: !(Maybe Integer) -- ^ "int64" - , formatTestNumber :: !(Double) -- ^ /Required/ "number" - , formatTestFloat :: !(Maybe Float) -- ^ "float" - , formatTestDouble :: !(Maybe Double) -- ^ "double" - , formatTestString :: !(Maybe Text) -- ^ "string" - , formatTestByte :: !(ByteArray) -- ^ /Required/ "byte" - , formatTestBinary :: !(Maybe Binary) -- ^ "binary" - , formatTestDate :: !(Date) -- ^ /Required/ "date" - , formatTestDateTime :: !(Maybe DateTime) -- ^ "dateTime" - , formatTestUuid :: !(Maybe Text) -- ^ "uuid" - , formatTestPassword :: !(Text) -- ^ /Required/ "password" - } deriving (P.Show, P.Eq, P.Typeable) + +-- | Construct a value of type 'EnumTest' (by applying it's required fields, if any) +mkEnumTest + :: EnumTest +mkEnumTest = + EnumTest + { enumTestEnumString = Nothing + , enumTestEnumInteger = Nothing + , enumTestEnumNumber = Nothing + , enumTestOuterEnum = Nothing + } + +-- ** FormatTest +-- | FormatTest +data FormatTest = FormatTest + { formatTestInteger :: !(Maybe Int) -- ^ "integer" + , formatTestInt32 :: !(Maybe Int) -- ^ "int32" + , formatTestInt64 :: !(Maybe Integer) -- ^ "int64" + , formatTestNumber :: !(Double) -- ^ /Required/ "number" + , formatTestFloat :: !(Maybe Float) -- ^ "float" + , formatTestDouble :: !(Maybe Double) -- ^ "double" + , formatTestString :: !(Maybe Text) -- ^ "string" + , formatTestByte :: !(ByteArray) -- ^ /Required/ "byte" + , formatTestBinary :: !(Maybe Binary) -- ^ "binary" + , formatTestDate :: !(Date) -- ^ /Required/ "date" + , formatTestDateTime :: !(Maybe DateTime) -- ^ "dateTime" + , formatTestUuid :: !(Maybe Text) -- ^ "uuid" + , formatTestPassword :: !(Text) -- ^ /Required/ "password" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON FormatTest +instance A.FromJSON FormatTest where + parseJSON = A.withObject "FormatTest" $ \o -> + FormatTest + <$> (o .:? "integer") + <*> (o .:? "int32") + <*> (o .:? "int64") + <*> (o .: "number") + <*> (o .:? "float") + <*> (o .:? "double") + <*> (o .:? "string") + <*> (o .: "byte") + <*> (o .:? "binary") + <*> (o .: "date") + <*> (o .:? "dateTime") + <*> (o .:? "uuid") + <*> (o .: "password") + +-- | ToJSON FormatTest +instance A.ToJSON FormatTest where + toJSON FormatTest {..} = + _omitNulls + [ "integer" .= formatTestInteger + , "int32" .= formatTestInt32 + , "int64" .= formatTestInt64 + , "number" .= formatTestNumber + , "float" .= formatTestFloat + , "double" .= formatTestDouble + , "string" .= formatTestString + , "byte" .= formatTestByte + , "binary" .= formatTestBinary + , "date" .= formatTestDate + , "dateTime" .= formatTestDateTime + , "uuid" .= formatTestUuid + , "password" .= formatTestPassword + ] + --- | FromJSON FormatTest -instance A.FromJSON FormatTest where - parseJSON = A.withObject "FormatTest" $ \o -> - FormatTest - <$> (o .:? "integer") - <*> (o .:? "int32") - <*> (o .:? "int64") - <*> (o .: "number") - <*> (o .:? "float") - <*> (o .:? "double") - <*> (o .:? "string") - <*> (o .: "byte") - <*> (o .:? "binary") - <*> (o .: "date") - <*> (o .:? "dateTime") - <*> (o .:? "uuid") - <*> (o .: "password") - --- | ToJSON FormatTest -instance A.ToJSON FormatTest where - toJSON FormatTest {..} = - _omitNulls - [ "integer" .= formatTestInteger - , "int32" .= formatTestInt32 - , "int64" .= formatTestInt64 - , "number" .= formatTestNumber - , "float" .= formatTestFloat - , "double" .= formatTestDouble - , "string" .= formatTestString - , "byte" .= formatTestByte - , "binary" .= formatTestBinary - , "date" .= formatTestDate - , "dateTime" .= formatTestDateTime - , "uuid" .= formatTestUuid - , "password" .= formatTestPassword - ] - +-- | Construct a value of type 'FormatTest' (by applying it's required fields, if any) +mkFormatTest + :: Double -- ^ 'formatTestNumber' + -> ByteArray -- ^ 'formatTestByte' + -> Date -- ^ 'formatTestDate' + -> Text -- ^ 'formatTestPassword' + -> FormatTest +mkFormatTest formatTestNumber formatTestByte formatTestDate formatTestPassword = + FormatTest + { formatTestInteger = Nothing + , formatTestInt32 = Nothing + , formatTestInt64 = Nothing + , formatTestNumber + , formatTestFloat = Nothing + , formatTestDouble = Nothing + , formatTestString = Nothing + , formatTestByte + , formatTestBinary = Nothing + , formatTestDate + , formatTestDateTime = Nothing + , formatTestUuid = Nothing + , formatTestPassword + } + +-- ** HasOnlyReadOnly +-- | HasOnlyReadOnly +data HasOnlyReadOnly = HasOnlyReadOnly + { hasOnlyReadOnlyBar :: !(Maybe Text) -- ^ "bar" + , hasOnlyReadOnlyFoo :: !(Maybe Text) -- ^ "foo" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON HasOnlyReadOnly +instance A.FromJSON HasOnlyReadOnly where + parseJSON = A.withObject "HasOnlyReadOnly" $ \o -> + HasOnlyReadOnly + <$> (o .:? "bar") + <*> (o .:? "foo") --- | Construct a value of type 'FormatTest' (by applying it's required fields, if any) -mkFormatTest - :: Double -- ^ 'formatTestNumber' - -> ByteArray -- ^ 'formatTestByte' - -> Date -- ^ 'formatTestDate' - -> Text -- ^ 'formatTestPassword' - -> FormatTest -mkFormatTest formatTestNumber formatTestByte formatTestDate formatTestPassword = - FormatTest - { formatTestInteger = Nothing - , formatTestInt32 = Nothing - , formatTestInt64 = Nothing - , formatTestNumber - , formatTestFloat = Nothing - , formatTestDouble = Nothing - , formatTestString = Nothing - , formatTestByte - , formatTestBinary = Nothing - , formatTestDate - , formatTestDateTime = Nothing - , formatTestUuid = Nothing - , formatTestPassword - } - +-- | ToJSON HasOnlyReadOnly +instance A.ToJSON HasOnlyReadOnly where + toJSON HasOnlyReadOnly {..} = + _omitNulls + [ "bar" .= hasOnlyReadOnlyBar + , "foo" .= hasOnlyReadOnlyFoo + ] + + +-- | Construct a value of type 'HasOnlyReadOnly' (by applying it's required fields, if any) +mkHasOnlyReadOnly + :: HasOnlyReadOnly +mkHasOnlyReadOnly = + HasOnlyReadOnly + { hasOnlyReadOnlyBar = Nothing + , hasOnlyReadOnlyFoo = Nothing + } + +-- ** MapTest +-- | MapTest +data MapTest = MapTest + { mapTestMapMapOfString :: !(Maybe (Map.Map String (Map.Map String Text))) -- ^ "map_map_of_string" + , mapTestMapOfEnumString :: !(Maybe (Map.Map String E'Inner)) -- ^ "map_of_enum_string" + } deriving (P.Show, P.Eq, P.Typeable) --- ** HasOnlyReadOnly --- | HasOnlyReadOnly -data HasOnlyReadOnly = HasOnlyReadOnly - { hasOnlyReadOnlyBar :: !(Maybe Text) -- ^ "bar" - , hasOnlyReadOnlyFoo :: !(Maybe Text) -- ^ "foo" - } deriving (P.Show, P.Eq, P.Typeable) +-- | FromJSON MapTest +instance A.FromJSON MapTest where + parseJSON = A.withObject "MapTest" $ \o -> + MapTest + <$> (o .:? "map_map_of_string") + <*> (o .:? "map_of_enum_string") --- | FromJSON HasOnlyReadOnly -instance A.FromJSON HasOnlyReadOnly where - parseJSON = A.withObject "HasOnlyReadOnly" $ \o -> - HasOnlyReadOnly - <$> (o .:? "bar") - <*> (o .:? "foo") - --- | ToJSON HasOnlyReadOnly -instance A.ToJSON HasOnlyReadOnly where - toJSON HasOnlyReadOnly {..} = - _omitNulls - [ "bar" .= hasOnlyReadOnlyBar - , "foo" .= hasOnlyReadOnlyFoo - ] - - --- | Construct a value of type 'HasOnlyReadOnly' (by applying it's required fields, if any) -mkHasOnlyReadOnly - :: HasOnlyReadOnly -mkHasOnlyReadOnly = - HasOnlyReadOnly - { hasOnlyReadOnlyBar = Nothing - , hasOnlyReadOnlyFoo = Nothing - } - +-- | ToJSON MapTest +instance A.ToJSON MapTest where + toJSON MapTest {..} = + _omitNulls + [ "map_map_of_string" .= mapTestMapMapOfString + , "map_of_enum_string" .= mapTestMapOfEnumString + ] + + +-- | Construct a value of type 'MapTest' (by applying it's required fields, if any) +mkMapTest + :: MapTest +mkMapTest = + MapTest + { mapTestMapMapOfString = Nothing + , mapTestMapOfEnumString = Nothing + } + +-- ** MixedPropertiesAndAdditionalPropertiesClass +-- | MixedPropertiesAndAdditionalPropertiesClass +data MixedPropertiesAndAdditionalPropertiesClass = MixedPropertiesAndAdditionalPropertiesClass + { mixedPropertiesAndAdditionalPropertiesClassUuid :: !(Maybe Text) -- ^ "uuid" + , mixedPropertiesAndAdditionalPropertiesClassDateTime :: !(Maybe DateTime) -- ^ "dateTime" + , mixedPropertiesAndAdditionalPropertiesClassMap :: !(Maybe (Map.Map String Animal)) -- ^ "map" + } deriving (P.Show, P.Eq, P.Typeable) --- ** MapTest --- | MapTest -data MapTest = MapTest - { mapTestMapMapOfString :: !(Maybe (Map.Map String (Map.Map String Text))) -- ^ "map_map_of_string" - , mapTestMapOfEnumString :: !(Maybe (Map.Map String Text)) -- ^ "map_of_enum_string" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON MapTest -instance A.FromJSON MapTest where - parseJSON = A.withObject "MapTest" $ \o -> - MapTest - <$> (o .:? "map_map_of_string") - <*> (o .:? "map_of_enum_string") - --- | ToJSON MapTest -instance A.ToJSON MapTest where - toJSON MapTest {..} = - _omitNulls - [ "map_map_of_string" .= mapTestMapMapOfString - , "map_of_enum_string" .= mapTestMapOfEnumString - ] - - --- | Construct a value of type 'MapTest' (by applying it's required fields, if any) -mkMapTest - :: MapTest -mkMapTest = - MapTest - { mapTestMapMapOfString = Nothing - , mapTestMapOfEnumString = Nothing - } - - --- ** MixedPropertiesAndAdditionalPropertiesClass --- | MixedPropertiesAndAdditionalPropertiesClass -data MixedPropertiesAndAdditionalPropertiesClass = MixedPropertiesAndAdditionalPropertiesClass - { mixedPropertiesAndAdditionalPropertiesClassUuid :: !(Maybe Text) -- ^ "uuid" - , mixedPropertiesAndAdditionalPropertiesClassDateTime :: !(Maybe DateTime) -- ^ "dateTime" - , mixedPropertiesAndAdditionalPropertiesClassMap :: !(Maybe (Map.Map String Animal)) -- ^ "map" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON MixedPropertiesAndAdditionalPropertiesClass -instance A.FromJSON MixedPropertiesAndAdditionalPropertiesClass where - parseJSON = A.withObject "MixedPropertiesAndAdditionalPropertiesClass" $ \o -> - MixedPropertiesAndAdditionalPropertiesClass - <$> (o .:? "uuid") - <*> (o .:? "dateTime") - <*> (o .:? "map") - --- | ToJSON MixedPropertiesAndAdditionalPropertiesClass -instance A.ToJSON MixedPropertiesAndAdditionalPropertiesClass where - toJSON MixedPropertiesAndAdditionalPropertiesClass {..} = - _omitNulls - [ "uuid" .= mixedPropertiesAndAdditionalPropertiesClassUuid - , "dateTime" .= mixedPropertiesAndAdditionalPropertiesClassDateTime - , "map" .= mixedPropertiesAndAdditionalPropertiesClassMap - ] - - --- | Construct a value of type 'MixedPropertiesAndAdditionalPropertiesClass' (by applying it's required fields, if any) -mkMixedPropertiesAndAdditionalPropertiesClass - :: MixedPropertiesAndAdditionalPropertiesClass -mkMixedPropertiesAndAdditionalPropertiesClass = - MixedPropertiesAndAdditionalPropertiesClass - { mixedPropertiesAndAdditionalPropertiesClassUuid = Nothing - , mixedPropertiesAndAdditionalPropertiesClassDateTime = Nothing - , mixedPropertiesAndAdditionalPropertiesClassMap = Nothing - } - - --- ** Model200Response --- | Model200Response --- Model for testing model name starting with number -data Model200Response = Model200Response - { model200ResponseName :: !(Maybe Int) -- ^ "name" - , model200ResponseClass :: !(Maybe Text) -- ^ "class" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON Model200Response -instance A.FromJSON Model200Response where - parseJSON = A.withObject "Model200Response" $ \o -> - Model200Response - <$> (o .:? "name") - <*> (o .:? "class") - --- | ToJSON Model200Response -instance A.ToJSON Model200Response where - toJSON Model200Response {..} = - _omitNulls - [ "name" .= model200ResponseName - , "class" .= model200ResponseClass - ] - - --- | Construct a value of type 'Model200Response' (by applying it's required fields, if any) -mkModel200Response - :: Model200Response -mkModel200Response = - Model200Response - { model200ResponseName = Nothing - , model200ResponseClass = Nothing - } - - --- ** ModelList --- | ModelList -data ModelList = ModelList - { modelList123List :: !(Maybe Text) -- ^ "123-list" - } deriving (P.Show, P.Eq, P.Typeable) +-- | FromJSON MixedPropertiesAndAdditionalPropertiesClass +instance A.FromJSON MixedPropertiesAndAdditionalPropertiesClass where + parseJSON = A.withObject "MixedPropertiesAndAdditionalPropertiesClass" $ \o -> + MixedPropertiesAndAdditionalPropertiesClass + <$> (o .:? "uuid") + <*> (o .:? "dateTime") + <*> (o .:? "map") + +-- | ToJSON MixedPropertiesAndAdditionalPropertiesClass +instance A.ToJSON MixedPropertiesAndAdditionalPropertiesClass where + toJSON MixedPropertiesAndAdditionalPropertiesClass {..} = + _omitNulls + [ "uuid" .= mixedPropertiesAndAdditionalPropertiesClassUuid + , "dateTime" .= mixedPropertiesAndAdditionalPropertiesClassDateTime + , "map" .= mixedPropertiesAndAdditionalPropertiesClassMap + ] + + +-- | Construct a value of type 'MixedPropertiesAndAdditionalPropertiesClass' (by applying it's required fields, if any) +mkMixedPropertiesAndAdditionalPropertiesClass + :: MixedPropertiesAndAdditionalPropertiesClass +mkMixedPropertiesAndAdditionalPropertiesClass = + MixedPropertiesAndAdditionalPropertiesClass + { mixedPropertiesAndAdditionalPropertiesClassUuid = Nothing + , mixedPropertiesAndAdditionalPropertiesClassDateTime = Nothing + , mixedPropertiesAndAdditionalPropertiesClassMap = Nothing + } + +-- ** Model200Response +-- | Model200Response +-- Model for testing model name starting with number +data Model200Response = Model200Response + { model200ResponseName :: !(Maybe Int) -- ^ "name" + , model200ResponseClass :: !(Maybe Text) -- ^ "class" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON Model200Response +instance A.FromJSON Model200Response where + parseJSON = A.withObject "Model200Response" $ \o -> + Model200Response + <$> (o .:? "name") + <*> (o .:? "class") + +-- | ToJSON Model200Response +instance A.ToJSON Model200Response where + toJSON Model200Response {..} = + _omitNulls + [ "name" .= model200ResponseName + , "class" .= model200ResponseClass + ] + + +-- | Construct a value of type 'Model200Response' (by applying it's required fields, if any) +mkModel200Response + :: Model200Response +mkModel200Response = + Model200Response + { model200ResponseName = Nothing + , model200ResponseClass = Nothing + } + +-- ** ModelList +-- | ModelList +data ModelList = ModelList + { modelList123List :: !(Maybe Text) -- ^ "123-list" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON ModelList +instance A.FromJSON ModelList where + parseJSON = A.withObject "ModelList" $ \o -> + ModelList + <$> (o .:? "123-list") + +-- | ToJSON ModelList +instance A.ToJSON ModelList where + toJSON ModelList {..} = + _omitNulls + [ "123-list" .= modelList123List + ] + + +-- | Construct a value of type 'ModelList' (by applying it's required fields, if any) +mkModelList + :: ModelList +mkModelList = + ModelList + { modelList123List = Nothing + } + +-- ** ModelReturn +-- | ModelReturn +-- Model for testing reserved words +data ModelReturn = ModelReturn + { modelReturnReturn :: !(Maybe Int) -- ^ "return" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON ModelReturn +instance A.FromJSON ModelReturn where + parseJSON = A.withObject "ModelReturn" $ \o -> + ModelReturn + <$> (o .:? "return") + +-- | ToJSON ModelReturn +instance A.ToJSON ModelReturn where + toJSON ModelReturn {..} = + _omitNulls + [ "return" .= modelReturnReturn + ] + --- | FromJSON ModelList -instance A.FromJSON ModelList where - parseJSON = A.withObject "ModelList" $ \o -> - ModelList - <$> (o .:? "123-list") - --- | ToJSON ModelList -instance A.ToJSON ModelList where - toJSON ModelList {..} = - _omitNulls - [ "123-list" .= modelList123List - ] - - --- | Construct a value of type 'ModelList' (by applying it's required fields, if any) -mkModelList - :: ModelList -mkModelList = - ModelList - { modelList123List = Nothing - } - - --- ** ModelReturn --- | ModelReturn --- Model for testing reserved words -data ModelReturn = ModelReturn - { modelReturnReturn :: !(Maybe Int) -- ^ "return" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON ModelReturn -instance A.FromJSON ModelReturn where - parseJSON = A.withObject "ModelReturn" $ \o -> - ModelReturn - <$> (o .:? "return") - --- | ToJSON ModelReturn -instance A.ToJSON ModelReturn where - toJSON ModelReturn {..} = - _omitNulls - [ "return" .= modelReturnReturn - ] - - --- | Construct a value of type 'ModelReturn' (by applying it's required fields, if any) -mkModelReturn - :: ModelReturn -mkModelReturn = - ModelReturn - { modelReturnReturn = Nothing - } - - --- ** Name --- | Name --- Model for testing model name same as property name -data Name = Name - { nameName :: !(Int) -- ^ /Required/ "name" - , nameSnakeCase :: !(Maybe Int) -- ^ "snake_case" - , nameProperty :: !(Maybe Text) -- ^ "property" - , name123Number :: !(Maybe Int) -- ^ "123Number" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON Name -instance A.FromJSON Name where - parseJSON = A.withObject "Name" $ \o -> - Name - <$> (o .: "name") - <*> (o .:? "snake_case") - <*> (o .:? "property") - <*> (o .:? "123Number") - --- | ToJSON Name -instance A.ToJSON Name where - toJSON Name {..} = - _omitNulls - [ "name" .= nameName - , "snake_case" .= nameSnakeCase - , "property" .= nameProperty - , "123Number" .= name123Number - ] - - --- | Construct a value of type 'Name' (by applying it's required fields, if any) -mkName - :: Int -- ^ 'nameName' - -> Name -mkName nameName = - Name - { nameName - , nameSnakeCase = Nothing - , nameProperty = Nothing - , name123Number = Nothing - } - - --- ** NumberOnly --- | NumberOnly -data NumberOnly = NumberOnly - { numberOnlyJustNumber :: !(Maybe Double) -- ^ "JustNumber" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON NumberOnly -instance A.FromJSON NumberOnly where - parseJSON = A.withObject "NumberOnly" $ \o -> - NumberOnly - <$> (o .:? "JustNumber") - --- | ToJSON NumberOnly -instance A.ToJSON NumberOnly where - toJSON NumberOnly {..} = - _omitNulls - [ "JustNumber" .= numberOnlyJustNumber - ] - - --- | Construct a value of type 'NumberOnly' (by applying it's required fields, if any) -mkNumberOnly - :: NumberOnly -mkNumberOnly = - NumberOnly - { numberOnlyJustNumber = Nothing - } - - --- ** Order --- | Order -data Order = Order - { orderId :: !(Maybe Integer) -- ^ "id" - , orderPetId :: !(Maybe Integer) -- ^ "petId" - , orderQuantity :: !(Maybe Int) -- ^ "quantity" - , orderShipDate :: !(Maybe DateTime) -- ^ "shipDate" - , orderStatus :: !(Maybe Text) -- ^ "status" - Order Status - , orderComplete :: !(Maybe Bool) -- ^ "complete" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON Order -instance A.FromJSON Order where - parseJSON = A.withObject "Order" $ \o -> - Order - <$> (o .:? "id") - <*> (o .:? "petId") - <*> (o .:? "quantity") - <*> (o .:? "shipDate") - <*> (o .:? "status") - <*> (o .:? "complete") - --- | ToJSON Order -instance A.ToJSON Order where - toJSON Order {..} = - _omitNulls - [ "id" .= orderId - , "petId" .= orderPetId - , "quantity" .= orderQuantity - , "shipDate" .= orderShipDate - , "status" .= orderStatus - , "complete" .= orderComplete - ] +-- | Construct a value of type 'ModelReturn' (by applying it's required fields, if any) +mkModelReturn + :: ModelReturn +mkModelReturn = + ModelReturn + { modelReturnReturn = Nothing + } + +-- ** Name +-- | Name +-- Model for testing model name same as property name +data Name = Name + { nameName :: !(Int) -- ^ /Required/ "name" + , nameSnakeCase :: !(Maybe Int) -- ^ "snake_case" + , nameProperty :: !(Maybe Text) -- ^ "property" + , name123Number :: !(Maybe Int) -- ^ "123Number" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON Name +instance A.FromJSON Name where + parseJSON = A.withObject "Name" $ \o -> + Name + <$> (o .: "name") + <*> (o .:? "snake_case") + <*> (o .:? "property") + <*> (o .:? "123Number") + +-- | ToJSON Name +instance A.ToJSON Name where + toJSON Name {..} = + _omitNulls + [ "name" .= nameName + , "snake_case" .= nameSnakeCase + , "property" .= nameProperty + , "123Number" .= name123Number + ] + + +-- | Construct a value of type 'Name' (by applying it's required fields, if any) +mkName + :: Int -- ^ 'nameName' + -> Name +mkName nameName = + Name + { nameName + , nameSnakeCase = Nothing + , nameProperty = Nothing + , name123Number = Nothing + } + +-- ** NumberOnly +-- | NumberOnly +data NumberOnly = NumberOnly + { numberOnlyJustNumber :: !(Maybe Double) -- ^ "JustNumber" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON NumberOnly +instance A.FromJSON NumberOnly where + parseJSON = A.withObject "NumberOnly" $ \o -> + NumberOnly + <$> (o .:? "JustNumber") + +-- | ToJSON NumberOnly +instance A.ToJSON NumberOnly where + toJSON NumberOnly {..} = + _omitNulls + [ "JustNumber" .= numberOnlyJustNumber + ] + + +-- | Construct a value of type 'NumberOnly' (by applying it's required fields, if any) +mkNumberOnly + :: NumberOnly +mkNumberOnly = + NumberOnly + { numberOnlyJustNumber = Nothing + } + +-- ** Order +-- | Order +data Order = Order + { orderId :: !(Maybe Integer) -- ^ "id" + , orderPetId :: !(Maybe Integer) -- ^ "petId" + , orderQuantity :: !(Maybe Int) -- ^ "quantity" + , orderShipDate :: !(Maybe DateTime) -- ^ "shipDate" + , orderStatus :: !(Maybe E'Status) -- ^ "status" - Order Status + , orderComplete :: !(Maybe Bool) -- ^ "complete" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON Order +instance A.FromJSON Order where + parseJSON = A.withObject "Order" $ \o -> + Order + <$> (o .:? "id") + <*> (o .:? "petId") + <*> (o .:? "quantity") + <*> (o .:? "shipDate") + <*> (o .:? "status") + <*> (o .:? "complete") + +-- | ToJSON Order +instance A.ToJSON Order where + toJSON Order {..} = + _omitNulls + [ "id" .= orderId + , "petId" .= orderPetId + , "quantity" .= orderQuantity + , "shipDate" .= orderShipDate + , "status" .= orderStatus + , "complete" .= orderComplete + ] + + +-- | Construct a value of type 'Order' (by applying it's required fields, if any) +mkOrder + :: Order +mkOrder = + Order + { orderId = Nothing + , orderPetId = Nothing + , orderQuantity = Nothing + , orderShipDate = Nothing + , orderStatus = Nothing + , orderComplete = Nothing + } + +-- ** OuterBoolean +-- | OuterBoolean +newtype OuterBoolean = OuterBoolean + { unOuterBoolean :: Bool + } deriving (P.Eq, P.Show, P.Typeable, A.ToJSON, A.FromJSON, WH.ToHttpApiData, WH.FromHttpApiData) + + +-- ** OuterComposite +-- | OuterComposite +data OuterComposite = OuterComposite + { outerCompositeMyNumber :: !(Maybe OuterNumber) -- ^ "my_number" + , outerCompositeMyString :: !(Maybe OuterString) -- ^ "my_string" + , outerCompositeMyBoolean :: !(Maybe OuterBoolean) -- ^ "my_boolean" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON OuterComposite +instance A.FromJSON OuterComposite where + parseJSON = A.withObject "OuterComposite" $ \o -> + OuterComposite + <$> (o .:? "my_number") + <*> (o .:? "my_string") + <*> (o .:? "my_boolean") + +-- | ToJSON OuterComposite +instance A.ToJSON OuterComposite where + toJSON OuterComposite {..} = + _omitNulls + [ "my_number" .= outerCompositeMyNumber + , "my_string" .= outerCompositeMyString + , "my_boolean" .= outerCompositeMyBoolean + ] + - --- | Construct a value of type 'Order' (by applying it's required fields, if any) -mkOrder - :: Order -mkOrder = - Order - { orderId = Nothing - , orderPetId = Nothing - , orderQuantity = Nothing - , orderShipDate = Nothing - , orderStatus = Nothing - , orderComplete = Nothing - } - - --- ** OuterBoolean --- | OuterBoolean -newtype OuterBoolean = OuterBoolean - { unOuterBoolean :: Bool - } deriving (P.Eq, P.Show, P.Typeable, A.ToJSON, A.FromJSON, WH.ToHttpApiData, WH.FromHttpApiData) - - +-- | Construct a value of type 'OuterComposite' (by applying it's required fields, if any) +mkOuterComposite + :: OuterComposite +mkOuterComposite = + OuterComposite + { outerCompositeMyNumber = Nothing + , outerCompositeMyString = Nothing + , outerCompositeMyBoolean = Nothing + } + +-- ** OuterNumber +-- | OuterNumber +newtype OuterNumber = OuterNumber + { unOuterNumber :: Double + } deriving (P.Eq, P.Show, P.Typeable, A.ToJSON, A.FromJSON, WH.ToHttpApiData, WH.FromHttpApiData) + + +-- ** OuterString +-- | OuterString +newtype OuterString = OuterString + { unOuterString :: Text + } deriving (P.Eq, P.Show, P.Typeable, A.ToJSON, A.FromJSON, WH.ToHttpApiData, WH.FromHttpApiData) --- ** OuterComposite --- | OuterComposite -data OuterComposite = OuterComposite - { outerCompositeMyNumber :: !(Maybe OuterNumber) -- ^ "my_number" - , outerCompositeMyString :: !(Maybe OuterString) -- ^ "my_string" - , outerCompositeMyBoolean :: !(Maybe OuterBoolean) -- ^ "my_boolean" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON OuterComposite -instance A.FromJSON OuterComposite where - parseJSON = A.withObject "OuterComposite" $ \o -> - OuterComposite - <$> (o .:? "my_number") - <*> (o .:? "my_string") - <*> (o .:? "my_boolean") - --- | ToJSON OuterComposite -instance A.ToJSON OuterComposite where - toJSON OuterComposite {..} = - _omitNulls - [ "my_number" .= outerCompositeMyNumber - , "my_string" .= outerCompositeMyString - , "my_boolean" .= outerCompositeMyBoolean - ] - - --- | Construct a value of type 'OuterComposite' (by applying it's required fields, if any) -mkOuterComposite - :: OuterComposite -mkOuterComposite = - OuterComposite - { outerCompositeMyNumber = Nothing - , outerCompositeMyString = Nothing - , outerCompositeMyBoolean = Nothing - } + +-- ** Pet +-- | Pet +data Pet = Pet + { petId :: !(Maybe Integer) -- ^ "id" + , petCategory :: !(Maybe Category) -- ^ "category" + , petName :: !(Text) -- ^ /Required/ "name" + , petPhotoUrls :: !([Text]) -- ^ /Required/ "photoUrls" + , petTags :: !(Maybe [Tag]) -- ^ "tags" + , petStatus :: !(Maybe E'Status2) -- ^ "status" - pet status in the store + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON Pet +instance A.FromJSON Pet where + parseJSON = A.withObject "Pet" $ \o -> + Pet + <$> (o .:? "id") + <*> (o .:? "category") + <*> (o .: "name") + <*> (o .: "photoUrls") + <*> (o .:? "tags") + <*> (o .:? "status") + +-- | ToJSON Pet +instance A.ToJSON Pet where + toJSON Pet {..} = + _omitNulls + [ "id" .= petId + , "category" .= petCategory + , "name" .= petName + , "photoUrls" .= petPhotoUrls + , "tags" .= petTags + , "status" .= petStatus + ] + - --- ** OuterEnum --- | OuterEnum -data OuterEnum = OuterEnum - { - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON OuterEnum -instance A.FromJSON OuterEnum where - parseJSON = A.withObject "OuterEnum" $ \o -> - pure OuterEnum - - --- | ToJSON OuterEnum -instance A.ToJSON OuterEnum where - toJSON OuterEnum = - _omitNulls - [ - ] - - --- | Construct a value of type 'OuterEnum' (by applying it's required fields, if any) -mkOuterEnum - :: OuterEnum -mkOuterEnum = - OuterEnum - { - } +-- | Construct a value of type 'Pet' (by applying it's required fields, if any) +mkPet + :: Text -- ^ 'petName' + -> [Text] -- ^ 'petPhotoUrls' + -> Pet +mkPet petName petPhotoUrls = + Pet + { petId = Nothing + , petCategory = Nothing + , petName + , petPhotoUrls + , petTags = Nothing + , petStatus = Nothing + } + +-- ** ReadOnlyFirst +-- | ReadOnlyFirst +data ReadOnlyFirst = ReadOnlyFirst + { readOnlyFirstBar :: !(Maybe Text) -- ^ "bar" + , readOnlyFirstBaz :: !(Maybe Text) -- ^ "baz" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON ReadOnlyFirst +instance A.FromJSON ReadOnlyFirst where + parseJSON = A.withObject "ReadOnlyFirst" $ \o -> + ReadOnlyFirst + <$> (o .:? "bar") + <*> (o .:? "baz") - --- ** OuterNumber --- | OuterNumber -newtype OuterNumber = OuterNumber - { unOuterNumber :: Double - } deriving (P.Eq, P.Show, P.Typeable, A.ToJSON, A.FromJSON, WH.ToHttpApiData, WH.FromHttpApiData) - +-- | ToJSON ReadOnlyFirst +instance A.ToJSON ReadOnlyFirst where + toJSON ReadOnlyFirst {..} = + _omitNulls + [ "bar" .= readOnlyFirstBar + , "baz" .= readOnlyFirstBaz + ] --- ** OuterString --- | OuterString -newtype OuterString = OuterString - { unOuterString :: Text - } deriving (P.Eq, P.Show, P.Typeable, A.ToJSON, A.FromJSON, WH.ToHttpApiData, WH.FromHttpApiData) - - - --- ** Pet --- | Pet -data Pet = Pet - { petId :: !(Maybe Integer) -- ^ "id" - , petCategory :: !(Maybe Category) -- ^ "category" - , petName :: !(Text) -- ^ /Required/ "name" - , petPhotoUrls :: !([Text]) -- ^ /Required/ "photoUrls" - , petTags :: !(Maybe [Tag]) -- ^ "tags" - , petStatus :: !(Maybe Text) -- ^ "status" - pet status in the store - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON Pet -instance A.FromJSON Pet where - parseJSON = A.withObject "Pet" $ \o -> - Pet - <$> (o .:? "id") - <*> (o .:? "category") - <*> (o .: "name") - <*> (o .: "photoUrls") - <*> (o .:? "tags") - <*> (o .:? "status") - --- | ToJSON Pet -instance A.ToJSON Pet where - toJSON Pet {..} = - _omitNulls - [ "id" .= petId - , "category" .= petCategory - , "name" .= petName - , "photoUrls" .= petPhotoUrls - , "tags" .= petTags - , "status" .= petStatus - ] - - --- | Construct a value of type 'Pet' (by applying it's required fields, if any) -mkPet - :: Text -- ^ 'petName' - -> [Text] -- ^ 'petPhotoUrls' - -> Pet -mkPet petName petPhotoUrls = - Pet - { petId = Nothing - , petCategory = Nothing - , petName - , petPhotoUrls - , petTags = Nothing - , petStatus = Nothing - } - +-- | Construct a value of type 'ReadOnlyFirst' (by applying it's required fields, if any) +mkReadOnlyFirst + :: ReadOnlyFirst +mkReadOnlyFirst = + ReadOnlyFirst + { readOnlyFirstBar = Nothing + , readOnlyFirstBaz = Nothing + } + +-- ** SpecialModelName +-- | SpecialModelName +data SpecialModelName = SpecialModelName + { specialModelNameSpecialPropertyName :: !(Maybe Integer) -- ^ "$special[property.name]" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON SpecialModelName +instance A.FromJSON SpecialModelName where + parseJSON = A.withObject "SpecialModelName" $ \o -> + SpecialModelName + <$> (o .:? "$special[property.name]") + +-- | ToJSON SpecialModelName +instance A.ToJSON SpecialModelName where + toJSON SpecialModelName {..} = + _omitNulls + [ "$special[property.name]" .= specialModelNameSpecialPropertyName + ] + + +-- | Construct a value of type 'SpecialModelName' (by applying it's required fields, if any) +mkSpecialModelName + :: SpecialModelName +mkSpecialModelName = + SpecialModelName + { specialModelNameSpecialPropertyName = Nothing + } + +-- ** Tag +-- | Tag +data Tag = Tag + { tagId :: !(Maybe Integer) -- ^ "id" + , tagName :: !(Maybe Text) -- ^ "name" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON Tag +instance A.FromJSON Tag where + parseJSON = A.withObject "Tag" $ \o -> + Tag + <$> (o .:? "id") + <*> (o .:? "name") + +-- | ToJSON Tag +instance A.ToJSON Tag where + toJSON Tag {..} = + _omitNulls + [ "id" .= tagId + , "name" .= tagName + ] --- ** ReadOnlyFirst --- | ReadOnlyFirst -data ReadOnlyFirst = ReadOnlyFirst - { readOnlyFirstBar :: !(Maybe Text) -- ^ "bar" - , readOnlyFirstBaz :: !(Maybe Text) -- ^ "baz" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON ReadOnlyFirst -instance A.FromJSON ReadOnlyFirst where - parseJSON = A.withObject "ReadOnlyFirst" $ \o -> - ReadOnlyFirst - <$> (o .:? "bar") - <*> (o .:? "baz") - --- | ToJSON ReadOnlyFirst -instance A.ToJSON ReadOnlyFirst where - toJSON ReadOnlyFirst {..} = - _omitNulls - [ "bar" .= readOnlyFirstBar - , "baz" .= readOnlyFirstBaz - ] - + +-- | Construct a value of type 'Tag' (by applying it's required fields, if any) +mkTag + :: Tag +mkTag = + Tag + { tagId = Nothing + , tagName = Nothing + } + +-- ** User +-- | User +data User = User + { userId :: !(Maybe Integer) -- ^ "id" + , userUsername :: !(Maybe Text) -- ^ "username" + , userFirstName :: !(Maybe Text) -- ^ "firstName" + , userLastName :: !(Maybe Text) -- ^ "lastName" + , userEmail :: !(Maybe Text) -- ^ "email" + , userPassword :: !(Maybe Text) -- ^ "password" + , userPhone :: !(Maybe Text) -- ^ "phone" + , userUserStatus :: !(Maybe Int) -- ^ "userStatus" - User Status + } deriving (P.Show, P.Eq, P.Typeable) --- | Construct a value of type 'ReadOnlyFirst' (by applying it's required fields, if any) -mkReadOnlyFirst - :: ReadOnlyFirst -mkReadOnlyFirst = - ReadOnlyFirst - { readOnlyFirstBar = Nothing - , readOnlyFirstBaz = Nothing - } - - --- ** SpecialModelName --- | SpecialModelName -data SpecialModelName = SpecialModelName - { specialModelNameSpecialPropertyName :: !(Maybe Integer) -- ^ "$special[property.name]" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON SpecialModelName -instance A.FromJSON SpecialModelName where - parseJSON = A.withObject "SpecialModelName" $ \o -> - SpecialModelName - <$> (o .:? "$special[property.name]") - --- | ToJSON SpecialModelName -instance A.ToJSON SpecialModelName where - toJSON SpecialModelName {..} = - _omitNulls - [ "$special[property.name]" .= specialModelNameSpecialPropertyName - ] - - --- | Construct a value of type 'SpecialModelName' (by applying it's required fields, if any) -mkSpecialModelName - :: SpecialModelName -mkSpecialModelName = - SpecialModelName - { specialModelNameSpecialPropertyName = Nothing - } - - --- ** Tag --- | Tag -data Tag = Tag - { tagId :: !(Maybe Integer) -- ^ "id" - , tagName :: !(Maybe Text) -- ^ "name" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON Tag -instance A.FromJSON Tag where - parseJSON = A.withObject "Tag" $ \o -> - Tag - <$> (o .:? "id") - <*> (o .:? "name") - --- | ToJSON Tag -instance A.ToJSON Tag where - toJSON Tag {..} = - _omitNulls - [ "id" .= tagId - , "name" .= tagName - ] - - --- | Construct a value of type 'Tag' (by applying it's required fields, if any) -mkTag - :: Tag -mkTag = - Tag - { tagId = Nothing - , tagName = Nothing - } - - --- ** User --- | User -data User = User - { userId :: !(Maybe Integer) -- ^ "id" - , userUsername :: !(Maybe Text) -- ^ "username" - , userFirstName :: !(Maybe Text) -- ^ "firstName" - , userLastName :: !(Maybe Text) -- ^ "lastName" - , userEmail :: !(Maybe Text) -- ^ "email" - , userPassword :: !(Maybe Text) -- ^ "password" - , userPhone :: !(Maybe Text) -- ^ "phone" - , userUserStatus :: !(Maybe Int) -- ^ "userStatus" - User Status - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON User -instance A.FromJSON User where - parseJSON = A.withObject "User" $ \o -> - User - <$> (o .:? "id") - <*> (o .:? "username") - <*> (o .:? "firstName") - <*> (o .:? "lastName") - <*> (o .:? "email") - <*> (o .:? "password") - <*> (o .:? "phone") - <*> (o .:? "userStatus") - --- | ToJSON User -instance A.ToJSON User where - toJSON User {..} = - _omitNulls - [ "id" .= userId - , "username" .= userUsername - , "firstName" .= userFirstName - , "lastName" .= userLastName - , "email" .= userEmail - , "password" .= userPassword - , "phone" .= userPhone - , "userStatus" .= userUserStatus - ] - - --- | Construct a value of type 'User' (by applying it's required fields, if any) -mkUser - :: User -mkUser = - User - { userId = Nothing - , userUsername = Nothing - , userFirstName = Nothing - , userLastName = Nothing - , userEmail = Nothing - , userPassword = Nothing - , userPhone = Nothing - , userUserStatus = Nothing - } - +-- | FromJSON User +instance A.FromJSON User where + parseJSON = A.withObject "User" $ \o -> + User + <$> (o .:? "id") + <*> (o .:? "username") + <*> (o .:? "firstName") + <*> (o .:? "lastName") + <*> (o .:? "email") + <*> (o .:? "password") + <*> (o .:? "phone") + <*> (o .:? "userStatus") + +-- | ToJSON User +instance A.ToJSON User where + toJSON User {..} = + _omitNulls + [ "id" .= userId + , "username" .= userUsername + , "firstName" .= userFirstName + , "lastName" .= userLastName + , "email" .= userEmail + , "password" .= userPassword + , "phone" .= userPhone + , "userStatus" .= userUserStatus + ] + + +-- | Construct a value of type 'User' (by applying it's required fields, if any) +mkUser + :: User +mkUser = + User + { userId = Nothing + , userUsername = Nothing + , userFirstName = Nothing + , userLastName = Nothing + , userEmail = Nothing + , userPassword = Nothing + , userPhone = Nothing + , userUserStatus = Nothing + } + +-- ** Cat +-- | Cat +data Cat = Cat + { catClassName :: !(Text) -- ^ /Required/ "className" + , catColor :: !(Maybe Text) -- ^ "color" + , catDeclawed :: !(Maybe Bool) -- ^ "declawed" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON Cat +instance A.FromJSON Cat where + parseJSON = A.withObject "Cat" $ \o -> + Cat + <$> (o .: "className") + <*> (o .:? "color") + <*> (o .:? "declawed") + +-- | ToJSON Cat +instance A.ToJSON Cat where + toJSON Cat {..} = + _omitNulls + [ "className" .= catClassName + , "color" .= catColor + , "declawed" .= catDeclawed + ] + + +-- | Construct a value of type 'Cat' (by applying it's required fields, if any) +mkCat + :: Text -- ^ 'catClassName' + -> Cat +mkCat catClassName = + Cat + { catClassName + , catColor = Nothing + , catDeclawed = Nothing + } + +-- ** Dog +-- | Dog +data Dog = Dog + { dogClassName :: !(Text) -- ^ /Required/ "className" + , dogColor :: !(Maybe Text) -- ^ "color" + , dogBreed :: !(Maybe Text) -- ^ "breed" + } deriving (P.Show, P.Eq, P.Typeable) + +-- | FromJSON Dog +instance A.FromJSON Dog where + parseJSON = A.withObject "Dog" $ \o -> + Dog + <$> (o .: "className") + <*> (o .:? "color") + <*> (o .:? "breed") + +-- | ToJSON Dog +instance A.ToJSON Dog where + toJSON Dog {..} = + _omitNulls + [ "className" .= dogClassName + , "color" .= dogColor + , "breed" .= dogBreed + ] + + +-- | Construct a value of type 'Dog' (by applying it's required fields, if any) +mkDog + :: Text -- ^ 'dogClassName' + -> Dog +mkDog dogClassName = + Dog + { dogClassName + , dogColor = Nothing + , dogBreed = Nothing + } + + +-- * Enums + + +-- ** E'ArrayEnum + +-- | Enum of 'Text' +data E'ArrayEnum + = E'ArrayEnum'Fish -- ^ @"fish"@ + | E'ArrayEnum'Crab -- ^ @"crab"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) --- ** Cat --- | Cat -data Cat = Cat - { catClassName :: !(Text) -- ^ /Required/ "className" - , catColor :: !(Maybe Text) -- ^ "color" - , catDeclawed :: !(Maybe Bool) -- ^ "declawed" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON Cat -instance A.FromJSON Cat where - parseJSON = A.withObject "Cat" $ \o -> - Cat - <$> (o .: "className") - <*> (o .:? "color") - <*> (o .:? "declawed") - --- | ToJSON Cat -instance A.ToJSON Cat where - toJSON Cat {..} = - _omitNulls - [ "className" .= catClassName - , "color" .= catColor - , "declawed" .= catDeclawed - ] - - --- | Construct a value of type 'Cat' (by applying it's required fields, if any) -mkCat - :: Text -- ^ 'catClassName' - -> Cat -mkCat catClassName = - Cat - { catClassName - , catColor = Nothing - , catDeclawed = Nothing - } - - --- ** Dog --- | Dog -data Dog = Dog - { dogClassName :: !(Text) -- ^ /Required/ "className" - , dogColor :: !(Maybe Text) -- ^ "color" - , dogBreed :: !(Maybe Text) -- ^ "breed" - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON Dog -instance A.FromJSON Dog where - parseJSON = A.withObject "Dog" $ \o -> - Dog - <$> (o .: "className") - <*> (o .:? "color") - <*> (o .:? "breed") - --- | ToJSON Dog -instance A.ToJSON Dog where - toJSON Dog {..} = - _omitNulls - [ "className" .= dogClassName - , "color" .= dogColor - , "breed" .= dogBreed - ] - - --- | Construct a value of type 'Dog' (by applying it's required fields, if any) -mkDog - :: Text -- ^ 'dogClassName' - -> Dog -mkDog dogClassName = - Dog - { dogClassName - , dogColor = Nothing - , dogBreed = Nothing - } - - - - \ No newline at end of file +instance A.ToJSON E'ArrayEnum where toJSON = A.toJSON . fromE'ArrayEnum +instance A.FromJSON E'ArrayEnum where parseJSON o = P.either P.fail (pure . P.id) . toE'ArrayEnum =<< A.parseJSON o +instance WH.ToHttpApiData E'ArrayEnum where toQueryParam = WH.toQueryParam . fromE'ArrayEnum +instance WH.FromHttpApiData E'ArrayEnum where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'ArrayEnum +instance MimeRender MimeMultipartFormData E'ArrayEnum where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'ArrayEnum' enum +fromE'ArrayEnum :: E'ArrayEnum -> Text +fromE'ArrayEnum = \case + E'ArrayEnum'Fish -> "fish" + E'ArrayEnum'Crab -> "crab" + +-- | parse 'E'ArrayEnum' enum +toE'ArrayEnum :: Text -> P.Either String E'ArrayEnum +toE'ArrayEnum = \case + "fish" -> P.Right E'ArrayEnum'Fish + "crab" -> P.Right E'ArrayEnum'Crab + s -> P.Left $ "toE'ArrayEnum: enum parse failure: " P.++ P.show s + + +-- ** E'EnumFormString + +-- | Enum of 'Text' +data E'EnumFormString + = E'EnumFormString'_abc -- ^ @"_abc"@ + | E'EnumFormString'_efg -- ^ @"-efg"@ + | E'EnumFormString'_xyz -- ^ @"(xyz)"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'EnumFormString where toJSON = A.toJSON . fromE'EnumFormString +instance A.FromJSON E'EnumFormString where parseJSON o = P.either P.fail (pure . P.id) . toE'EnumFormString =<< A.parseJSON o +instance WH.ToHttpApiData E'EnumFormString where toQueryParam = WH.toQueryParam . fromE'EnumFormString +instance WH.FromHttpApiData E'EnumFormString where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'EnumFormString +instance MimeRender MimeMultipartFormData E'EnumFormString where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'EnumFormString' enum +fromE'EnumFormString :: E'EnumFormString -> Text +fromE'EnumFormString = \case + E'EnumFormString'_abc -> "_abc" + E'EnumFormString'_efg -> "-efg" + E'EnumFormString'_xyz -> "(xyz)" + +-- | parse 'E'EnumFormString' enum +toE'EnumFormString :: Text -> P.Either String E'EnumFormString +toE'EnumFormString = \case + "_abc" -> P.Right E'EnumFormString'_abc + "-efg" -> P.Right E'EnumFormString'_efg + "(xyz)" -> P.Right E'EnumFormString'_xyz + s -> P.Left $ "toE'EnumFormString: enum parse failure: " P.++ P.show s + + +-- ** E'EnumInteger + +-- | Enum of 'Int' +data E'EnumInteger + = E'EnumInteger'Num1 -- ^ @1@ + | E'EnumInteger'NumMinus_1 -- ^ @-1@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'EnumInteger where toJSON = A.toJSON . fromE'EnumInteger +instance A.FromJSON E'EnumInteger where parseJSON o = P.either P.fail (pure . P.id) . toE'EnumInteger =<< A.parseJSON o +instance WH.ToHttpApiData E'EnumInteger where toQueryParam = WH.toQueryParam . fromE'EnumInteger +instance WH.FromHttpApiData E'EnumInteger where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'EnumInteger +instance MimeRender MimeMultipartFormData E'EnumInteger where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'EnumInteger' enum +fromE'EnumInteger :: E'EnumInteger -> Int +fromE'EnumInteger = \case + E'EnumInteger'Num1 -> 1 + E'EnumInteger'NumMinus_1 -> -1 + +-- | parse 'E'EnumInteger' enum +toE'EnumInteger :: Int -> P.Either String E'EnumInteger +toE'EnumInteger = \case + 1 -> P.Right E'EnumInteger'Num1 + -1 -> P.Right E'EnumInteger'NumMinus_1 + s -> P.Left $ "toE'EnumInteger: enum parse failure: " P.++ P.show s + + +-- ** E'EnumNumber + +-- | Enum of 'Double' +data E'EnumNumber + = E'EnumNumber'Num1_Dot_1 -- ^ @1.1@ + | E'EnumNumber'NumMinus_1_Dot_2 -- ^ @-1.2@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'EnumNumber where toJSON = A.toJSON . fromE'EnumNumber +instance A.FromJSON E'EnumNumber where parseJSON o = P.either P.fail (pure . P.id) . toE'EnumNumber =<< A.parseJSON o +instance WH.ToHttpApiData E'EnumNumber where toQueryParam = WH.toQueryParam . fromE'EnumNumber +instance WH.FromHttpApiData E'EnumNumber where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'EnumNumber +instance MimeRender MimeMultipartFormData E'EnumNumber where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'EnumNumber' enum +fromE'EnumNumber :: E'EnumNumber -> Double +fromE'EnumNumber = \case + E'EnumNumber'Num1_Dot_1 -> 1.1 + E'EnumNumber'NumMinus_1_Dot_2 -> -1.2 + +-- | parse 'E'EnumNumber' enum +toE'EnumNumber :: Double -> P.Either String E'EnumNumber +toE'EnumNumber = \case + 1.1 -> P.Right E'EnumNumber'Num1_Dot_1 + -1.2 -> P.Right E'EnumNumber'NumMinus_1_Dot_2 + s -> P.Left $ "toE'EnumNumber: enum parse failure: " P.++ P.show s + + +-- ** E'EnumQueryInteger + +-- | Enum of 'Int' +data E'EnumQueryInteger + = E'EnumQueryInteger'Num1 -- ^ @1@ + | E'EnumQueryInteger'NumMinus_2 -- ^ @-2@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'EnumQueryInteger where toJSON = A.toJSON . fromE'EnumQueryInteger +instance A.FromJSON E'EnumQueryInteger where parseJSON o = P.either P.fail (pure . P.id) . toE'EnumQueryInteger =<< A.parseJSON o +instance WH.ToHttpApiData E'EnumQueryInteger where toQueryParam = WH.toQueryParam . fromE'EnumQueryInteger +instance WH.FromHttpApiData E'EnumQueryInteger where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'EnumQueryInteger +instance MimeRender MimeMultipartFormData E'EnumQueryInteger where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'EnumQueryInteger' enum +fromE'EnumQueryInteger :: E'EnumQueryInteger -> Int +fromE'EnumQueryInteger = \case + E'EnumQueryInteger'Num1 -> 1 + E'EnumQueryInteger'NumMinus_2 -> -2 + +-- | parse 'E'EnumQueryInteger' enum +toE'EnumQueryInteger :: Int -> P.Either String E'EnumQueryInteger +toE'EnumQueryInteger = \case + 1 -> P.Right E'EnumQueryInteger'Num1 + -2 -> P.Right E'EnumQueryInteger'NumMinus_2 + s -> P.Left $ "toE'EnumQueryInteger: enum parse failure: " P.++ P.show s + + +-- ** E'EnumString + +-- | Enum of 'Text' +data E'EnumString + = E'EnumString'UPPER -- ^ @"UPPER"@ + | E'EnumString'Lower -- ^ @"lower"@ + | E'EnumString'Empty -- ^ @""@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'EnumString where toJSON = A.toJSON . fromE'EnumString +instance A.FromJSON E'EnumString where parseJSON o = P.either P.fail (pure . P.id) . toE'EnumString =<< A.parseJSON o +instance WH.ToHttpApiData E'EnumString where toQueryParam = WH.toQueryParam . fromE'EnumString +instance WH.FromHttpApiData E'EnumString where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'EnumString +instance MimeRender MimeMultipartFormData E'EnumString where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'EnumString' enum +fromE'EnumString :: E'EnumString -> Text +fromE'EnumString = \case + E'EnumString'UPPER -> "UPPER" + E'EnumString'Lower -> "lower" + E'EnumString'Empty -> "" + +-- | parse 'E'EnumString' enum +toE'EnumString :: Text -> P.Either String E'EnumString +toE'EnumString = \case + "UPPER" -> P.Right E'EnumString'UPPER + "lower" -> P.Right E'EnumString'Lower + "" -> P.Right E'EnumString'Empty + s -> P.Left $ "toE'EnumString: enum parse failure: " P.++ P.show s + + +-- ** E'Inner + +-- | Enum of 'Text' +data E'Inner + = E'Inner'UPPER -- ^ @"UPPER"@ + | E'Inner'Lower -- ^ @"lower"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'Inner where toJSON = A.toJSON . fromE'Inner +instance A.FromJSON E'Inner where parseJSON o = P.either P.fail (pure . P.id) . toE'Inner =<< A.parseJSON o +instance WH.ToHttpApiData E'Inner where toQueryParam = WH.toQueryParam . fromE'Inner +instance WH.FromHttpApiData E'Inner where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'Inner +instance MimeRender MimeMultipartFormData E'Inner where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'Inner' enum +fromE'Inner :: E'Inner -> Text +fromE'Inner = \case + E'Inner'UPPER -> "UPPER" + E'Inner'Lower -> "lower" + +-- | parse 'E'Inner' enum +toE'Inner :: Text -> P.Either String E'Inner +toE'Inner = \case + "UPPER" -> P.Right E'Inner'UPPER + "lower" -> P.Right E'Inner'Lower + s -> P.Left $ "toE'Inner: enum parse failure: " P.++ P.show s + + +-- ** E'Inner2 + +-- | Enum of 'Text' +data E'Inner2 + = E'Inner2'GreaterThan -- ^ @">"@ + | E'Inner2'Dollar -- ^ @"$"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'Inner2 where toJSON = A.toJSON . fromE'Inner2 +instance A.FromJSON E'Inner2 where parseJSON o = P.either P.fail (pure . P.id) . toE'Inner2 =<< A.parseJSON o +instance WH.ToHttpApiData E'Inner2 where toQueryParam = WH.toQueryParam . fromE'Inner2 +instance WH.FromHttpApiData E'Inner2 where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'Inner2 +instance MimeRender MimeMultipartFormData E'Inner2 where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'Inner2' enum +fromE'Inner2 :: E'Inner2 -> Text +fromE'Inner2 = \case + E'Inner2'GreaterThan -> ">" + E'Inner2'Dollar -> "$" + +-- | parse 'E'Inner2' enum +toE'Inner2 :: Text -> P.Either String E'Inner2 +toE'Inner2 = \case + ">" -> P.Right E'Inner2'GreaterThan + "$" -> P.Right E'Inner2'Dollar + s -> P.Left $ "toE'Inner2: enum parse failure: " P.++ P.show s + + +-- ** E'JustSymbol + +-- | Enum of 'Text' +data E'JustSymbol + = E'JustSymbol'Greater_Than_Or_Equal_To -- ^ @">="@ + | E'JustSymbol'Dollar -- ^ @"$"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'JustSymbol where toJSON = A.toJSON . fromE'JustSymbol +instance A.FromJSON E'JustSymbol where parseJSON o = P.either P.fail (pure . P.id) . toE'JustSymbol =<< A.parseJSON o +instance WH.ToHttpApiData E'JustSymbol where toQueryParam = WH.toQueryParam . fromE'JustSymbol +instance WH.FromHttpApiData E'JustSymbol where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'JustSymbol +instance MimeRender MimeMultipartFormData E'JustSymbol where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'JustSymbol' enum +fromE'JustSymbol :: E'JustSymbol -> Text +fromE'JustSymbol = \case + E'JustSymbol'Greater_Than_Or_Equal_To -> ">=" + E'JustSymbol'Dollar -> "$" + +-- | parse 'E'JustSymbol' enum +toE'JustSymbol :: Text -> P.Either String E'JustSymbol +toE'JustSymbol = \case + ">=" -> P.Right E'JustSymbol'Greater_Than_Or_Equal_To + "$" -> P.Right E'JustSymbol'Dollar + s -> P.Left $ "toE'JustSymbol: enum parse failure: " P.++ P.show s + + +-- ** E'Status + +-- | Enum of 'Text' . +-- Order Status +data E'Status + = E'Status'Placed -- ^ @"placed"@ + | E'Status'Approved -- ^ @"approved"@ + | E'Status'Delivered -- ^ @"delivered"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'Status where toJSON = A.toJSON . fromE'Status +instance A.FromJSON E'Status where parseJSON o = P.either P.fail (pure . P.id) . toE'Status =<< A.parseJSON o +instance WH.ToHttpApiData E'Status where toQueryParam = WH.toQueryParam . fromE'Status +instance WH.FromHttpApiData E'Status where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'Status +instance MimeRender MimeMultipartFormData E'Status where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'Status' enum +fromE'Status :: E'Status -> Text +fromE'Status = \case + E'Status'Placed -> "placed" + E'Status'Approved -> "approved" + E'Status'Delivered -> "delivered" + +-- | parse 'E'Status' enum +toE'Status :: Text -> P.Either String E'Status +toE'Status = \case + "placed" -> P.Right E'Status'Placed + "approved" -> P.Right E'Status'Approved + "delivered" -> P.Right E'Status'Delivered + s -> P.Left $ "toE'Status: enum parse failure: " P.++ P.show s + + +-- ** E'Status2 + +-- | Enum of 'Text' . +-- pet status in the store +data E'Status2 + = E'Status2'Available -- ^ @"available"@ + | E'Status2'Pending -- ^ @"pending"@ + | E'Status2'Sold -- ^ @"sold"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'Status2 where toJSON = A.toJSON . fromE'Status2 +instance A.FromJSON E'Status2 where parseJSON o = P.either P.fail (pure . P.id) . toE'Status2 =<< A.parseJSON o +instance WH.ToHttpApiData E'Status2 where toQueryParam = WH.toQueryParam . fromE'Status2 +instance WH.FromHttpApiData E'Status2 where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'Status2 +instance MimeRender MimeMultipartFormData E'Status2 where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'Status2' enum +fromE'Status2 :: E'Status2 -> Text +fromE'Status2 = \case + E'Status2'Available -> "available" + E'Status2'Pending -> "pending" + E'Status2'Sold -> "sold" + +-- | parse 'E'Status2' enum +toE'Status2 :: Text -> P.Either String E'Status2 +toE'Status2 = \case + "available" -> P.Right E'Status2'Available + "pending" -> P.Right E'Status2'Pending + "sold" -> P.Right E'Status2'Sold + s -> P.Left $ "toE'Status2: enum parse failure: " P.++ P.show s + + +-- ** EnumClass + +-- | Enum of 'Text' +data EnumClass + = EnumClass'_abc -- ^ @"_abc"@ + | EnumClass'_efg -- ^ @"-efg"@ + | EnumClass'_xyz -- ^ @"(xyz)"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON EnumClass where toJSON = A.toJSON . fromEnumClass +instance A.FromJSON EnumClass where parseJSON o = P.either P.fail (pure . P.id) . toEnumClass =<< A.parseJSON o +instance WH.ToHttpApiData EnumClass where toQueryParam = WH.toQueryParam . fromEnumClass +instance WH.FromHttpApiData EnumClass where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toEnumClass +instance MimeRender MimeMultipartFormData EnumClass where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'EnumClass' enum +fromEnumClass :: EnumClass -> Text +fromEnumClass = \case + EnumClass'_abc -> "_abc" + EnumClass'_efg -> "-efg" + EnumClass'_xyz -> "(xyz)" + +-- | parse 'EnumClass' enum +toEnumClass :: Text -> P.Either String EnumClass +toEnumClass = \case + "_abc" -> P.Right EnumClass'_abc + "-efg" -> P.Right EnumClass'_efg + "(xyz)" -> P.Right EnumClass'_xyz + s -> P.Left $ "toEnumClass: enum parse failure: " P.++ P.show s + + +-- ** OuterEnum + +-- | Enum of 'Text' +data OuterEnum + = OuterEnum'Placed -- ^ @"placed"@ + | OuterEnum'Approved -- ^ @"approved"@ + | OuterEnum'Delivered -- ^ @"delivered"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON OuterEnum where toJSON = A.toJSON . fromOuterEnum +instance A.FromJSON OuterEnum where parseJSON o = P.either P.fail (pure . P.id) . toOuterEnum =<< A.parseJSON o +instance WH.ToHttpApiData OuterEnum where toQueryParam = WH.toQueryParam . fromOuterEnum +instance WH.FromHttpApiData OuterEnum where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toOuterEnum +instance MimeRender MimeMultipartFormData OuterEnum where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'OuterEnum' enum +fromOuterEnum :: OuterEnum -> Text +fromOuterEnum = \case + OuterEnum'Placed -> "placed" + OuterEnum'Approved -> "approved" + OuterEnum'Delivered -> "delivered" + +-- | parse 'OuterEnum' enum +toOuterEnum :: Text -> P.Either String OuterEnum +toOuterEnum = \case + "placed" -> P.Right OuterEnum'Placed + "approved" -> P.Right OuterEnum'Approved + "delivered" -> P.Right OuterEnum'Delivered + s -> P.Left $ "toOuterEnum: enum parse failure: " P.++ P.show s + \ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.ModelLens.html b/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.ModelLens.html index 79957636daf..1d31d78ad10 100644 --- a/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.ModelLens.html +++ b/samples/client/petstore/haskell-http-client/docs/src/SwaggerPetstore.ModelLens.html @@ -41,12 +41,12 @@ Module : SwaggerPetstore.Lens -- | 'additionalPropertiesClassMapProperty' Lens additionalPropertiesClassMapPropertyL :: Lens_' AdditionalPropertiesClass (Maybe (Map.Map String Text)) -additionalPropertiesClassMapPropertyL f AdditionalPropertiesClass{..} = (\additionalPropertiesClassMapProperty -> AdditionalPropertiesClass { additionalPropertiesClassMapProperty, ..} ) <$> f additionalPropertiesClassMapProperty +additionalPropertiesClassMapPropertyL f AdditionalPropertiesClass{..} = (\additionalPropertiesClassMapProperty -> AdditionalPropertiesClass { additionalPropertiesClassMapProperty, ..} ) <$> f additionalPropertiesClassMapProperty {-# INLINE additionalPropertiesClassMapPropertyL #-} -- | 'additionalPropertiesClassMapOfMapProperty' Lens additionalPropertiesClassMapOfMapPropertyL :: Lens_' AdditionalPropertiesClass (Maybe (Map.Map String (Map.Map String Text))) -additionalPropertiesClassMapOfMapPropertyL f AdditionalPropertiesClass{..} = (\additionalPropertiesClassMapOfMapProperty -> AdditionalPropertiesClass { additionalPropertiesClassMapOfMapProperty, ..} ) <$> f additionalPropertiesClassMapOfMapProperty +additionalPropertiesClassMapOfMapPropertyL f AdditionalPropertiesClass{..} = (\additionalPropertiesClassMapOfMapProperty -> AdditionalPropertiesClass { additionalPropertiesClassMapOfMapProperty, ..} ) <$> f additionalPropertiesClassMapOfMapProperty {-# INLINE additionalPropertiesClassMapOfMapPropertyL #-} @@ -55,12 +55,12 @@ Module : SwaggerPetstore.Lens -- | 'animalClassName' Lens animalClassNameL :: Lens_' Animal (Text) -animalClassNameL f Animal{..} = (\animalClassName -> Animal { animalClassName, ..} ) <$> f animalClassName +animalClassNameL f Animal{..} = (\animalClassName -> Animal { animalClassName, ..} ) <$> f animalClassName {-# INLINE animalClassNameL #-} -- | 'animalColor' Lens animalColorL :: Lens_' Animal (Maybe Text) -animalColorL f Animal{..} = (\animalColor -> Animal { animalColor, ..} ) <$> f animalColor +animalColorL f Animal{..} = (\animalColor -> Animal { animalColor, ..} ) <$> f animalColor {-# INLINE animalColorL #-} @@ -73,17 +73,17 @@ Module : SwaggerPetstore.Lens -- | 'apiResponseCode' Lens apiResponseCodeL :: Lens_' ApiResponse (Maybe Int) -apiResponseCodeL f ApiResponse{..} = (\apiResponseCode -> ApiResponse { apiResponseCode, ..} ) <$> f apiResponseCode +apiResponseCodeL f ApiResponse{..} = (\apiResponseCode -> ApiResponse { apiResponseCode, ..} ) <$> f apiResponseCode {-# INLINE apiResponseCodeL #-} -- | 'apiResponseType' Lens apiResponseTypeL :: Lens_' ApiResponse (Maybe Text) -apiResponseTypeL f ApiResponse{..} = (\apiResponseType -> ApiResponse { apiResponseType, ..} ) <$> f apiResponseType +apiResponseTypeL f ApiResponse{..} = (\apiResponseType -> ApiResponse { apiResponseType, ..} ) <$> f apiResponseType {-# INLINE apiResponseTypeL #-} -- | 'apiResponseMessage' Lens apiResponseMessageL :: Lens_' ApiResponse (Maybe Text) -apiResponseMessageL f ApiResponse{..} = (\apiResponseMessage -> ApiResponse { apiResponseMessage, ..} ) <$> f apiResponseMessage +apiResponseMessageL f ApiResponse{..} = (\apiResponseMessage -> ApiResponse { apiResponseMessage, ..} ) <$> f apiResponseMessage {-# INLINE apiResponseMessageL #-} @@ -92,7 +92,7 @@ Module : SwaggerPetstore.Lens -- | 'arrayOfArrayOfNumberOnlyArrayArrayNumber' Lens arrayOfArrayOfNumberOnlyArrayArrayNumberL :: Lens_' ArrayOfArrayOfNumberOnly (Maybe [[Double]]) -arrayOfArrayOfNumberOnlyArrayArrayNumberL f ArrayOfArrayOfNumberOnly{..} = (\arrayOfArrayOfNumberOnlyArrayArrayNumber -> ArrayOfArrayOfNumberOnly { arrayOfArrayOfNumberOnlyArrayArrayNumber, ..} ) <$> f arrayOfArrayOfNumberOnlyArrayArrayNumber +arrayOfArrayOfNumberOnlyArrayArrayNumberL f ArrayOfArrayOfNumberOnly{..} = (\arrayOfArrayOfNumberOnlyArrayArrayNumber -> ArrayOfArrayOfNumberOnly { arrayOfArrayOfNumberOnlyArrayArrayNumber, ..} ) <$> f arrayOfArrayOfNumberOnlyArrayArrayNumber {-# INLINE arrayOfArrayOfNumberOnlyArrayArrayNumberL #-} @@ -101,7 +101,7 @@ Module : SwaggerPetstore.Lens -- | 'arrayOfNumberOnlyArrayNumber' Lens arrayOfNumberOnlyArrayNumberL :: Lens_' ArrayOfNumberOnly (Maybe [Double]) -arrayOfNumberOnlyArrayNumberL f ArrayOfNumberOnly{..} = (\arrayOfNumberOnlyArrayNumber -> ArrayOfNumberOnly { arrayOfNumberOnlyArrayNumber, ..} ) <$> f arrayOfNumberOnlyArrayNumber +arrayOfNumberOnlyArrayNumberL f ArrayOfNumberOnly{..} = (\arrayOfNumberOnlyArrayNumber -> ArrayOfNumberOnly { arrayOfNumberOnlyArrayNumber, ..} ) <$> f arrayOfNumberOnlyArrayNumber {-# INLINE arrayOfNumberOnlyArrayNumberL #-} @@ -110,17 +110,17 @@ Module : SwaggerPetstore.Lens -- | 'arrayTestArrayOfString' Lens arrayTestArrayOfStringL :: Lens_' ArrayTest (Maybe [Text]) -arrayTestArrayOfStringL f ArrayTest{..} = (\arrayTestArrayOfString -> ArrayTest { arrayTestArrayOfString, ..} ) <$> f arrayTestArrayOfString +arrayTestArrayOfStringL f ArrayTest{..} = (\arrayTestArrayOfString -> ArrayTest { arrayTestArrayOfString, ..} ) <$> f arrayTestArrayOfString {-# INLINE arrayTestArrayOfStringL #-} -- | 'arrayTestArrayArrayOfInteger' Lens arrayTestArrayArrayOfIntegerL :: Lens_' ArrayTest (Maybe [[Integer]]) -arrayTestArrayArrayOfIntegerL f ArrayTest{..} = (\arrayTestArrayArrayOfInteger -> ArrayTest { arrayTestArrayArrayOfInteger, ..} ) <$> f arrayTestArrayArrayOfInteger +arrayTestArrayArrayOfIntegerL f ArrayTest{..} = (\arrayTestArrayArrayOfInteger -> ArrayTest { arrayTestArrayArrayOfInteger, ..} ) <$> f arrayTestArrayArrayOfInteger {-# INLINE arrayTestArrayArrayOfIntegerL #-} -- | 'arrayTestArrayArrayOfModel' Lens arrayTestArrayArrayOfModelL :: Lens_' ArrayTest (Maybe [[ReadOnlyFirst]]) -arrayTestArrayArrayOfModelL f ArrayTest{..} = (\arrayTestArrayArrayOfModel -> ArrayTest { arrayTestArrayArrayOfModel, ..} ) <$> f arrayTestArrayArrayOfModel +arrayTestArrayArrayOfModelL f ArrayTest{..} = (\arrayTestArrayArrayOfModel -> ArrayTest { arrayTestArrayArrayOfModel, ..} ) <$> f arrayTestArrayArrayOfModel {-# INLINE arrayTestArrayArrayOfModelL #-} @@ -129,32 +129,32 @@ Module : SwaggerPetstore.Lens -- | 'capitalizationSmallCamel' Lens capitalizationSmallCamelL :: Lens_' Capitalization (Maybe Text) -capitalizationSmallCamelL f Capitalization{..} = (\capitalizationSmallCamel -> Capitalization { capitalizationSmallCamel, ..} ) <$> f capitalizationSmallCamel +capitalizationSmallCamelL f Capitalization{..} = (\capitalizationSmallCamel -> Capitalization { capitalizationSmallCamel, ..} ) <$> f capitalizationSmallCamel {-# INLINE capitalizationSmallCamelL #-} -- | 'capitalizationCapitalCamel' Lens capitalizationCapitalCamelL :: Lens_' Capitalization (Maybe Text) -capitalizationCapitalCamelL f Capitalization{..} = (\capitalizationCapitalCamel -> Capitalization { capitalizationCapitalCamel, ..} ) <$> f capitalizationCapitalCamel +capitalizationCapitalCamelL f Capitalization{..} = (\capitalizationCapitalCamel -> Capitalization { capitalizationCapitalCamel, ..} ) <$> f capitalizationCapitalCamel {-# INLINE capitalizationCapitalCamelL #-} -- | 'capitalizationSmallSnake' Lens capitalizationSmallSnakeL :: Lens_' Capitalization (Maybe Text) -capitalizationSmallSnakeL f Capitalization{..} = (\capitalizationSmallSnake -> Capitalization { capitalizationSmallSnake, ..} ) <$> f capitalizationSmallSnake +capitalizationSmallSnakeL f Capitalization{..} = (\capitalizationSmallSnake -> Capitalization { capitalizationSmallSnake, ..} ) <$> f capitalizationSmallSnake {-# INLINE capitalizationSmallSnakeL #-} -- | 'capitalizationCapitalSnake' Lens capitalizationCapitalSnakeL :: Lens_' Capitalization (Maybe Text) -capitalizationCapitalSnakeL f Capitalization{..} = (\capitalizationCapitalSnake -> Capitalization { capitalizationCapitalSnake, ..} ) <$> f capitalizationCapitalSnake +capitalizationCapitalSnakeL f Capitalization{..} = (\capitalizationCapitalSnake -> Capitalization { capitalizationCapitalSnake, ..} ) <$> f capitalizationCapitalSnake {-# INLINE capitalizationCapitalSnakeL #-} -- | 'capitalizationScaEthFlowPoints' Lens capitalizationScaEthFlowPointsL :: Lens_' Capitalization (Maybe Text) -capitalizationScaEthFlowPointsL f Capitalization{..} = (\capitalizationScaEthFlowPoints -> Capitalization { capitalizationScaEthFlowPoints, ..} ) <$> f capitalizationScaEthFlowPoints +capitalizationScaEthFlowPointsL f Capitalization{..} = (\capitalizationScaEthFlowPoints -> Capitalization { capitalizationScaEthFlowPoints, ..} ) <$> f capitalizationScaEthFlowPoints {-# INLINE capitalizationScaEthFlowPointsL #-} -- | 'capitalizationAttName' Lens capitalizationAttNameL :: Lens_' Capitalization (Maybe Text) -capitalizationAttNameL f Capitalization{..} = (\capitalizationAttName -> Capitalization { capitalizationAttName, ..} ) <$> f capitalizationAttName +capitalizationAttNameL f Capitalization{..} = (\capitalizationAttName -> Capitalization { capitalizationAttName, ..} ) <$> f capitalizationAttName {-# INLINE capitalizationAttNameL #-} @@ -163,12 +163,12 @@ Module : SwaggerPetstore.Lens -- | 'categoryId' Lens categoryIdL :: Lens_' Category (Maybe Integer) -categoryIdL f Category{..} = (\categoryId -> Category { categoryId, ..} ) <$> f categoryId +categoryIdL f Category{..} = (\categoryId -> Category { categoryId, ..} ) <$> f categoryId {-# INLINE categoryIdL #-} -- | 'categoryName' Lens categoryNameL :: Lens_' Category (Maybe Text) -categoryNameL f Category{..} = (\categoryName -> Category { categoryName, ..} ) <$> f categoryName +categoryNameL f Category{..} = (\categoryName -> Category { categoryName, ..} ) <$> f categoryName {-# INLINE categoryNameL #-} @@ -177,7 +177,7 @@ Module : SwaggerPetstore.Lens -- | 'classModelClass' Lens classModelClassL :: Lens_' ClassModel (Maybe Text) -classModelClassL f ClassModel{..} = (\classModelClass -> ClassModel { classModelClass, ..} ) <$> f classModelClass +classModelClassL f ClassModel{..} = (\classModelClass -> ClassModel { classModelClass, ..} ) <$> f classModelClass {-# INLINE classModelClassL #-} @@ -186,7 +186,7 @@ Module : SwaggerPetstore.Lens -- | 'clientClient' Lens clientClientL :: Lens_' Client (Maybe Text) -clientClientL f Client{..} = (\clientClient -> Client { clientClient, ..} ) <$> f clientClient +clientClientL f Client{..} = (\clientClient -> Client { clientClient, ..} ) <$> f clientClient {-# INLINE clientClientL #-} @@ -194,13 +194,13 @@ Module : SwaggerPetstore.Lens -- * EnumArrays -- | 'enumArraysJustSymbol' Lens -enumArraysJustSymbolL :: Lens_' EnumArrays (Maybe Text) -enumArraysJustSymbolL f EnumArrays{..} = (\enumArraysJustSymbol -> EnumArrays { enumArraysJustSymbol, ..} ) <$> f enumArraysJustSymbol +enumArraysJustSymbolL :: Lens_' EnumArrays (Maybe E'JustSymbol) +enumArraysJustSymbolL f EnumArrays{..} = (\enumArraysJustSymbol -> EnumArrays { enumArraysJustSymbol, ..} ) <$> f enumArraysJustSymbol {-# INLINE enumArraysJustSymbolL #-} -- | 'enumArraysArrayEnum' Lens -enumArraysArrayEnumL :: Lens_' EnumArrays (Maybe [Text]) -enumArraysArrayEnumL f EnumArrays{..} = (\enumArraysArrayEnum -> EnumArrays { enumArraysArrayEnum, ..} ) <$> f enumArraysArrayEnum +enumArraysArrayEnumL :: Lens_' EnumArrays (Maybe [E'ArrayEnum]) +enumArraysArrayEnumL f EnumArrays{..} = (\enumArraysArrayEnum -> EnumArrays { enumArraysArrayEnum, ..} ) <$> f enumArraysArrayEnum {-# INLINE enumArraysArrayEnumL #-} @@ -212,23 +212,23 @@ Module : SwaggerPetstore.Lens -- * EnumTest -- | 'enumTestEnumString' Lens -enumTestEnumStringL :: Lens_' EnumTest (Maybe Text) -enumTestEnumStringL f EnumTest{..} = (\enumTestEnumString -> EnumTest { enumTestEnumString, ..} ) <$> f enumTestEnumString +enumTestEnumStringL :: Lens_' EnumTest (Maybe E'EnumString) +enumTestEnumStringL f EnumTest{..} = (\enumTestEnumString -> EnumTest { enumTestEnumString, ..} ) <$> f enumTestEnumString {-# INLINE enumTestEnumStringL #-} -- | 'enumTestEnumInteger' Lens -enumTestEnumIntegerL :: Lens_' EnumTest (Maybe Int) -enumTestEnumIntegerL f EnumTest{..} = (\enumTestEnumInteger -> EnumTest { enumTestEnumInteger, ..} ) <$> f enumTestEnumInteger +enumTestEnumIntegerL :: Lens_' EnumTest (Maybe E'EnumInteger) +enumTestEnumIntegerL f EnumTest{..} = (\enumTestEnumInteger -> EnumTest { enumTestEnumInteger, ..} ) <$> f enumTestEnumInteger {-# INLINE enumTestEnumIntegerL #-} -- | 'enumTestEnumNumber' Lens -enumTestEnumNumberL :: Lens_' EnumTest (Maybe Double) -enumTestEnumNumberL f EnumTest{..} = (\enumTestEnumNumber -> EnumTest { enumTestEnumNumber, ..} ) <$> f enumTestEnumNumber +enumTestEnumNumberL :: Lens_' EnumTest (Maybe E'EnumNumber) +enumTestEnumNumberL f EnumTest{..} = (\enumTestEnumNumber -> EnumTest { enumTestEnumNumber, ..} ) <$> f enumTestEnumNumber {-# INLINE enumTestEnumNumberL #-} -- | 'enumTestOuterEnum' Lens enumTestOuterEnumL :: Lens_' EnumTest (Maybe OuterEnum) -enumTestOuterEnumL f EnumTest{..} = (\enumTestOuterEnum -> EnumTest { enumTestOuterEnum, ..} ) <$> f enumTestOuterEnum +enumTestOuterEnumL f EnumTest{..} = (\enumTestOuterEnum -> EnumTest { enumTestOuterEnum, ..} ) <$> f enumTestOuterEnum {-# INLINE enumTestOuterEnumL #-} @@ -237,67 +237,67 @@ Module : SwaggerPetstore.Lens -- | 'formatTestInteger' Lens formatTestIntegerL :: Lens_' FormatTest (Maybe Int) -formatTestIntegerL f FormatTest{..} = (\formatTestInteger -> FormatTest { formatTestInteger, ..} ) <$> f formatTestInteger +formatTestIntegerL f FormatTest{..} = (\formatTestInteger -> FormatTest { formatTestInteger, ..} ) <$> f formatTestInteger {-# INLINE formatTestIntegerL #-} -- | 'formatTestInt32' Lens formatTestInt32L :: Lens_' FormatTest (Maybe Int) -formatTestInt32L f FormatTest{..} = (\formatTestInt32 -> FormatTest { formatTestInt32, ..} ) <$> f formatTestInt32 +formatTestInt32L f FormatTest{..} = (\formatTestInt32 -> FormatTest { formatTestInt32, ..} ) <$> f formatTestInt32 {-# INLINE formatTestInt32L #-} -- | 'formatTestInt64' Lens formatTestInt64L :: Lens_' FormatTest (Maybe Integer) -formatTestInt64L f FormatTest{..} = (\formatTestInt64 -> FormatTest { formatTestInt64, ..} ) <$> f formatTestInt64 +formatTestInt64L f FormatTest{..} = (\formatTestInt64 -> FormatTest { formatTestInt64, ..} ) <$> f formatTestInt64 {-# INLINE formatTestInt64L #-} -- | 'formatTestNumber' Lens formatTestNumberL :: Lens_' FormatTest (Double) -formatTestNumberL f FormatTest{..} = (\formatTestNumber -> FormatTest { formatTestNumber, ..} ) <$> f formatTestNumber +formatTestNumberL f FormatTest{..} = (\formatTestNumber -> FormatTest { formatTestNumber, ..} ) <$> f formatTestNumber {-# INLINE formatTestNumberL #-} -- | 'formatTestFloat' Lens formatTestFloatL :: Lens_' FormatTest (Maybe Float) -formatTestFloatL f FormatTest{..} = (\formatTestFloat -> FormatTest { formatTestFloat, ..} ) <$> f formatTestFloat +formatTestFloatL f FormatTest{..} = (\formatTestFloat -> FormatTest { formatTestFloat, ..} ) <$> f formatTestFloat {-# INLINE formatTestFloatL #-} -- | 'formatTestDouble' Lens formatTestDoubleL :: Lens_' FormatTest (Maybe Double) -formatTestDoubleL f FormatTest{..} = (\formatTestDouble -> FormatTest { formatTestDouble, ..} ) <$> f formatTestDouble +formatTestDoubleL f FormatTest{..} = (\formatTestDouble -> FormatTest { formatTestDouble, ..} ) <$> f formatTestDouble {-# INLINE formatTestDoubleL #-} -- | 'formatTestString' Lens formatTestStringL :: Lens_' FormatTest (Maybe Text) -formatTestStringL f FormatTest{..} = (\formatTestString -> FormatTest { formatTestString, ..} ) <$> f formatTestString +formatTestStringL f FormatTest{..} = (\formatTestString -> FormatTest { formatTestString, ..} ) <$> f formatTestString {-# INLINE formatTestStringL #-} -- | 'formatTestByte' Lens formatTestByteL :: Lens_' FormatTest (ByteArray) -formatTestByteL f FormatTest{..} = (\formatTestByte -> FormatTest { formatTestByte, ..} ) <$> f formatTestByte +formatTestByteL f FormatTest{..} = (\formatTestByte -> FormatTest { formatTestByte, ..} ) <$> f formatTestByte {-# INLINE formatTestByteL #-} -- | 'formatTestBinary' Lens formatTestBinaryL :: Lens_' FormatTest (Maybe Binary) -formatTestBinaryL f FormatTest{..} = (\formatTestBinary -> FormatTest { formatTestBinary, ..} ) <$> f formatTestBinary +formatTestBinaryL f FormatTest{..} = (\formatTestBinary -> FormatTest { formatTestBinary, ..} ) <$> f formatTestBinary {-# INLINE formatTestBinaryL #-} -- | 'formatTestDate' Lens formatTestDateL :: Lens_' FormatTest (Date) -formatTestDateL f FormatTest{..} = (\formatTestDate -> FormatTest { formatTestDate, ..} ) <$> f formatTestDate +formatTestDateL f FormatTest{..} = (\formatTestDate -> FormatTest { formatTestDate, ..} ) <$> f formatTestDate {-# INLINE formatTestDateL #-} -- | 'formatTestDateTime' Lens formatTestDateTimeL :: Lens_' FormatTest (Maybe DateTime) -formatTestDateTimeL f FormatTest{..} = (\formatTestDateTime -> FormatTest { formatTestDateTime, ..} ) <$> f formatTestDateTime +formatTestDateTimeL f FormatTest{..} = (\formatTestDateTime -> FormatTest { formatTestDateTime, ..} ) <$> f formatTestDateTime {-# INLINE formatTestDateTimeL #-} -- | 'formatTestUuid' Lens formatTestUuidL :: Lens_' FormatTest (Maybe Text) -formatTestUuidL f FormatTest{..} = (\formatTestUuid -> FormatTest { formatTestUuid, ..} ) <$> f formatTestUuid +formatTestUuidL f FormatTest{..} = (\formatTestUuid -> FormatTest { formatTestUuid, ..} ) <$> f formatTestUuid {-# INLINE formatTestUuidL #-} -- | 'formatTestPassword' Lens formatTestPasswordL :: Lens_' FormatTest (Text) -formatTestPasswordL f FormatTest{..} = (\formatTestPassword -> FormatTest { formatTestPassword, ..} ) <$> f formatTestPassword +formatTestPasswordL f FormatTest{..} = (\formatTestPassword -> FormatTest { formatTestPassword, ..} ) <$> f formatTestPassword {-# INLINE formatTestPasswordL #-} @@ -306,12 +306,12 @@ Module : SwaggerPetstore.Lens -- | 'hasOnlyReadOnlyBar' Lens hasOnlyReadOnlyBarL :: Lens_' HasOnlyReadOnly (Maybe Text) -hasOnlyReadOnlyBarL f HasOnlyReadOnly{..} = (\hasOnlyReadOnlyBar -> HasOnlyReadOnly { hasOnlyReadOnlyBar, ..} ) <$> f hasOnlyReadOnlyBar +hasOnlyReadOnlyBarL f HasOnlyReadOnly{..} = (\hasOnlyReadOnlyBar -> HasOnlyReadOnly { hasOnlyReadOnlyBar, ..} ) <$> f hasOnlyReadOnlyBar {-# INLINE hasOnlyReadOnlyBarL #-} -- | 'hasOnlyReadOnlyFoo' Lens hasOnlyReadOnlyFooL :: Lens_' HasOnlyReadOnly (Maybe Text) -hasOnlyReadOnlyFooL f HasOnlyReadOnly{..} = (\hasOnlyReadOnlyFoo -> HasOnlyReadOnly { hasOnlyReadOnlyFoo, ..} ) <$> f hasOnlyReadOnlyFoo +hasOnlyReadOnlyFooL f HasOnlyReadOnly{..} = (\hasOnlyReadOnlyFoo -> HasOnlyReadOnly { hasOnlyReadOnlyFoo, ..} ) <$> f hasOnlyReadOnlyFoo {-# INLINE hasOnlyReadOnlyFooL #-} @@ -320,12 +320,12 @@ Module : SwaggerPetstore.Lens -- | 'mapTestMapMapOfString' Lens mapTestMapMapOfStringL :: Lens_' MapTest (Maybe (Map.Map String (Map.Map String Text))) -mapTestMapMapOfStringL f MapTest{..} = (\mapTestMapMapOfString -> MapTest { mapTestMapMapOfString, ..} ) <$> f mapTestMapMapOfString +mapTestMapMapOfStringL f MapTest{..} = (\mapTestMapMapOfString -> MapTest { mapTestMapMapOfString, ..} ) <$> f mapTestMapMapOfString {-# INLINE mapTestMapMapOfStringL #-} -- | 'mapTestMapOfEnumString' Lens -mapTestMapOfEnumStringL :: Lens_' MapTest (Maybe (Map.Map String Text)) -mapTestMapOfEnumStringL f MapTest{..} = (\mapTestMapOfEnumString -> MapTest { mapTestMapOfEnumString, ..} ) <$> f mapTestMapOfEnumString +mapTestMapOfEnumStringL :: Lens_' MapTest (Maybe (Map.Map String E'Inner)) +mapTestMapOfEnumStringL f MapTest{..} = (\mapTestMapOfEnumString -> MapTest { mapTestMapOfEnumString, ..} ) <$> f mapTestMapOfEnumString {-# INLINE mapTestMapOfEnumStringL #-} @@ -334,17 +334,17 @@ Module : SwaggerPetstore.Lens -- | 'mixedPropertiesAndAdditionalPropertiesClassUuid' Lens mixedPropertiesAndAdditionalPropertiesClassUuidL :: Lens_' MixedPropertiesAndAdditionalPropertiesClass (Maybe Text) -mixedPropertiesAndAdditionalPropertiesClassUuidL f MixedPropertiesAndAdditionalPropertiesClass{..} = (\mixedPropertiesAndAdditionalPropertiesClassUuid -> MixedPropertiesAndAdditionalPropertiesClass { mixedPropertiesAndAdditionalPropertiesClassUuid, ..} ) <$> f mixedPropertiesAndAdditionalPropertiesClassUuid +mixedPropertiesAndAdditionalPropertiesClassUuidL f MixedPropertiesAndAdditionalPropertiesClass{..} = (\mixedPropertiesAndAdditionalPropertiesClassUuid -> MixedPropertiesAndAdditionalPropertiesClass { mixedPropertiesAndAdditionalPropertiesClassUuid, ..} ) <$> f mixedPropertiesAndAdditionalPropertiesClassUuid {-# INLINE mixedPropertiesAndAdditionalPropertiesClassUuidL #-} -- | 'mixedPropertiesAndAdditionalPropertiesClassDateTime' Lens mixedPropertiesAndAdditionalPropertiesClassDateTimeL :: Lens_' MixedPropertiesAndAdditionalPropertiesClass (Maybe DateTime) -mixedPropertiesAndAdditionalPropertiesClassDateTimeL f MixedPropertiesAndAdditionalPropertiesClass{..} = (\mixedPropertiesAndAdditionalPropertiesClassDateTime -> MixedPropertiesAndAdditionalPropertiesClass { mixedPropertiesAndAdditionalPropertiesClassDateTime, ..} ) <$> f mixedPropertiesAndAdditionalPropertiesClassDateTime +mixedPropertiesAndAdditionalPropertiesClassDateTimeL f MixedPropertiesAndAdditionalPropertiesClass{..} = (\mixedPropertiesAndAdditionalPropertiesClassDateTime -> MixedPropertiesAndAdditionalPropertiesClass { mixedPropertiesAndAdditionalPropertiesClassDateTime, ..} ) <$> f mixedPropertiesAndAdditionalPropertiesClassDateTime {-# INLINE mixedPropertiesAndAdditionalPropertiesClassDateTimeL #-} -- | 'mixedPropertiesAndAdditionalPropertiesClassMap' Lens mixedPropertiesAndAdditionalPropertiesClassMapL :: Lens_' MixedPropertiesAndAdditionalPropertiesClass (Maybe (Map.Map String Animal)) -mixedPropertiesAndAdditionalPropertiesClassMapL f MixedPropertiesAndAdditionalPropertiesClass{..} = (\mixedPropertiesAndAdditionalPropertiesClassMap -> MixedPropertiesAndAdditionalPropertiesClass { mixedPropertiesAndAdditionalPropertiesClassMap, ..} ) <$> f mixedPropertiesAndAdditionalPropertiesClassMap +mixedPropertiesAndAdditionalPropertiesClassMapL f MixedPropertiesAndAdditionalPropertiesClass{..} = (\mixedPropertiesAndAdditionalPropertiesClassMap -> MixedPropertiesAndAdditionalPropertiesClass { mixedPropertiesAndAdditionalPropertiesClassMap, ..} ) <$> f mixedPropertiesAndAdditionalPropertiesClassMap {-# INLINE mixedPropertiesAndAdditionalPropertiesClassMapL #-} @@ -353,12 +353,12 @@ Module : SwaggerPetstore.Lens -- | 'model200ResponseName' Lens model200ResponseNameL :: Lens_' Model200Response (Maybe Int) -model200ResponseNameL f Model200Response{..} = (\model200ResponseName -> Model200Response { model200ResponseName, ..} ) <$> f model200ResponseName +model200ResponseNameL f Model200Response{..} = (\model200ResponseName -> Model200Response { model200ResponseName, ..} ) <$> f model200ResponseName {-# INLINE model200ResponseNameL #-} -- | 'model200ResponseClass' Lens model200ResponseClassL :: Lens_' Model200Response (Maybe Text) -model200ResponseClassL f Model200Response{..} = (\model200ResponseClass -> Model200Response { model200ResponseClass, ..} ) <$> f model200ResponseClass +model200ResponseClassL f Model200Response{..} = (\model200ResponseClass -> Model200Response { model200ResponseClass, ..} ) <$> f model200ResponseClass {-# INLINE model200ResponseClassL #-} @@ -367,7 +367,7 @@ Module : SwaggerPetstore.Lens -- | 'modelList123List' Lens modelList123ListL :: Lens_' ModelList (Maybe Text) -modelList123ListL f ModelList{..} = (\modelList123List -> ModelList { modelList123List, ..} ) <$> f modelList123List +modelList123ListL f ModelList{..} = (\modelList123List -> ModelList { modelList123List, ..} ) <$> f modelList123List {-# INLINE modelList123ListL #-} @@ -376,7 +376,7 @@ Module : SwaggerPetstore.Lens -- | 'modelReturnReturn' Lens modelReturnReturnL :: Lens_' ModelReturn (Maybe Int) -modelReturnReturnL f ModelReturn{..} = (\modelReturnReturn -> ModelReturn { modelReturnReturn, ..} ) <$> f modelReturnReturn +modelReturnReturnL f ModelReturn{..} = (\modelReturnReturn -> ModelReturn { modelReturnReturn, ..} ) <$> f modelReturnReturn {-# INLINE modelReturnReturnL #-} @@ -385,22 +385,22 @@ Module : SwaggerPetstore.Lens -- | 'nameName' Lens nameNameL :: Lens_' Name (Int) -nameNameL f Name{..} = (\nameName -> Name { nameName, ..} ) <$> f nameName +nameNameL f Name{..} = (\nameName -> Name { nameName, ..} ) <$> f nameName {-# INLINE nameNameL #-} -- | 'nameSnakeCase' Lens nameSnakeCaseL :: Lens_' Name (Maybe Int) -nameSnakeCaseL f Name{..} = (\nameSnakeCase -> Name { nameSnakeCase, ..} ) <$> f nameSnakeCase +nameSnakeCaseL f Name{..} = (\nameSnakeCase -> Name { nameSnakeCase, ..} ) <$> f nameSnakeCase {-# INLINE nameSnakeCaseL #-} -- | 'nameProperty' Lens namePropertyL :: Lens_' Name (Maybe Text) -namePropertyL f Name{..} = (\nameProperty -> Name { nameProperty, ..} ) <$> f nameProperty +namePropertyL f Name{..} = (\nameProperty -> Name { nameProperty, ..} ) <$> f nameProperty {-# INLINE namePropertyL #-} -- | 'name123Number' Lens name123NumberL :: Lens_' Name (Maybe Int) -name123NumberL f Name{..} = (\name123Number -> Name { name123Number, ..} ) <$> f name123Number +name123NumberL f Name{..} = (\name123Number -> Name { name123Number, ..} ) <$> f name123Number {-# INLINE name123NumberL #-} @@ -409,7 +409,7 @@ Module : SwaggerPetstore.Lens -- | 'numberOnlyJustNumber' Lens numberOnlyJustNumberL :: Lens_' NumberOnly (Maybe Double) -numberOnlyJustNumberL f NumberOnly{..} = (\numberOnlyJustNumber -> NumberOnly { numberOnlyJustNumber, ..} ) <$> f numberOnlyJustNumber +numberOnlyJustNumberL f NumberOnly{..} = (\numberOnlyJustNumber -> NumberOnly { numberOnlyJustNumber, ..} ) <$> f numberOnlyJustNumber {-# INLINE numberOnlyJustNumberL #-} @@ -418,32 +418,32 @@ Module : SwaggerPetstore.Lens -- | 'orderId' Lens orderIdL :: Lens_' Order (Maybe Integer) -orderIdL f Order{..} = (\orderId -> Order { orderId, ..} ) <$> f orderId +orderIdL f Order{..} = (\orderId -> Order { orderId, ..} ) <$> f orderId {-# INLINE orderIdL #-} -- | 'orderPetId' Lens orderPetIdL :: Lens_' Order (Maybe Integer) -orderPetIdL f Order{..} = (\orderPetId -> Order { orderPetId, ..} ) <$> f orderPetId +orderPetIdL f Order{..} = (\orderPetId -> Order { orderPetId, ..} ) <$> f orderPetId {-# INLINE orderPetIdL #-} -- | 'orderQuantity' Lens orderQuantityL :: Lens_' Order (Maybe Int) -orderQuantityL f Order{..} = (\orderQuantity -> Order { orderQuantity, ..} ) <$> f orderQuantity +orderQuantityL f Order{..} = (\orderQuantity -> Order { orderQuantity, ..} ) <$> f orderQuantity {-# INLINE orderQuantityL #-} -- | 'orderShipDate' Lens orderShipDateL :: Lens_' Order (Maybe DateTime) -orderShipDateL f Order{..} = (\orderShipDate -> Order { orderShipDate, ..} ) <$> f orderShipDate +orderShipDateL f Order{..} = (\orderShipDate -> Order { orderShipDate, ..} ) <$> f orderShipDate {-# INLINE orderShipDateL #-} -- | 'orderStatus' Lens -orderStatusL :: Lens_' Order (Maybe Text) -orderStatusL f Order{..} = (\orderStatus -> Order { orderStatus, ..} ) <$> f orderStatus +orderStatusL :: Lens_' Order (Maybe E'Status) +orderStatusL f Order{..} = (\orderStatus -> Order { orderStatus, ..} ) <$> f orderStatus {-# INLINE orderStatusL #-} -- | 'orderComplete' Lens orderCompleteL :: Lens_' Order (Maybe Bool) -orderCompleteL f Order{..} = (\orderComplete -> Order { orderComplete, ..} ) <$> f orderComplete +orderCompleteL f Order{..} = (\orderComplete -> Order { orderComplete, ..} ) <$> f orderComplete {-# INLINE orderCompleteL #-} @@ -456,17 +456,17 @@ Module : SwaggerPetstore.Lens -- | 'outerCompositeMyNumber' Lens outerCompositeMyNumberL :: Lens_' OuterComposite (Maybe OuterNumber) -outerCompositeMyNumberL f OuterComposite{..} = (\outerCompositeMyNumber -> OuterComposite { outerCompositeMyNumber, ..} ) <$> f outerCompositeMyNumber +outerCompositeMyNumberL f OuterComposite{..} = (\outerCompositeMyNumber -> OuterComposite { outerCompositeMyNumber, ..} ) <$> f outerCompositeMyNumber {-# INLINE outerCompositeMyNumberL #-} -- | 'outerCompositeMyString' Lens outerCompositeMyStringL :: Lens_' OuterComposite (Maybe OuterString) -outerCompositeMyStringL f OuterComposite{..} = (\outerCompositeMyString -> OuterComposite { outerCompositeMyString, ..} ) <$> f outerCompositeMyString +outerCompositeMyStringL f OuterComposite{..} = (\outerCompositeMyString -> OuterComposite { outerCompositeMyString, ..} ) <$> f outerCompositeMyString {-# INLINE outerCompositeMyStringL #-} -- | 'outerCompositeMyBoolean' Lens outerCompositeMyBooleanL :: Lens_' OuterComposite (Maybe OuterBoolean) -outerCompositeMyBooleanL f OuterComposite{..} = (\outerCompositeMyBoolean -> OuterComposite { outerCompositeMyBoolean, ..} ) <$> f outerCompositeMyBoolean +outerCompositeMyBooleanL f OuterComposite{..} = (\outerCompositeMyBoolean -> OuterComposite { outerCompositeMyBoolean, ..} ) <$> f outerCompositeMyBoolean {-# INLINE outerCompositeMyBooleanL #-} @@ -487,32 +487,32 @@ Module : SwaggerPetstore.Lens -- | 'petId' Lens petIdL :: Lens_' Pet (Maybe Integer) -petIdL f Pet{..} = (\petId -> Pet { petId, ..} ) <$> f petId +petIdL f Pet{..} = (\petId -> Pet { petId, ..} ) <$> f petId {-# INLINE petIdL #-} -- | 'petCategory' Lens petCategoryL :: Lens_' Pet (Maybe Category) -petCategoryL f Pet{..} = (\petCategory -> Pet { petCategory, ..} ) <$> f petCategory +petCategoryL f Pet{..} = (\petCategory -> Pet { petCategory, ..} ) <$> f petCategory {-# INLINE petCategoryL #-} -- | 'petName' Lens petNameL :: Lens_' Pet (Text) -petNameL f Pet{..} = (\petName -> Pet { petName, ..} ) <$> f petName +petNameL f Pet{..} = (\petName -> Pet { petName, ..} ) <$> f petName {-# INLINE petNameL #-} -- | 'petPhotoUrls' Lens petPhotoUrlsL :: Lens_' Pet ([Text]) -petPhotoUrlsL f Pet{..} = (\petPhotoUrls -> Pet { petPhotoUrls, ..} ) <$> f petPhotoUrls +petPhotoUrlsL f Pet{..} = (\petPhotoUrls -> Pet { petPhotoUrls, ..} ) <$> f petPhotoUrls {-# INLINE petPhotoUrlsL #-} -- | 'petTags' Lens petTagsL :: Lens_' Pet (Maybe [Tag]) -petTagsL f Pet{..} = (\petTags -> Pet { petTags, ..} ) <$> f petTags +petTagsL f Pet{..} = (\petTags -> Pet { petTags, ..} ) <$> f petTags {-# INLINE petTagsL #-} -- | 'petStatus' Lens -petStatusL :: Lens_' Pet (Maybe Text) -petStatusL f Pet{..} = (\petStatus -> Pet { petStatus, ..} ) <$> f petStatus +petStatusL :: Lens_' Pet (Maybe E'Status2) +petStatusL f Pet{..} = (\petStatus -> Pet { petStatus, ..} ) <$> f petStatus {-# INLINE petStatusL #-} @@ -521,12 +521,12 @@ Module : SwaggerPetstore.Lens -- | 'readOnlyFirstBar' Lens readOnlyFirstBarL :: Lens_' ReadOnlyFirst (Maybe Text) -readOnlyFirstBarL f ReadOnlyFirst{..} = (\readOnlyFirstBar -> ReadOnlyFirst { readOnlyFirstBar, ..} ) <$> f readOnlyFirstBar +readOnlyFirstBarL f ReadOnlyFirst{..} = (\readOnlyFirstBar -> ReadOnlyFirst { readOnlyFirstBar, ..} ) <$> f readOnlyFirstBar {-# INLINE readOnlyFirstBarL #-} -- | 'readOnlyFirstBaz' Lens readOnlyFirstBazL :: Lens_' ReadOnlyFirst (Maybe Text) -readOnlyFirstBazL f ReadOnlyFirst{..} = (\readOnlyFirstBaz -> ReadOnlyFirst { readOnlyFirstBaz, ..} ) <$> f readOnlyFirstBaz +readOnlyFirstBazL f ReadOnlyFirst{..} = (\readOnlyFirstBaz -> ReadOnlyFirst { readOnlyFirstBaz, ..} ) <$> f readOnlyFirstBaz {-# INLINE readOnlyFirstBazL #-} @@ -535,7 +535,7 @@ Module : SwaggerPetstore.Lens -- | 'specialModelNameSpecialPropertyName' Lens specialModelNameSpecialPropertyNameL :: Lens_' SpecialModelName (Maybe Integer) -specialModelNameSpecialPropertyNameL f SpecialModelName{..} = (\specialModelNameSpecialPropertyName -> SpecialModelName { specialModelNameSpecialPropertyName, ..} ) <$> f specialModelNameSpecialPropertyName +specialModelNameSpecialPropertyNameL f SpecialModelName{..} = (\specialModelNameSpecialPropertyName -> SpecialModelName { specialModelNameSpecialPropertyName, ..} ) <$> f specialModelNameSpecialPropertyName {-# INLINE specialModelNameSpecialPropertyNameL #-} @@ -544,12 +544,12 @@ Module : SwaggerPetstore.Lens -- | 'tagId' Lens tagIdL :: Lens_' Tag (Maybe Integer) -tagIdL f Tag{..} = (\tagId -> Tag { tagId, ..} ) <$> f tagId +tagIdL f Tag{..} = (\tagId -> Tag { tagId, ..} ) <$> f tagId {-# INLINE tagIdL #-} -- | 'tagName' Lens tagNameL :: Lens_' Tag (Maybe Text) -tagNameL f Tag{..} = (\tagName -> Tag { tagName, ..} ) <$> f tagName +tagNameL f Tag{..} = (\tagName -> Tag { tagName, ..} ) <$> f tagName {-# INLINE tagNameL #-} @@ -558,42 +558,42 @@ Module : SwaggerPetstore.Lens -- | 'userId' Lens userIdL :: Lens_' User (Maybe Integer) -userIdL f User{..} = (\userId -> User { userId, ..} ) <$> f userId +userIdL f User{..} = (\userId -> User { userId, ..} ) <$> f userId {-# INLINE userIdL #-} -- | 'userUsername' Lens userUsernameL :: Lens_' User (Maybe Text) -userUsernameL f User{..} = (\userUsername -> User { userUsername, ..} ) <$> f userUsername +userUsernameL f User{..} = (\userUsername -> User { userUsername, ..} ) <$> f userUsername {-# INLINE userUsernameL #-} -- | 'userFirstName' Lens userFirstNameL :: Lens_' User (Maybe Text) -userFirstNameL f User{..} = (\userFirstName -> User { userFirstName, ..} ) <$> f userFirstName +userFirstNameL f User{..} = (\userFirstName -> User { userFirstName, ..} ) <$> f userFirstName {-# INLINE userFirstNameL #-} -- | 'userLastName' Lens userLastNameL :: Lens_' User (Maybe Text) -userLastNameL f User{..} = (\userLastName -> User { userLastName, ..} ) <$> f userLastName +userLastNameL f User{..} = (\userLastName -> User { userLastName, ..} ) <$> f userLastName {-# INLINE userLastNameL #-} -- | 'userEmail' Lens userEmailL :: Lens_' User (Maybe Text) -userEmailL f User{..} = (\userEmail -> User { userEmail, ..} ) <$> f userEmail +userEmailL f User{..} = (\userEmail -> User { userEmail, ..} ) <$> f userEmail {-# INLINE userEmailL #-} -- | 'userPassword' Lens userPasswordL :: Lens_' User (Maybe Text) -userPasswordL f User{..} = (\userPassword -> User { userPassword, ..} ) <$> f userPassword +userPasswordL f User{..} = (\userPassword -> User { userPassword, ..} ) <$> f userPassword {-# INLINE userPasswordL #-} -- | 'userPhone' Lens userPhoneL :: Lens_' User (Maybe Text) -userPhoneL f User{..} = (\userPhone -> User { userPhone, ..} ) <$> f userPhone +userPhoneL f User{..} = (\userPhone -> User { userPhone, ..} ) <$> f userPhone {-# INLINE userPhoneL #-} -- | 'userUserStatus' Lens userUserStatusL :: Lens_' User (Maybe Int) -userUserStatusL f User{..} = (\userUserStatus -> User { userUserStatus, ..} ) <$> f userUserStatus +userUserStatusL f User{..} = (\userUserStatus -> User { userUserStatus, ..} ) <$> f userUserStatus {-# INLINE userUserStatusL #-} @@ -602,17 +602,17 @@ Module : SwaggerPetstore.Lens -- | 'catClassName' Lens catClassNameL :: Lens_' Cat (Text) -catClassNameL f Cat{..} = (\catClassName -> Cat { catClassName, ..} ) <$> f catClassName +catClassNameL f Cat{..} = (\catClassName -> Cat { catClassName, ..} ) <$> f catClassName {-# INLINE catClassNameL #-} -- | 'catColor' Lens catColorL :: Lens_' Cat (Maybe Text) -catColorL f Cat{..} = (\catColor -> Cat { catColor, ..} ) <$> f catColor +catColorL f Cat{..} = (\catColor -> Cat { catColor, ..} ) <$> f catColor {-# INLINE catColorL #-} -- | 'catDeclawed' Lens catDeclawedL :: Lens_' Cat (Maybe Bool) -catDeclawedL f Cat{..} = (\catDeclawed -> Cat { catDeclawed, ..} ) <$> f catDeclawed +catDeclawedL f Cat{..} = (\catDeclawed -> Cat { catDeclawed, ..} ) <$> f catDeclawed {-# INLINE catDeclawedL #-} @@ -621,17 +621,17 @@ Module : SwaggerPetstore.Lens -- | 'dogClassName' Lens dogClassNameL :: Lens_' Dog (Text) -dogClassNameL f Dog{..} = (\dogClassName -> Dog { dogClassName, ..} ) <$> f dogClassName +dogClassNameL f Dog{..} = (\dogClassName -> Dog { dogClassName, ..} ) <$> f dogClassName {-# INLINE dogClassNameL #-} -- | 'dogColor' Lens dogColorL :: Lens_' Dog (Maybe Text) -dogColorL f Dog{..} = (\dogColor -> Dog { dogColor, ..} ) <$> f dogColor +dogColorL f Dog{..} = (\dogColor -> Dog { dogColor, ..} ) <$> f dogColor {-# INLINE dogColorL #-} -- | 'dogBreed' Lens dogBreedL :: Lens_' Dog (Maybe Text) -dogBreedL f Dog{..} = (\dogBreed -> Dog { dogBreed, ..} ) <$> f dogBreed +dogBreedL f Dog{..} = (\dogBreed -> Dog { dogBreed, ..} ) <$> f dogBreed {-# INLINE dogBreedL #-} diff --git a/samples/client/petstore/haskell-http-client/example-app/Main.hs b/samples/client/petstore/haskell-http-client/example-app/Main.hs index cf703a572d6..3518b97a3ef 100644 --- a/samples/client/petstore/haskell-http-client/example-app/Main.hs +++ b/samples/client/petstore/haskell-http-client/example-app/Main.hs @@ -59,17 +59,16 @@ main = do runPet :: NH.Manager -> S.SwaggerPetstoreConfig -> IO () runPet mgr config = do - -- create the request for addPet, encoded with content-type application/json - let addPetRequest = S.addPet S.MimeJSON (S.mkPet "name" ["url1", "url2"]) + -- create the request for addPet, encoded with content-type application/json, with accept header application/json + let addPetRequest = S.addPet (S.ContentType S.MimeJSON) (S.Accept S.MimeJSON) (S.mkPet "name" ["url1", "url2"]) - -- send the rquest with accept header application/json -- dispatchLbs simply returns the raw Network.HTTP.Client.Response ByteString - addPetResponse <- S.dispatchLbs mgr config addPetRequest S.MimeJSON + addPetResponse <- S.dispatchLbs mgr config addPetRequest -- the Consumes & Produces typeclasses control which 'content-type' -- and 'accept' encodings are allowed for each operation -- -- No instance for (S.Produces S.AddPet S.MimePlainText) - -- addPetResponse <- S.dispatchLbs mgr config addPetRequest S.MimePlainText + -- addPetResponse <- S.dispatchLbs mgr config addPetRequest -- inspect the AddPet type to see typeclasses indicating wihch -- content-type and accept types (mimeTypes) are valid @@ -94,31 +93,34 @@ runPet mgr config = do Right pet@S.Pet { S.petId = Just pid } -> do -- create the request for getPetById - let getPetByIdRequest = S.getPetById (S.PetId pid) + let getPetByIdRequest = S.getPetById (S.Accept S.MimeJSON) (S.PetId pid) -- dispatchMime returns MimeResult, which includes the -- expected decoded model object 'Pet', or a parse failure - getPetByIdRequestResult <- S.dispatchMime mgr config getPetByIdRequest S.MimeJSON + getPetByIdRequestResult <- S.dispatchMime mgr config getPetByIdRequest case S.mimeResult getPetByIdRequestResult of Left (S.MimeError _ _) -> return () -- parse error, already displayed in the log Right r -> putStrLn $ "getPetById: found pet: " <> show r -- display 'Pet' model object, r -- findPetsByStatus - let findPetsByStatusRequest = S.findPetsByStatus (S.Status ["available","pending","sold"]) - findPetsByStatusResult <- S.dispatchMime mgr config findPetsByStatusRequest S.MimeJSON + let findPetsByStatusRequest = S.findPetsByStatus (S.Accept S.MimeJSON) + (S.Status [ S.E'Status2'Available + , S.E'Status2'Pending + , S.E'Status2'Sold]) + findPetsByStatusResult <- S.dispatchMime mgr config findPetsByStatusRequest mapM_ (\r -> putStrLn $ "findPetsByStatus: found " <> (show . length) r <> " pets") findPetsByStatusResult -- findPetsByTags - let findPetsByTagsRequest = S.findPetsByTags (S.Tags ["name","tag1"]) - findPetsByTagsResult <- S.dispatchMime mgr config findPetsByTagsRequest S.MimeJSON + let findPetsByTagsRequest = S.findPetsByTags (S.Accept S.MimeJSON) (S.Tags ["name","tag1"]) + findPetsByTagsResult <- S.dispatchMime mgr config findPetsByTagsRequest mapM_ (\r -> putStrLn $ "findPetsByTags: found " <> (show . length) r <> " pets") findPetsByTagsResult -- updatePet - let updatePetRequest = S.updatePet S.MimeJSON $ pet - { S.petStatus = Just "available" + let updatePetRequest = S.updatePet (S.ContentType S.MimeJSON) (S.Accept S.MimeXML) $ pet + { S.petStatus = Just S.E'Status2'Available , S.petCategory = Just (S.Category (Just 3) (Just "catname")) } - _ <- S.dispatchLbs mgr config updatePetRequest S.MimeXML + _ <- S.dispatchLbs mgr config updatePetRequest -- requred parameters are included as function arguments, optional parameters are included with applyOptionalParam -- inspect the UpdatePetWithForm type to see typeclasses indicating optional paramteters (:i S.UpdatePetWithForm) @@ -126,22 +128,22 @@ runPet mgr config = do -- -- Defined in ‘SwaggerPetstore.API’ -- instance S.HasOptionalParam S.UpdatePetWithForm S.Status -- -- Defined in ‘SwaggerPetstore.API’ - let updatePetWithFormRequest = S.updatePetWithForm S.MimeFormUrlEncoded (S.PetId pid) + let updatePetWithFormRequest = S.updatePetWithForm (S.ContentType S.MimeFormUrlEncoded) (S.Accept S.MimeJSON) (S.PetId pid) `S.applyOptionalParam` S.Name2 "petName" `S.applyOptionalParam` S.StatusText "pending" - _ <- S.dispatchLbs mgr config updatePetWithFormRequest S.MimeJSON + _ <- S.dispatchLbs mgr config updatePetWithFormRequest -- multipart/form-data file uploads are just a different content-type - let uploadFileRequest = S.uploadFile S.MimeMultipartFormData (S.PetId pid) + let uploadFileRequest = S.uploadFile (S.ContentType S.MimeMultipartFormData) (S.Accept S.MimeJSON) (S.PetId pid) `S.applyOptionalParam` S.File "package.yaml" -- the file contents of the path are read when dispatched `S.applyOptionalParam` S.AdditionalMetadata "a package.yaml file" - uploadFileRequestResult <- S.dispatchMime mgr config uploadFileRequest S.MimeJSON + uploadFileRequestResult <- S.dispatchMime mgr config uploadFileRequest mapM_ (\r -> putStrLn $ "uploadFile: " <> show r) uploadFileRequestResult -- deletePet - let deletePetRequest = S.deletePet (S.PetId pid) + let deletePetRequest = S.deletePet (S.Accept S.MimeJSON) (S.PetId pid) `S.applyOptionalParam` S.ApiKey "api key" - _ <- S.dispatchLbs mgr config deletePetRequest S.MimeJSON + _ <- S.dispatchLbs mgr config deletePetRequest return () @@ -161,27 +163,27 @@ runStore :: NH.Manager -> S.SwaggerPetstoreConfig -> IO () runStore mgr config = do -- we can set arbitrary headers with setHeader - let getInventoryRequest = S.getInventory + let getInventoryRequest = S.getInventory (S.Accept S.MimeJSON) `S.setHeader` [("random-header","random-value")] - getInventoryRequestRequestResult <- S.dispatchMime mgr config getInventoryRequest S.MimeJSON + getInventoryRequestRequestResult <- S.dispatchMime mgr config getInventoryRequest mapM_ (\r -> putStrLn $ "getInventoryRequest: found " <> (show . length) r <> " results") getInventoryRequestRequestResult -- placeOrder now <- TI.getCurrentTime - let placeOrderRequest = S.placeOrder S.MimeJSON (S.mkOrder { S.orderId = Just 21, S.orderQuantity = Just 210, S.orderShipDate = Just (S.DateTime now)}) - placeOrderResult <- S.dispatchMime mgr config placeOrderRequest S.MimeJSON + let placeOrderRequest = S.placeOrder (S.ContentType S.MimeJSON) (S.Accept S.MimeJSON) (S.mkOrder { S.orderId = Just 21, S.orderQuantity = Just 210, S.orderShipDate = Just (S.DateTime now)}) + placeOrderResult <- S.dispatchMime mgr config placeOrderRequest mapM_ (\r -> putStrLn $ "placeOrderResult: " <> show r) placeOrderResult let orderId = maybe 10 id $ either (const Nothing) (S.orderId) (S.mimeResult placeOrderResult) -- getOrderByid - let getOrderByIdRequest = S.getOrderById (S.OrderId orderId) - getOrderByIdRequestResult <- S.dispatchMime mgr config getOrderByIdRequest S.MimeJSON + let getOrderByIdRequest = S.getOrderById (S.Accept S.MimeJSON) (S.OrderId orderId) + getOrderByIdRequestResult <- S.dispatchMime mgr config getOrderByIdRequest mapM_ (\r -> putStrLn $ "getOrderById: found order: " <> show r) getOrderByIdRequestResult -- deleteOrder - let deleteOrderRequest = S.deleteOrder (S.OrderIdText "21") - _ <- S.dispatchLbs mgr config deleteOrderRequest S.MimeJSON + let deleteOrderRequest = S.deleteOrder (S.Accept S.MimeJSON) (S.OrderIdText "21") + _ <- S.dispatchLbs mgr config deleteOrderRequest return () @@ -207,37 +209,37 @@ runUser mgr config = do let username = "hsusername" -- createUser let user = S.mkUser { S.userId = Just 21, S.userUsername = Just username } - let createUserRequest = S.createUser S.MimeJSON user - _ <- S.dispatchLbs mgr config createUserRequest S.MimeJSON + let createUserRequest = S.createUser (S.ContentType S.MimeJSON) (S.Accept S.MimeJSON) user + _ <- S.dispatchLbs mgr config createUserRequest -- can use lenses (model record names are appended L) to view or modify records let users = take 8 $ drop 1 $ iterate (L.over S.userUsernameL (fmap (<> "*")) . L.over S.userIdL (fmap (+ 1))) user - let createUsersWithArrayInputRequest = S.createUsersWithArrayInput S.MimeJSON (S.Body users) - _ <- S.dispatchLbs mgr config createUsersWithArrayInputRequest S.MimeNoContent + let createUsersWithArrayInputRequest = S.createUsersWithArrayInput (S.ContentType S.MimeJSON) (S.Accept S.MimeNoContent) (S.Body users) + _ <- S.dispatchLbs mgr config createUsersWithArrayInputRequest -- createUsersWithArrayInput - let createUsersWithListInputRequest = S.createUsersWithListInput S.MimeJSON (S.Body users) - _ <- S.dispatchLbs mgr config createUsersWithListInputRequest S.MimeNoContent + let createUsersWithListInputRequest = S.createUsersWithListInput (S.ContentType S.MimeJSON) (S.Accept S.MimeNoContent) (S.Body users) + _ <- S.dispatchLbs mgr config createUsersWithListInputRequest -- getUserByName - let getUserByNameRequest = S.getUserByName (S.Username username) - getUserByNameResult <- S.dispatchMime mgr config getUserByNameRequest S.MimeJSON + let getUserByNameRequest = S.getUserByName (S.Accept S.MimeJSON) (S.Username username) + getUserByNameResult <- S.dispatchMime mgr config getUserByNameRequest mapM_ (\r -> putStrLn $ "getUserByName: found user: " <> show r) getUserByNameResult -- loginUser - let loginUserRequest = S.loginUser (S.Username username) (S.Password "password1") - loginUserResult <- S.dispatchLbs mgr config loginUserRequest S.MimeJSON + let loginUserRequest = S.loginUser (S.Accept S.MimeJSON) (S.Username username) (S.Password "password1") + loginUserResult <- S.dispatchLbs mgr config loginUserRequest BCL.putStrLn $ "loginUser: " <> (NH.responseBody loginUserResult) -- updateUser - let updateUserRequest = S.updateUser S.MimeJSON (S.Username username) (user { S.userEmail = Just "xyz@example.com" }) - _ <- S.dispatchLbs mgr config updateUserRequest S.MimeJSON + let updateUserRequest = S.updateUser (S.ContentType S.MimeJSON) (S.Accept S.MimeJSON) (S.Username username) (user { S.userEmail = Just "xyz@example.com" }) + _ <- S.dispatchLbs mgr config updateUserRequest -- logoutUser - _ <- S.dispatchLbs mgr config S.logoutUser S.MimeJSON + _ <- S.dispatchLbs mgr config (S.logoutUser (S.Accept S.MimeJSON)) -- deleteUser - let deleteUserRequest = S.deleteUser (S.Username username) - _ <- S.dispatchLbs mgr config deleteUserRequest S.MimeJSON + let deleteUserRequest = S.deleteUser (S.Accept S.MimeJSON) (S.Username username) + _ <- S.dispatchLbs mgr config deleteUserRequest return () diff --git a/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/API.hs b/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/API.hs index afce16b8084..72cacd2ab60 100644 --- a/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/API.hs +++ b/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/API.hs @@ -80,10 +80,11 @@ import qualified Prelude as P -- testSpecialTags :: (Consumes TestSpecialTags contentType, MimeRender contentType Client) - => contentType -- ^ request content-type ('MimeType') + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') -> Client -- ^ "body" - client model - -> SwaggerPetstoreRequest TestSpecialTags contentType Client -testSpecialTags _ body = + -> SwaggerPetstoreRequest TestSpecialTags contentType Client accept +testSpecialTags _ _ body = _mkRequest "PATCH" ["/another-fake/dummy"] `setBodyParam` body @@ -109,9 +110,10 @@ instance Produces TestSpecialTags MimeJSON -- fakeOuterBooleanSerialize :: (Consumes FakeOuterBooleanSerialize contentType) - => contentType -- ^ request content-type ('MimeType') - -> SwaggerPetstoreRequest FakeOuterBooleanSerialize contentType OuterBoolean -fakeOuterBooleanSerialize _ = + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> SwaggerPetstoreRequest FakeOuterBooleanSerialize contentType OuterBoolean accept +fakeOuterBooleanSerialize _ _ = _mkRequest "POST" ["/fake/outer/boolean"] data FakeOuterBooleanSerialize @@ -127,9 +129,10 @@ instance HasBodyParam FakeOuterBooleanSerialize OuterBoolean -- fakeOuterCompositeSerialize :: (Consumes FakeOuterCompositeSerialize contentType) - => contentType -- ^ request content-type ('MimeType') - -> SwaggerPetstoreRequest FakeOuterCompositeSerialize contentType OuterComposite -fakeOuterCompositeSerialize _ = + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> SwaggerPetstoreRequest FakeOuterCompositeSerialize contentType OuterComposite accept +fakeOuterCompositeSerialize _ _ = _mkRequest "POST" ["/fake/outer/composite"] data FakeOuterCompositeSerialize @@ -145,9 +148,10 @@ instance HasBodyParam FakeOuterCompositeSerialize OuterComposite -- fakeOuterNumberSerialize :: (Consumes FakeOuterNumberSerialize contentType) - => contentType -- ^ request content-type ('MimeType') - -> SwaggerPetstoreRequest FakeOuterNumberSerialize contentType OuterNumber -fakeOuterNumberSerialize _ = + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> SwaggerPetstoreRequest FakeOuterNumberSerialize contentType OuterNumber accept +fakeOuterNumberSerialize _ _ = _mkRequest "POST" ["/fake/outer/number"] data FakeOuterNumberSerialize @@ -163,9 +167,10 @@ instance HasBodyParam FakeOuterNumberSerialize OuterNumber -- fakeOuterStringSerialize :: (Consumes FakeOuterStringSerialize contentType) - => contentType -- ^ request content-type ('MimeType') - -> SwaggerPetstoreRequest FakeOuterStringSerialize contentType OuterString -fakeOuterStringSerialize _ = + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> SwaggerPetstoreRequest FakeOuterStringSerialize contentType OuterString accept +fakeOuterStringSerialize _ _ = _mkRequest "POST" ["/fake/outer/string"] data FakeOuterStringSerialize @@ -183,10 +188,11 @@ instance HasBodyParam FakeOuterStringSerialize OuterString -- testClientModel :: (Consumes TestClientModel contentType, MimeRender contentType Client) - => contentType -- ^ request content-type ('MimeType') + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') -> Client -- ^ "body" - client model - -> SwaggerPetstoreRequest TestClientModel contentType Client -testClientModel _ body = + -> SwaggerPetstoreRequest TestClientModel contentType Client accept +testClientModel _ _ body = _mkRequest "PATCH" ["/fake"] `setBodyParam` body @@ -216,13 +222,14 @@ instance Produces TestClientModel MimeJSON -- testEndpointParameters :: (Consumes TestEndpointParameters contentType) - => contentType -- ^ request content-type ('MimeType') + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') -> Number -- ^ "number" - None -> ParamDouble -- ^ "double" - None -> PatternWithoutDelimiter -- ^ "patternWithoutDelimiter" - None -> Byte -- ^ "byte" - None - -> SwaggerPetstoreRequest TestEndpointParameters contentType res -testEndpointParameters _ (Number number) (ParamDouble double) (PatternWithoutDelimiter patternWithoutDelimiter) (Byte byte) = + -> SwaggerPetstoreRequest TestEndpointParameters contentType res accept +testEndpointParameters _ _ (Number number) (ParamDouble double) (PatternWithoutDelimiter patternWithoutDelimiter) (Byte byte) = _mkRequest "POST" ["/fake"] `_hasAuthType` (P.Proxy :: P.Proxy AuthBasicHttpBasicTest) `addForm` toForm ("number", number) @@ -305,9 +312,10 @@ instance Produces TestEndpointParameters MimeJsonCharsetutf8 -- testEnumParameters :: (Consumes TestEnumParameters contentType) - => contentType -- ^ request content-type ('MimeType') - -> SwaggerPetstoreRequest TestEnumParameters contentType res -testEnumParameters _ = + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') + -> SwaggerPetstoreRequest TestEnumParameters contentType res accept +testEnumParameters _ _ = _mkRequest "GET" ["/fake"] data TestEnumParameters @@ -359,6 +367,32 @@ instance Consumes TestEnumParameters MimeAny instance Produces TestEnumParameters MimeAny +-- *** testInlineAdditionalProperties + +-- | @POST \/fake\/inline-additionalProperties@ +-- +-- test inline additionalProperties +-- +-- +-- +testInlineAdditionalProperties + :: (Consumes TestInlineAdditionalProperties contentType, MimeRender contentType A.Value) + => ContentType contentType -- ^ request content-type ('MimeType') + -> A.Value -- ^ "param" - request body + -> SwaggerPetstoreRequest TestInlineAdditionalProperties contentType NoContent MimeNoContent +testInlineAdditionalProperties _ param = + _mkRequest "POST" ["/fake/inline-additionalProperties"] + `setBodyParam` param + +data TestInlineAdditionalProperties + +-- | /Body Param/ "param" - request body +instance HasBodyParam TestInlineAdditionalProperties A.Value + +-- | @application/json@ +instance Consumes TestInlineAdditionalProperties MimeJSON + + -- *** testJsonFormData -- | @GET \/fake\/jsonFormData@ @@ -369,10 +403,10 @@ instance Produces TestEnumParameters MimeAny -- testJsonFormData :: (Consumes TestJsonFormData contentType) - => contentType -- ^ request content-type ('MimeType') + => ContentType contentType -- ^ request content-type ('MimeType') -> Param -- ^ "param" - field1 -> Param2 -- ^ "param2" - field2 - -> SwaggerPetstoreRequest TestJsonFormData contentType NoContent + -> SwaggerPetstoreRequest TestJsonFormData contentType NoContent MimeNoContent testJsonFormData _ (Param param) (Param2 param2) = _mkRequest "GET" ["/fake/jsonFormData"] `addForm` toForm ("param", param) @@ -396,10 +430,11 @@ instance Consumes TestJsonFormData MimeJSON -- testClassname :: (Consumes TestClassname contentType, MimeRender contentType Client) - => contentType -- ^ request content-type ('MimeType') + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') -> Client -- ^ "body" - client model - -> SwaggerPetstoreRequest TestClassname contentType Client -testClassname _ body = + -> SwaggerPetstoreRequest TestClassname contentType Client accept +testClassname _ _ body = _mkRequest "PATCH" ["/fake_classname_test"] `_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyApiKeyQuery) `setBodyParam` body @@ -432,10 +467,11 @@ instance Produces TestClassname MimeJSON -- addPet :: (Consumes AddPet contentType, MimeRender contentType Pet) - => contentType -- ^ request content-type ('MimeType') + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') -> Pet -- ^ "body" - Pet object that needs to be added to the store - -> SwaggerPetstoreRequest AddPet contentType res -addPet _ body = + -> SwaggerPetstoreRequest AddPet contentType res accept +addPet _ _ body = _mkRequest "POST" ["/pet"] `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) `setBodyParam` body @@ -469,9 +505,10 @@ instance Produces AddPet MimeJSON -- Note: Has 'Produces' instances, but no response schema -- deletePet - :: PetId -- ^ "petId" - Pet id to delete - -> SwaggerPetstoreRequest DeletePet MimeNoContent res -deletePet (PetId petId) = + :: Accept accept -- ^ request accept ('MimeType') + -> PetId -- ^ "petId" - Pet id to delete + -> SwaggerPetstoreRequest DeletePet MimeNoContent res accept +deletePet _ (PetId petId) = _mkRequest "DELETE" ["/pet/",toPath petId] `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) @@ -496,9 +533,10 @@ instance Produces DeletePet MimeJSON -- AuthMethod: 'AuthOAuthPetstoreAuth' -- findPetsByStatus - :: Status -- ^ "status" - Status values that need to be considered for filter - -> SwaggerPetstoreRequest FindPetsByStatus MimeNoContent [Pet] -findPetsByStatus (Status status) = + :: Accept accept -- ^ request accept ('MimeType') + -> Status -- ^ "status" - Status values that need to be considered for filter + -> SwaggerPetstoreRequest FindPetsByStatus MimeNoContent [Pet] accept +findPetsByStatus _ (Status status) = _mkRequest "GET" ["/pet/findByStatus"] `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) `setQuery` toQueryColl CommaSeparated ("status", Just status) @@ -521,9 +559,10 @@ instance Produces FindPetsByStatus MimeJSON -- AuthMethod: 'AuthOAuthPetstoreAuth' -- findPetsByTags - :: Tags -- ^ "tags" - Tags to filter by - -> SwaggerPetstoreRequest FindPetsByTags MimeNoContent [Pet] -findPetsByTags (Tags tags) = + :: Accept accept -- ^ request accept ('MimeType') + -> Tags -- ^ "tags" - Tags to filter by + -> SwaggerPetstoreRequest FindPetsByTags MimeNoContent [Pet] accept +findPetsByTags _ (Tags tags) = _mkRequest "GET" ["/pet/findByTags"] `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) `setQuery` toQueryColl CommaSeparated ("tags", Just tags) @@ -548,9 +587,10 @@ instance Produces FindPetsByTags MimeJSON -- AuthMethod: 'AuthApiKeyApiKey' -- getPetById - :: PetId -- ^ "petId" - ID of pet to return - -> SwaggerPetstoreRequest GetPetById MimeNoContent Pet -getPetById (PetId petId) = + :: Accept accept -- ^ request accept ('MimeType') + -> PetId -- ^ "petId" - ID of pet to return + -> SwaggerPetstoreRequest GetPetById MimeNoContent Pet accept +getPetById _ (PetId petId) = _mkRequest "GET" ["/pet/",toPath petId] `_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyApiKey) @@ -575,10 +615,11 @@ instance Produces GetPetById MimeJSON -- updatePet :: (Consumes UpdatePet contentType, MimeRender contentType Pet) - => contentType -- ^ request content-type ('MimeType') + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') -> Pet -- ^ "body" - Pet object that needs to be added to the store - -> SwaggerPetstoreRequest UpdatePet contentType res -updatePet _ body = + -> SwaggerPetstoreRequest UpdatePet contentType res accept +updatePet _ _ body = _mkRequest "PUT" ["/pet"] `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) `setBodyParam` body @@ -613,10 +654,11 @@ instance Produces UpdatePet MimeJSON -- updatePetWithForm :: (Consumes UpdatePetWithForm contentType) - => contentType -- ^ request content-type ('MimeType') + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') -> PetId -- ^ "petId" - ID of pet that needs to be updated - -> SwaggerPetstoreRequest UpdatePetWithForm contentType res -updatePetWithForm _ (PetId petId) = + -> SwaggerPetstoreRequest UpdatePetWithForm contentType res accept +updatePetWithForm _ _ (PetId petId) = _mkRequest "POST" ["/pet/",toPath petId] `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) @@ -653,10 +695,11 @@ instance Produces UpdatePetWithForm MimeJSON -- uploadFile :: (Consumes UploadFile contentType) - => contentType -- ^ request content-type ('MimeType') + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') -> PetId -- ^ "petId" - ID of pet to update - -> SwaggerPetstoreRequest UploadFile contentType ApiResponse -uploadFile _ (PetId petId) = + -> SwaggerPetstoreRequest UploadFile contentType ApiResponse accept +uploadFile _ _ (PetId petId) = _mkRequest "POST" ["/pet/",toPath petId,"/uploadImage"] `_hasAuthType` (P.Proxy :: P.Proxy AuthOAuthPetstoreAuth) @@ -692,9 +735,10 @@ instance Produces UploadFile MimeJSON -- Note: Has 'Produces' instances, but no response schema -- deleteOrder - :: OrderIdText -- ^ "orderId" - ID of the order that needs to be deleted - -> SwaggerPetstoreRequest DeleteOrder MimeNoContent res -deleteOrder (OrderIdText orderId) = + :: Accept accept -- ^ request accept ('MimeType') + -> OrderIdText -- ^ "orderId" - ID of the order that needs to be deleted + -> SwaggerPetstoreRequest DeleteOrder MimeNoContent res accept +deleteOrder _ (OrderIdText orderId) = _mkRequest "DELETE" ["/store/order/",toPath orderId] data DeleteOrder @@ -715,8 +759,9 @@ instance Produces DeleteOrder MimeJSON -- AuthMethod: 'AuthApiKeyApiKey' -- getInventory - :: SwaggerPetstoreRequest GetInventory MimeNoContent ((Map.Map String Int)) -getInventory = + :: Accept accept -- ^ request accept ('MimeType') + -> SwaggerPetstoreRequest GetInventory MimeNoContent ((Map.Map String Int)) accept +getInventory _ = _mkRequest "GET" ["/store/inventory"] `_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyApiKey) @@ -734,9 +779,10 @@ instance Produces GetInventory MimeJSON -- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions -- getOrderById - :: OrderId -- ^ "orderId" - ID of pet that needs to be fetched - -> SwaggerPetstoreRequest GetOrderById MimeNoContent Order -getOrderById (OrderId orderId) = + :: Accept accept -- ^ request accept ('MimeType') + -> OrderId -- ^ "orderId" - ID of pet that needs to be fetched + -> SwaggerPetstoreRequest GetOrderById MimeNoContent Order accept +getOrderById _ (OrderId orderId) = _mkRequest "GET" ["/store/order/",toPath orderId] data GetOrderById @@ -756,10 +802,11 @@ instance Produces GetOrderById MimeJSON -- placeOrder :: (Consumes PlaceOrder contentType, MimeRender contentType Order) - => contentType -- ^ request content-type ('MimeType') + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') -> Order -- ^ "body" - order placed for purchasing the pet - -> SwaggerPetstoreRequest PlaceOrder contentType Order -placeOrder _ body = + -> SwaggerPetstoreRequest PlaceOrder contentType Order accept +placeOrder _ _ body = _mkRequest "POST" ["/store/order"] `setBodyParam` body @@ -787,10 +834,11 @@ instance Produces PlaceOrder MimeJSON -- createUser :: (Consumes CreateUser contentType, MimeRender contentType User) - => contentType -- ^ request content-type ('MimeType') + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') -> User -- ^ "body" - Created user object - -> SwaggerPetstoreRequest CreateUser contentType res -createUser _ body = + -> SwaggerPetstoreRequest CreateUser contentType res accept +createUser _ _ body = _mkRequest "POST" ["/user"] `setBodyParam` body @@ -816,10 +864,11 @@ instance Produces CreateUser MimeJSON -- createUsersWithArrayInput :: (Consumes CreateUsersWithArrayInput contentType, MimeRender contentType Body) - => contentType -- ^ request content-type ('MimeType') + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') -> Body -- ^ "body" - List of user object - -> SwaggerPetstoreRequest CreateUsersWithArrayInput contentType res -createUsersWithArrayInput _ body = + -> SwaggerPetstoreRequest CreateUsersWithArrayInput contentType res accept +createUsersWithArrayInput _ _ body = _mkRequest "POST" ["/user/createWithArray"] `setBodyParam` body @@ -845,10 +894,11 @@ instance Produces CreateUsersWithArrayInput MimeJSON -- createUsersWithListInput :: (Consumes CreateUsersWithListInput contentType, MimeRender contentType Body) - => contentType -- ^ request content-type ('MimeType') + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') -> Body -- ^ "body" - List of user object - -> SwaggerPetstoreRequest CreateUsersWithListInput contentType res -createUsersWithListInput _ body = + -> SwaggerPetstoreRequest CreateUsersWithListInput contentType res accept +createUsersWithListInput _ _ body = _mkRequest "POST" ["/user/createWithList"] `setBodyParam` body @@ -873,9 +923,10 @@ instance Produces CreateUsersWithListInput MimeJSON -- Note: Has 'Produces' instances, but no response schema -- deleteUser - :: Username -- ^ "username" - The name that needs to be deleted - -> SwaggerPetstoreRequest DeleteUser MimeNoContent res -deleteUser (Username username) = + :: Accept accept -- ^ request accept ('MimeType') + -> Username -- ^ "username" - The name that needs to be deleted + -> SwaggerPetstoreRequest DeleteUser MimeNoContent res accept +deleteUser _ (Username username) = _mkRequest "DELETE" ["/user/",toPath username] data DeleteUser @@ -894,9 +945,10 @@ instance Produces DeleteUser MimeJSON -- -- getUserByName - :: Username -- ^ "username" - The name that needs to be fetched. Use user1 for testing. - -> SwaggerPetstoreRequest GetUserByName MimeNoContent User -getUserByName (Username username) = + :: Accept accept -- ^ request accept ('MimeType') + -> Username -- ^ "username" - The name that needs to be fetched. Use user1 for testing. + -> SwaggerPetstoreRequest GetUserByName MimeNoContent User accept +getUserByName _ (Username username) = _mkRequest "GET" ["/user/",toPath username] data GetUserByName @@ -915,10 +967,11 @@ instance Produces GetUserByName MimeJSON -- -- loginUser - :: Username -- ^ "username" - The user name for login + :: Accept accept -- ^ request accept ('MimeType') + -> Username -- ^ "username" - The user name for login -> Password -- ^ "password" - The password for login in clear text - -> SwaggerPetstoreRequest LoginUser MimeNoContent Text -loginUser (Username username) (Password password) = + -> SwaggerPetstoreRequest LoginUser MimeNoContent Text accept +loginUser _ (Username username) (Password password) = _mkRequest "GET" ["/user/login"] `setQuery` toQuery ("username", Just username) `setQuery` toQuery ("password", Just password) @@ -941,8 +994,9 @@ instance Produces LoginUser MimeJSON -- Note: Has 'Produces' instances, but no response schema -- logoutUser - :: SwaggerPetstoreRequest LogoutUser MimeNoContent res -logoutUser = + :: Accept accept -- ^ request accept ('MimeType') + -> SwaggerPetstoreRequest LogoutUser MimeNoContent res accept +logoutUser _ = _mkRequest "GET" ["/user/logout"] data LogoutUser @@ -964,11 +1018,12 @@ instance Produces LogoutUser MimeJSON -- updateUser :: (Consumes UpdateUser contentType, MimeRender contentType User) - => contentType -- ^ request content-type ('MimeType') + => ContentType contentType -- ^ request content-type ('MimeType') + -> Accept accept -- ^ request accept ('MimeType') -> Username -- ^ "username" - name that need to be deleted -> User -- ^ "body" - Updated user object - -> SwaggerPetstoreRequest UpdateUser contentType res -updateUser _ (Username username) body = + -> SwaggerPetstoreRequest UpdateUser contentType res accept +updateUser _ _ (Username username) body = _mkRequest "PUT" ["/user/",toPath username] `setBodyParam` body @@ -990,14 +1045,14 @@ newtype ApiKey = ApiKey { unApiKey :: Text } deriving (P.Eq, P.Show) newtype Body = Body { unBody :: [User] } deriving (P.Eq, P.Show, A.ToJSON) newtype Byte = Byte { unByte :: ByteArray } deriving (P.Eq, P.Show) newtype Callback = Callback { unCallback :: Text } deriving (P.Eq, P.Show) -newtype EnumFormString = EnumFormString { unEnumFormString :: Text } deriving (P.Eq, P.Show) -newtype EnumFormStringArray = EnumFormStringArray { unEnumFormStringArray :: [Text] } deriving (P.Eq, P.Show) -newtype EnumHeaderString = EnumHeaderString { unEnumHeaderString :: Text } deriving (P.Eq, P.Show) -newtype EnumHeaderStringArray = EnumHeaderStringArray { unEnumHeaderStringArray :: [Text] } deriving (P.Eq, P.Show) -newtype EnumQueryDouble = EnumQueryDouble { unEnumQueryDouble :: Double } deriving (P.Eq, P.Show) -newtype EnumQueryInteger = EnumQueryInteger { unEnumQueryInteger :: Int } deriving (P.Eq, P.Show) -newtype EnumQueryString = EnumQueryString { unEnumQueryString :: Text } deriving (P.Eq, P.Show) -newtype EnumQueryStringArray = EnumQueryStringArray { unEnumQueryStringArray :: [Text] } deriving (P.Eq, P.Show) +newtype EnumFormString = EnumFormString { unEnumFormString :: E'EnumFormString } deriving (P.Eq, P.Show) +newtype EnumFormStringArray = EnumFormStringArray { unEnumFormStringArray :: [E'Inner2] } deriving (P.Eq, P.Show) +newtype EnumHeaderString = EnumHeaderString { unEnumHeaderString :: E'EnumFormString } deriving (P.Eq, P.Show) +newtype EnumHeaderStringArray = EnumHeaderStringArray { unEnumHeaderStringArray :: [E'Inner2] } deriving (P.Eq, P.Show) +newtype EnumQueryDouble = EnumQueryDouble { unEnumQueryDouble :: E'EnumNumber } deriving (P.Eq, P.Show) +newtype EnumQueryInteger = EnumQueryInteger { unEnumQueryInteger :: E'EnumQueryInteger } deriving (P.Eq, P.Show) +newtype EnumQueryString = EnumQueryString { unEnumQueryString :: E'EnumFormString } deriving (P.Eq, P.Show) +newtype EnumQueryStringArray = EnumQueryStringArray { unEnumQueryStringArray :: [E'Inner2] } deriving (P.Eq, P.Show) newtype File = File { unFile :: FilePath } deriving (P.Eq, P.Show) newtype Int32 = Int32 { unInt32 :: Int } deriving (P.Eq, P.Show) newtype Int64 = Int64 { unInt64 :: Integer } deriving (P.Eq, P.Show) @@ -1017,7 +1072,7 @@ newtype ParamString = ParamString { unParamString :: Text } deriving (P.Eq, P.Sh newtype Password = Password { unPassword :: Text } deriving (P.Eq, P.Show) newtype PatternWithoutDelimiter = PatternWithoutDelimiter { unPatternWithoutDelimiter :: Text } deriving (P.Eq, P.Show) newtype PetId = PetId { unPetId :: Integer } deriving (P.Eq, P.Show) -newtype Status = Status { unStatus :: [Text] } deriving (P.Eq, P.Show) +newtype Status = Status { unStatus :: [E'Status2] } deriving (P.Eq, P.Show) newtype StatusText = StatusText { unStatusText :: Text } deriving (P.Eq, P.Show) newtype Tags = Tags { unTags :: [Text] } deriving (P.Eq, P.Show) newtype Username = Username { unUsername :: Text } deriving (P.Eq, P.Show) diff --git a/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/Client.hs b/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/Client.hs index ad1041e7bc4..b78c10f15cd 100644 --- a/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/Client.hs +++ b/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/Client.hs @@ -59,11 +59,10 @@ dispatchLbs :: (Produces req accept, MimeType contentType) => NH.Manager -- ^ http-client Connection manager -> SwaggerPetstoreConfig -- ^ config - -> SwaggerPetstoreRequest req contentType res -- ^ request - -> accept -- ^ "accept" 'MimeType' + -> SwaggerPetstoreRequest req contentType res accept -- ^ request -> IO (NH.Response BCL.ByteString) -- ^ response -dispatchLbs manager config request accept = do - initReq <- _toInitRequest config request accept +dispatchLbs manager config request = do + initReq <- _toInitRequest config request dispatchInitUnsafe manager config initReq -- ** Mime @@ -84,21 +83,26 @@ data MimeError = -- | send a request returning the 'MimeResult' dispatchMime - :: (Produces req accept, MimeUnrender accept res, MimeType contentType) + :: forall req contentType res accept. (Produces req accept, MimeUnrender accept res, MimeType contentType) => NH.Manager -- ^ http-client Connection manager -> SwaggerPetstoreConfig -- ^ config - -> SwaggerPetstoreRequest req contentType res -- ^ request - -> accept -- ^ "accept" 'MimeType' + -> SwaggerPetstoreRequest req contentType res accept -- ^ request -> IO (MimeResult res) -- ^ response -dispatchMime manager config request accept = do - httpResponse <- dispatchLbs manager config request accept +dispatchMime manager config request = do + httpResponse <- dispatchLbs manager config request + let statusCode = NH.statusCode . NH.responseStatus $ httpResponse parsedResult <- runConfigLogWithExceptions "Client" config $ - do case mimeUnrender' accept (NH.responseBody httpResponse) of - Left s -> do + do if (statusCode >= 400 && statusCode < 600) + then do + let s = "error statusCode: " ++ show statusCode _log "Client" levelError (T.pack s) pure (Left (MimeError s httpResponse)) - Right r -> pure (Right r) + else case mimeUnrender (P.Proxy :: P.Proxy accept) (NH.responseBody httpResponse) of + Left s -> do + _log "Client" levelError (T.pack s) + pure (Left (MimeError s httpResponse)) + Right r -> pure (Right r) return (MimeResult parsedResult httpResponse) -- | like 'dispatchMime', but only returns the decoded http body @@ -106,11 +110,10 @@ dispatchMime' :: (Produces req accept, MimeUnrender accept res, MimeType contentType) => NH.Manager -- ^ http-client Connection manager -> SwaggerPetstoreConfig -- ^ config - -> SwaggerPetstoreRequest req contentType res -- ^ request - -> accept -- ^ "accept" 'MimeType' + -> SwaggerPetstoreRequest req contentType res accept -- ^ request -> IO (Either MimeError res) -- ^ response -dispatchMime' manager config request accept = do - MimeResult parsedResult _ <- dispatchMime manager config request accept +dispatchMime' manager config request = do + MimeResult parsedResult _ <- dispatchMime manager config request return parsedResult -- ** Unsafe @@ -120,11 +123,10 @@ dispatchLbsUnsafe :: (MimeType accept, MimeType contentType) => NH.Manager -- ^ http-client Connection manager -> SwaggerPetstoreConfig -- ^ config - -> SwaggerPetstoreRequest req contentType res -- ^ request - -> accept -- ^ "accept" 'MimeType' + -> SwaggerPetstoreRequest req contentType res accept -- ^ request -> IO (NH.Response BCL.ByteString) -- ^ response -dispatchLbsUnsafe manager config request accept = do - initReq <- _toInitRequest config request accept +dispatchLbsUnsafe manager config request = do + initReq <- _toInitRequest config request dispatchInitUnsafe manager config initReq -- | dispatch an InitRequest @@ -168,17 +170,16 @@ newtype InitRequest req contentType res accept = InitRequest _toInitRequest :: (MimeType accept, MimeType contentType) => SwaggerPetstoreConfig -- ^ config - -> SwaggerPetstoreRequest req contentType res -- ^ request - -> accept -- ^ "accept" 'MimeType' + -> SwaggerPetstoreRequest req contentType res accept -- ^ request -> IO (InitRequest req contentType res accept) -- ^ initialized request -_toInitRequest config req0 accept = +_toInitRequest config req0 = runConfigLogWithExceptions "Client" config $ do parsedReq <- P.liftIO $ NH.parseRequest $ BCL.unpack $ BCL.append (configHost config) (BCL.concat (rUrlPath req0)) req1 <- P.liftIO $ _applyAuthMethods req0 config P.when (configValidateAuthMethods config && (not . null . rAuthTypes) req1) - (E.throwString $ "AuthMethod not configured: " <> (show . head . rAuthTypes) req1) - let req2 = req1 & _setContentTypeHeader & flip _setAcceptHeader accept + (E.throw $ AuthMethodException $ "AuthMethod not configured: " <> (show . head . rAuthTypes) req1) + let req2 = req1 & _setContentTypeHeader & _setAcceptHeader reqHeaders = ("User-Agent", WH.toHeader (configUserAgent config)) : paramsHeaders (rParams req2) reqQuery = NH.renderQuery True (paramsQuery (rParams req2)) pReq = parsedReq { NH.method = (rMethod req2) @@ -195,7 +196,7 @@ _toInitRequest config req0 accept = pure (InitRequest outReq) -- | modify the underlying Request -modifyInitRequest :: InitRequest req contentType res accept -> (NH.Request -> NH.Request) -> InitRequest req contentType res accept +modifyInitRequest :: InitRequest req contentType res accept -> (NH.Request -> NH.Request) -> InitRequest req contentType res accept modifyInitRequest (InitRequest req) f = InitRequest (f req) -- | modify the underlying Request (monadic) diff --git a/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/Core.hs b/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/Core.hs index db3e935068b..3e540481c55 100644 --- a/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/Core.hs +++ b/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/Core.hs @@ -33,6 +33,7 @@ import SwaggerPetstore.Logging import qualified Control.Arrow as P (left) import qualified Control.DeepSeq as NF +import qualified Control.Exception.Safe as E import qualified Data.Aeson as A import qualified Data.ByteString as B import qualified Data.ByteString.Base64.Lazy as BL64 @@ -132,8 +133,15 @@ withNoLogging p = p { configLogExecWithContext = runNullLogExec} -- * SwaggerPetstoreRequest --- | Represents a request. The "req" type variable is the request type. The "res" type variable is the response type. -data SwaggerPetstoreRequest req contentType res = SwaggerPetstoreRequest +-- | Represents a request. +-- +-- Type Variables: +-- +-- * req - request operation +-- * contentType - 'MimeType' associated with request body +-- * res - response model +-- * accept - 'MimeType' associated with response body +data SwaggerPetstoreRequest req contentType res accept = SwaggerPetstoreRequest { rMethod :: NH.Method -- ^ Method of SwaggerPetstoreRequest , rUrlPath :: [BCL.ByteString] -- ^ Endpoint of SwaggerPetstoreRequest , rParams :: Params -- ^ params of SwaggerPetstoreRequest @@ -142,22 +150,22 @@ data SwaggerPetstoreRequest req contentType res = SwaggerPetstoreRequest deriving (P.Show) -- | 'rMethod' Lens -rMethodL :: Lens_' (SwaggerPetstoreRequest req contentType res) NH.Method +rMethodL :: Lens_' (SwaggerPetstoreRequest req contentType res accept) NH.Method rMethodL f SwaggerPetstoreRequest{..} = (\rMethod -> SwaggerPetstoreRequest { rMethod, ..} ) <$> f rMethod {-# INLINE rMethodL #-} -- | 'rUrlPath' Lens -rUrlPathL :: Lens_' (SwaggerPetstoreRequest req contentType res) [BCL.ByteString] +rUrlPathL :: Lens_' (SwaggerPetstoreRequest req contentType res accept) [BCL.ByteString] rUrlPathL f SwaggerPetstoreRequest{..} = (\rUrlPath -> SwaggerPetstoreRequest { rUrlPath, ..} ) <$> f rUrlPath {-# INLINE rUrlPathL #-} -- | 'rParams' Lens -rParamsL :: Lens_' (SwaggerPetstoreRequest req contentType res) Params +rParamsL :: Lens_' (SwaggerPetstoreRequest req contentType res accept) Params rParamsL f SwaggerPetstoreRequest{..} = (\rParams -> SwaggerPetstoreRequest { rParams, ..} ) <$> f rParams {-# INLINE rParamsL #-} -- | 'rParams' Lens -rAuthTypesL :: Lens_' (SwaggerPetstoreRequest req contentType res) [P.TypeRep] +rAuthTypesL :: Lens_' (SwaggerPetstoreRequest req contentType res accept) [P.TypeRep] rAuthTypesL f SwaggerPetstoreRequest{..} = (\rAuthTypes -> SwaggerPetstoreRequest { rAuthTypes, ..} ) <$> f rAuthTypes {-# INLINE rAuthTypesL #-} @@ -165,7 +173,7 @@ rAuthTypesL f SwaggerPetstoreRequest{..} = (\rAuthTypes -> SwaggerPetstoreReques -- | Designates the body parameter of a request class HasBodyParam req param where - setBodyParam :: forall contentType res. (Consumes req contentType, MimeRender contentType param) => SwaggerPetstoreRequest req contentType res -> param -> SwaggerPetstoreRequest req contentType res + setBodyParam :: forall contentType res accept. (Consumes req contentType, MimeRender contentType param) => SwaggerPetstoreRequest req contentType res accept -> param -> SwaggerPetstoreRequest req contentType res accept setBodyParam req xs = req `_setBodyLBS` mimeRender (P.Proxy :: P.Proxy contentType) xs & _setContentTypeHeader @@ -176,12 +184,12 @@ class HasOptionalParam req param where {-# MINIMAL applyOptionalParam | (-&-) #-} -- | Apply an optional parameter to a request - applyOptionalParam :: SwaggerPetstoreRequest req contentType res -> param -> SwaggerPetstoreRequest req contentType res + applyOptionalParam :: SwaggerPetstoreRequest req contentType res accept -> param -> SwaggerPetstoreRequest req contentType res accept applyOptionalParam = (-&-) {-# INLINE applyOptionalParam #-} -- | infix operator \/ alias for 'addOptionalParam' - (-&-) :: SwaggerPetstoreRequest req contentType res -> param -> SwaggerPetstoreRequest req contentType res + (-&-) :: SwaggerPetstoreRequest req contentType res accept -> param -> SwaggerPetstoreRequest req contentType res accept (-&-) = applyOptionalParam {-# INLINE (-&-) #-} @@ -223,18 +231,18 @@ data ParamBody _mkRequest :: NH.Method -- ^ Method -> [BCL.ByteString] -- ^ Endpoint - -> SwaggerPetstoreRequest req contentType res -- ^ req: Request Type, res: Response Type + -> SwaggerPetstoreRequest req contentType res accept -- ^ req: Request Type, res: Response Type _mkRequest m u = SwaggerPetstoreRequest m u _mkParams [] _mkParams :: Params _mkParams = Params [] [] ParamBodyNone -setHeader :: SwaggerPetstoreRequest req contentType res -> [NH.Header] -> SwaggerPetstoreRequest req contentType res +setHeader :: SwaggerPetstoreRequest req contentType res accept -> [NH.Header] -> SwaggerPetstoreRequest req contentType res accept setHeader req header = req `removeHeader` P.fmap P.fst header & L.over (rParamsL . paramsHeadersL) (header P.++) -removeHeader :: SwaggerPetstoreRequest req contentType res -> [NH.HeaderName] -> SwaggerPetstoreRequest req contentType res +removeHeader :: SwaggerPetstoreRequest req contentType res accept -> [NH.HeaderName] -> SwaggerPetstoreRequest req contentType res accept removeHeader req header = req & L.over @@ -244,19 +252,19 @@ removeHeader req header = cifst = CI.mk . P.fst -_setContentTypeHeader :: forall req contentType res. MimeType contentType => SwaggerPetstoreRequest req contentType res -> SwaggerPetstoreRequest req contentType res +_setContentTypeHeader :: forall req contentType res accept. MimeType contentType => SwaggerPetstoreRequest req contentType res accept -> SwaggerPetstoreRequest req contentType res accept _setContentTypeHeader req = case mimeType (P.Proxy :: P.Proxy contentType) of Just m -> req `setHeader` [("content-type", BC.pack $ P.show m)] Nothing -> req `removeHeader` ["content-type"] -_setAcceptHeader :: forall req contentType res accept. MimeType accept => SwaggerPetstoreRequest req contentType res -> accept -> SwaggerPetstoreRequest req contentType res -_setAcceptHeader req accept = - case mimeType' accept of +_setAcceptHeader :: forall req contentType res accept. MimeType accept => SwaggerPetstoreRequest req contentType res accept -> SwaggerPetstoreRequest req contentType res accept +_setAcceptHeader req = + case mimeType (P.Proxy :: P.Proxy accept) of Just m -> req `setHeader` [("accept", BC.pack $ P.show m)] Nothing -> req `removeHeader` ["accept"] -setQuery :: SwaggerPetstoreRequest req contentType res -> [NH.QueryItem] -> SwaggerPetstoreRequest req contentType res +setQuery :: SwaggerPetstoreRequest req contentType res accept -> [NH.QueryItem] -> SwaggerPetstoreRequest req contentType res accept setQuery req query = req & L.over @@ -265,29 +273,29 @@ setQuery req query = where cifst = CI.mk . P.fst -addForm :: SwaggerPetstoreRequest req contentType res -> WH.Form -> SwaggerPetstoreRequest req contentType res +addForm :: SwaggerPetstoreRequest req contentType res accept -> WH.Form -> SwaggerPetstoreRequest req contentType res accept addForm req newform = let form = case paramsBody (rParams req) of ParamBodyFormUrlEncoded _form -> _form _ -> mempty in req & L.set (rParamsL . paramsBodyL) (ParamBodyFormUrlEncoded (newform <> form)) -_addMultiFormPart :: SwaggerPetstoreRequest req contentType res -> NH.Part -> SwaggerPetstoreRequest req contentType res +_addMultiFormPart :: SwaggerPetstoreRequest req contentType res accept -> NH.Part -> SwaggerPetstoreRequest req contentType res accept _addMultiFormPart req newpart = let parts = case paramsBody (rParams req) of ParamBodyMultipartFormData _parts -> _parts _ -> [] in req & L.set (rParamsL . paramsBodyL) (ParamBodyMultipartFormData (newpart : parts)) -_setBodyBS :: SwaggerPetstoreRequest req contentType res -> B.ByteString -> SwaggerPetstoreRequest req contentType res +_setBodyBS :: SwaggerPetstoreRequest req contentType res accept -> B.ByteString -> SwaggerPetstoreRequest req contentType res accept _setBodyBS req body = req & L.set (rParamsL . paramsBodyL) (ParamBodyB body) -_setBodyLBS :: SwaggerPetstoreRequest req contentType res -> BL.ByteString -> SwaggerPetstoreRequest req contentType res +_setBodyLBS :: SwaggerPetstoreRequest req contentType res accept -> BL.ByteString -> SwaggerPetstoreRequest req contentType res accept _setBodyLBS req body = req & L.set (rParamsL . paramsBodyL) (ParamBodyBL body) -_hasAuthType :: AuthMethod authMethod => SwaggerPetstoreRequest req contentType res -> P.Proxy authMethod -> SwaggerPetstoreRequest req contentType res +_hasAuthType :: AuthMethod authMethod => SwaggerPetstoreRequest req contentType res accept -> P.Proxy authMethod -> SwaggerPetstoreRequest req contentType res accept _hasAuthType req proxy = req & L.over rAuthTypesL (P.typeRep proxy :) @@ -362,19 +370,24 @@ class P.Typeable a => applyAuthMethod :: SwaggerPetstoreConfig -> a - -> SwaggerPetstoreRequest req contentType res - -> IO (SwaggerPetstoreRequest req contentType res) + -> SwaggerPetstoreRequest req contentType res accept + -> IO (SwaggerPetstoreRequest req contentType res accept) -- | An existential wrapper for any AuthMethod data AnyAuthMethod = forall a. AuthMethod a => AnyAuthMethod a deriving (P.Typeable) instance AuthMethod AnyAuthMethod where applyAuthMethod config (AnyAuthMethod a) req = applyAuthMethod config a req +-- | indicates exceptions related to AuthMethods +data AuthMethodException = AuthMethodException String deriving (P.Show, P.Typeable) + +instance E.Exception AuthMethodException + -- | apply all matching AuthMethods in config to request _applyAuthMethods - :: SwaggerPetstoreRequest req contentType res + :: SwaggerPetstoreRequest req contentType res accept -> SwaggerPetstoreConfig - -> IO (SwaggerPetstoreRequest req contentType res) + -> IO (SwaggerPetstoreRequest req contentType res accept) _applyAuthMethods req config@(SwaggerPetstoreConfig {configAuthMethods = as}) = foldlM go req as where diff --git a/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/MimeTypes.hs b/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/MimeTypes.hs index 066fdd21244..31b402efad4 100644 --- a/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/MimeTypes.hs +++ b/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/MimeTypes.hs @@ -14,6 +14,7 @@ Module : SwaggerPetstore.MimeTypes -} {-# LANGUAGE ConstraintKinds #-} +{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} @@ -42,6 +43,13 @@ import qualified Web.HttpApiData as WH import Prelude (($), (.),(<$>),(<*>),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty) import qualified Prelude as P +-- * ContentType MimeType + +data ContentType a = MimeType a => ContentType { unContentType :: a } + +-- * Accept MimeType + +data Accept a = MimeType a => Accept { unAccept :: a } -- * Consumes Class @@ -191,4 +199,4 @@ instance MimeUnrender MimeOctetStream T.Text where mimeUnrender _ = P.left P.sho instance MimeUnrender MimeOctetStream String where mimeUnrender _ = P.Right . BCL.unpack -- | @P.Right . P.const NoContent@ -instance MimeUnrender MimeNoContent NoContent where mimeUnrender _ = P.Right . P.const NoContent \ No newline at end of file +instance MimeUnrender MimeNoContent NoContent where mimeUnrender _ = P.Right . P.const NoContent diff --git a/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/Model.hs b/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/Model.hs index 81208c6ce42..588f92a2390 100644 --- a/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/Model.hs +++ b/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/Model.hs @@ -18,6 +18,8 @@ Module : SwaggerPetstore.Model {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} @@ -28,9 +30,11 @@ Module : SwaggerPetstore.Model module SwaggerPetstore.Model where import SwaggerPetstore.Core +import SwaggerPetstore.MimeTypes import Data.Aeson ((.:),(.:!),(.:?),(.=)) +import qualified Control.Arrow as P (left) import qualified Data.Aeson as A import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL @@ -49,7 +53,7 @@ import qualified Web.HttpApiData as WH import Control.Applicative ((<|>)) import Control.Applicative (Alternative) import Data.Text (Text) -import Prelude (($), (.),(<$>),(<*>),(>>=),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty,maybe,pure,Monad,Applicative,Functor) +import Prelude (($), (.),(<$>),(<*>),(>>=),(=<<),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty,maybe,pure,Monad,Applicative,Functor) import qualified Prelude as P @@ -90,7 +94,6 @@ mkAdditionalPropertiesClass = , additionalPropertiesClassMapOfMapProperty = Nothing } - -- ** Animal -- | Animal data Animal = Animal @@ -124,7 +127,6 @@ mkAnimal animalClassName = , animalColor = Nothing } - -- ** AnimalFarm -- | AnimalFarm data AnimalFarm = AnimalFarm @@ -153,7 +155,6 @@ mkAnimalFarm = { } - -- ** ApiResponse -- | ApiResponse data ApiResponse = ApiResponse @@ -190,7 +191,6 @@ mkApiResponse = , apiResponseMessage = Nothing } - -- ** ArrayOfArrayOfNumberOnly -- | ArrayOfArrayOfNumberOnly data ArrayOfArrayOfNumberOnly = ArrayOfArrayOfNumberOnly @@ -219,7 +219,6 @@ mkArrayOfArrayOfNumberOnly = { arrayOfArrayOfNumberOnlyArrayArrayNumber = Nothing } - -- ** ArrayOfNumberOnly -- | ArrayOfNumberOnly data ArrayOfNumberOnly = ArrayOfNumberOnly @@ -248,7 +247,6 @@ mkArrayOfNumberOnly = { arrayOfNumberOnlyArrayNumber = Nothing } - -- ** ArrayTest -- | ArrayTest data ArrayTest = ArrayTest @@ -285,7 +283,6 @@ mkArrayTest = , arrayTestArrayArrayOfModel = Nothing } - -- ** Capitalization -- | Capitalization data Capitalization = Capitalization @@ -334,7 +331,6 @@ mkCapitalization = , capitalizationAttName = Nothing } - -- ** Category -- | Category data Category = Category @@ -367,7 +363,6 @@ mkCategory = , categoryName = Nothing } - -- ** ClassModel -- | ClassModel -- Model for testing model with \"_class\" property @@ -397,7 +392,6 @@ mkClassModel = { classModelClass = Nothing } - -- ** Client -- | Client data Client = Client @@ -426,12 +420,11 @@ mkClient = { clientClient = Nothing } - -- ** EnumArrays -- | EnumArrays data EnumArrays = EnumArrays - { enumArraysJustSymbol :: !(Maybe Text) -- ^ "just_symbol" - , enumArraysArrayEnum :: !(Maybe [Text]) -- ^ "array_enum" + { enumArraysJustSymbol :: !(Maybe E'JustSymbol) -- ^ "just_symbol" + , enumArraysArrayEnum :: !(Maybe [E'ArrayEnum]) -- ^ "array_enum" } deriving (P.Show, P.Eq, P.Typeable) -- | FromJSON EnumArrays @@ -459,42 +452,12 @@ mkEnumArrays = , enumArraysArrayEnum = Nothing } - --- ** EnumClass --- | EnumClass -data EnumClass = EnumClass - { - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON EnumClass -instance A.FromJSON EnumClass where - parseJSON = A.withObject "EnumClass" $ \o -> - pure EnumClass - - --- | ToJSON EnumClass -instance A.ToJSON EnumClass where - toJSON EnumClass = - _omitNulls - [ - ] - - --- | Construct a value of type 'EnumClass' (by applying it's required fields, if any) -mkEnumClass - :: EnumClass -mkEnumClass = - EnumClass - { - } - - -- ** EnumTest -- | EnumTest data EnumTest = EnumTest - { enumTestEnumString :: !(Maybe Text) -- ^ "enum_string" - , enumTestEnumInteger :: !(Maybe Int) -- ^ "enum_integer" - , enumTestEnumNumber :: !(Maybe Double) -- ^ "enum_number" + { enumTestEnumString :: !(Maybe E'EnumString) -- ^ "enum_string" + , enumTestEnumInteger :: !(Maybe E'EnumInteger) -- ^ "enum_integer" + , enumTestEnumNumber :: !(Maybe E'EnumNumber) -- ^ "enum_number" , enumTestOuterEnum :: !(Maybe OuterEnum) -- ^ "outerEnum" } deriving (P.Show, P.Eq, P.Typeable) @@ -529,7 +492,6 @@ mkEnumTest = , enumTestOuterEnum = Nothing } - -- ** FormatTest -- | FormatTest data FormatTest = FormatTest @@ -610,7 +572,6 @@ mkFormatTest formatTestNumber formatTestByte formatTestDate formatTestPassword = , formatTestPassword } - -- ** HasOnlyReadOnly -- | HasOnlyReadOnly data HasOnlyReadOnly = HasOnlyReadOnly @@ -643,12 +604,11 @@ mkHasOnlyReadOnly = , hasOnlyReadOnlyFoo = Nothing } - -- ** MapTest -- | MapTest data MapTest = MapTest { mapTestMapMapOfString :: !(Maybe (Map.Map String (Map.Map String Text))) -- ^ "map_map_of_string" - , mapTestMapOfEnumString :: !(Maybe (Map.Map String Text)) -- ^ "map_of_enum_string" + , mapTestMapOfEnumString :: !(Maybe (Map.Map String E'Inner)) -- ^ "map_of_enum_string" } deriving (P.Show, P.Eq, P.Typeable) -- | FromJSON MapTest @@ -676,7 +636,6 @@ mkMapTest = , mapTestMapOfEnumString = Nothing } - -- ** MixedPropertiesAndAdditionalPropertiesClass -- | MixedPropertiesAndAdditionalPropertiesClass data MixedPropertiesAndAdditionalPropertiesClass = MixedPropertiesAndAdditionalPropertiesClass @@ -713,7 +672,6 @@ mkMixedPropertiesAndAdditionalPropertiesClass = , mixedPropertiesAndAdditionalPropertiesClassMap = Nothing } - -- ** Model200Response -- | Model200Response -- Model for testing model name starting with number @@ -747,7 +705,6 @@ mkModel200Response = , model200ResponseClass = Nothing } - -- ** ModelList -- | ModelList data ModelList = ModelList @@ -776,7 +733,6 @@ mkModelList = { modelList123List = Nothing } - -- ** ModelReturn -- | ModelReturn -- Model for testing reserved words @@ -806,7 +762,6 @@ mkModelReturn = { modelReturnReturn = Nothing } - -- ** Name -- | Name -- Model for testing model name same as property name @@ -849,7 +804,6 @@ mkName nameName = , name123Number = Nothing } - -- ** NumberOnly -- | NumberOnly data NumberOnly = NumberOnly @@ -878,7 +832,6 @@ mkNumberOnly = { numberOnlyJustNumber = Nothing } - -- ** Order -- | Order data Order = Order @@ -886,7 +839,7 @@ data Order = Order , orderPetId :: !(Maybe Integer) -- ^ "petId" , orderQuantity :: !(Maybe Int) -- ^ "quantity" , orderShipDate :: !(Maybe DateTime) -- ^ "shipDate" - , orderStatus :: !(Maybe Text) -- ^ "status" - Order Status + , orderStatus :: !(Maybe E'Status) -- ^ "status" - Order Status , orderComplete :: !(Maybe Bool) -- ^ "complete" } deriving (P.Show, P.Eq, P.Typeable) @@ -927,7 +880,6 @@ mkOrder = , orderComplete = Nothing } - -- ** OuterBoolean -- | OuterBoolean newtype OuterBoolean = OuterBoolean @@ -935,7 +887,6 @@ newtype OuterBoolean = OuterBoolean } deriving (P.Eq, P.Show, P.Typeable, A.ToJSON, A.FromJSON, WH.ToHttpApiData, WH.FromHttpApiData) - -- ** OuterComposite -- | OuterComposite data OuterComposite = OuterComposite @@ -972,36 +923,6 @@ mkOuterComposite = , outerCompositeMyBoolean = Nothing } - --- ** OuterEnum --- | OuterEnum -data OuterEnum = OuterEnum - { - } deriving (P.Show, P.Eq, P.Typeable) - --- | FromJSON OuterEnum -instance A.FromJSON OuterEnum where - parseJSON = A.withObject "OuterEnum" $ \o -> - pure OuterEnum - - --- | ToJSON OuterEnum -instance A.ToJSON OuterEnum where - toJSON OuterEnum = - _omitNulls - [ - ] - - --- | Construct a value of type 'OuterEnum' (by applying it's required fields, if any) -mkOuterEnum - :: OuterEnum -mkOuterEnum = - OuterEnum - { - } - - -- ** OuterNumber -- | OuterNumber newtype OuterNumber = OuterNumber @@ -1009,7 +930,6 @@ newtype OuterNumber = OuterNumber } deriving (P.Eq, P.Show, P.Typeable, A.ToJSON, A.FromJSON, WH.ToHttpApiData, WH.FromHttpApiData) - -- ** OuterString -- | OuterString newtype OuterString = OuterString @@ -1017,7 +937,6 @@ newtype OuterString = OuterString } deriving (P.Eq, P.Show, P.Typeable, A.ToJSON, A.FromJSON, WH.ToHttpApiData, WH.FromHttpApiData) - -- ** Pet -- | Pet data Pet = Pet @@ -1026,7 +945,7 @@ data Pet = Pet , petName :: !(Text) -- ^ /Required/ "name" , petPhotoUrls :: !([Text]) -- ^ /Required/ "photoUrls" , petTags :: !(Maybe [Tag]) -- ^ "tags" - , petStatus :: !(Maybe Text) -- ^ "status" - pet status in the store + , petStatus :: !(Maybe E'Status2) -- ^ "status" - pet status in the store } deriving (P.Show, P.Eq, P.Typeable) -- | FromJSON Pet @@ -1068,7 +987,6 @@ mkPet petName petPhotoUrls = , petStatus = Nothing } - -- ** ReadOnlyFirst -- | ReadOnlyFirst data ReadOnlyFirst = ReadOnlyFirst @@ -1101,7 +1019,6 @@ mkReadOnlyFirst = , readOnlyFirstBaz = Nothing } - -- ** SpecialModelName -- | SpecialModelName data SpecialModelName = SpecialModelName @@ -1130,7 +1047,6 @@ mkSpecialModelName = { specialModelNameSpecialPropertyName = Nothing } - -- ** Tag -- | Tag data Tag = Tag @@ -1163,7 +1079,6 @@ mkTag = , tagName = Nothing } - -- ** User -- | User data User = User @@ -1220,7 +1135,6 @@ mkUser = , userUserStatus = Nothing } - -- ** Cat -- | Cat data Cat = Cat @@ -1258,7 +1172,6 @@ mkCat catClassName = , catDeclawed = Nothing } - -- ** Dog -- | Dog data Dog = Dog @@ -1297,4 +1210,388 @@ mkDog dogClassName = } +-- * Enums + +-- ** E'ArrayEnum + +-- | Enum of 'Text' +data E'ArrayEnum + = E'ArrayEnum'Fish -- ^ @"fish"@ + | E'ArrayEnum'Crab -- ^ @"crab"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'ArrayEnum where toJSON = A.toJSON . fromE'ArrayEnum +instance A.FromJSON E'ArrayEnum where parseJSON o = P.either P.fail (pure . P.id) . toE'ArrayEnum =<< A.parseJSON o +instance WH.ToHttpApiData E'ArrayEnum where toQueryParam = WH.toQueryParam . fromE'ArrayEnum +instance WH.FromHttpApiData E'ArrayEnum where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'ArrayEnum +instance MimeRender MimeMultipartFormData E'ArrayEnum where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'ArrayEnum' enum +fromE'ArrayEnum :: E'ArrayEnum -> Text +fromE'ArrayEnum = \case + E'ArrayEnum'Fish -> "fish" + E'ArrayEnum'Crab -> "crab" + +-- | parse 'E'ArrayEnum' enum +toE'ArrayEnum :: Text -> P.Either String E'ArrayEnum +toE'ArrayEnum = \case + "fish" -> P.Right E'ArrayEnum'Fish + "crab" -> P.Right E'ArrayEnum'Crab + s -> P.Left $ "toE'ArrayEnum: enum parse failure: " P.++ P.show s + + +-- ** E'EnumFormString + +-- | Enum of 'Text' +data E'EnumFormString + = E'EnumFormString'_abc -- ^ @"_abc"@ + | E'EnumFormString'_efg -- ^ @"-efg"@ + | E'EnumFormString'_xyz -- ^ @"(xyz)"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'EnumFormString where toJSON = A.toJSON . fromE'EnumFormString +instance A.FromJSON E'EnumFormString where parseJSON o = P.either P.fail (pure . P.id) . toE'EnumFormString =<< A.parseJSON o +instance WH.ToHttpApiData E'EnumFormString where toQueryParam = WH.toQueryParam . fromE'EnumFormString +instance WH.FromHttpApiData E'EnumFormString where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'EnumFormString +instance MimeRender MimeMultipartFormData E'EnumFormString where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'EnumFormString' enum +fromE'EnumFormString :: E'EnumFormString -> Text +fromE'EnumFormString = \case + E'EnumFormString'_abc -> "_abc" + E'EnumFormString'_efg -> "-efg" + E'EnumFormString'_xyz -> "(xyz)" + +-- | parse 'E'EnumFormString' enum +toE'EnumFormString :: Text -> P.Either String E'EnumFormString +toE'EnumFormString = \case + "_abc" -> P.Right E'EnumFormString'_abc + "-efg" -> P.Right E'EnumFormString'_efg + "(xyz)" -> P.Right E'EnumFormString'_xyz + s -> P.Left $ "toE'EnumFormString: enum parse failure: " P.++ P.show s + + +-- ** E'EnumInteger + +-- | Enum of 'Int' +data E'EnumInteger + = E'EnumInteger'Num1 -- ^ @1@ + | E'EnumInteger'NumMinus_1 -- ^ @-1@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'EnumInteger where toJSON = A.toJSON . fromE'EnumInteger +instance A.FromJSON E'EnumInteger where parseJSON o = P.either P.fail (pure . P.id) . toE'EnumInteger =<< A.parseJSON o +instance WH.ToHttpApiData E'EnumInteger where toQueryParam = WH.toQueryParam . fromE'EnumInteger +instance WH.FromHttpApiData E'EnumInteger where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'EnumInteger +instance MimeRender MimeMultipartFormData E'EnumInteger where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'EnumInteger' enum +fromE'EnumInteger :: E'EnumInteger -> Int +fromE'EnumInteger = \case + E'EnumInteger'Num1 -> 1 + E'EnumInteger'NumMinus_1 -> -1 + +-- | parse 'E'EnumInteger' enum +toE'EnumInteger :: Int -> P.Either String E'EnumInteger +toE'EnumInteger = \case + 1 -> P.Right E'EnumInteger'Num1 + -1 -> P.Right E'EnumInteger'NumMinus_1 + s -> P.Left $ "toE'EnumInteger: enum parse failure: " P.++ P.show s + + +-- ** E'EnumNumber + +-- | Enum of 'Double' +data E'EnumNumber + = E'EnumNumber'Num1_Dot_1 -- ^ @1.1@ + | E'EnumNumber'NumMinus_1_Dot_2 -- ^ @-1.2@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'EnumNumber where toJSON = A.toJSON . fromE'EnumNumber +instance A.FromJSON E'EnumNumber where parseJSON o = P.either P.fail (pure . P.id) . toE'EnumNumber =<< A.parseJSON o +instance WH.ToHttpApiData E'EnumNumber where toQueryParam = WH.toQueryParam . fromE'EnumNumber +instance WH.FromHttpApiData E'EnumNumber where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'EnumNumber +instance MimeRender MimeMultipartFormData E'EnumNumber where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'EnumNumber' enum +fromE'EnumNumber :: E'EnumNumber -> Double +fromE'EnumNumber = \case + E'EnumNumber'Num1_Dot_1 -> 1.1 + E'EnumNumber'NumMinus_1_Dot_2 -> -1.2 + +-- | parse 'E'EnumNumber' enum +toE'EnumNumber :: Double -> P.Either String E'EnumNumber +toE'EnumNumber = \case + 1.1 -> P.Right E'EnumNumber'Num1_Dot_1 + -1.2 -> P.Right E'EnumNumber'NumMinus_1_Dot_2 + s -> P.Left $ "toE'EnumNumber: enum parse failure: " P.++ P.show s + + +-- ** E'EnumQueryInteger + +-- | Enum of 'Int' +data E'EnumQueryInteger + = E'EnumQueryInteger'Num1 -- ^ @1@ + | E'EnumQueryInteger'NumMinus_2 -- ^ @-2@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'EnumQueryInteger where toJSON = A.toJSON . fromE'EnumQueryInteger +instance A.FromJSON E'EnumQueryInteger where parseJSON o = P.either P.fail (pure . P.id) . toE'EnumQueryInteger =<< A.parseJSON o +instance WH.ToHttpApiData E'EnumQueryInteger where toQueryParam = WH.toQueryParam . fromE'EnumQueryInteger +instance WH.FromHttpApiData E'EnumQueryInteger where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'EnumQueryInteger +instance MimeRender MimeMultipartFormData E'EnumQueryInteger where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'EnumQueryInteger' enum +fromE'EnumQueryInteger :: E'EnumQueryInteger -> Int +fromE'EnumQueryInteger = \case + E'EnumQueryInteger'Num1 -> 1 + E'EnumQueryInteger'NumMinus_2 -> -2 + +-- | parse 'E'EnumQueryInteger' enum +toE'EnumQueryInteger :: Int -> P.Either String E'EnumQueryInteger +toE'EnumQueryInteger = \case + 1 -> P.Right E'EnumQueryInteger'Num1 + -2 -> P.Right E'EnumQueryInteger'NumMinus_2 + s -> P.Left $ "toE'EnumQueryInteger: enum parse failure: " P.++ P.show s + + +-- ** E'EnumString + +-- | Enum of 'Text' +data E'EnumString + = E'EnumString'UPPER -- ^ @"UPPER"@ + | E'EnumString'Lower -- ^ @"lower"@ + | E'EnumString'Empty -- ^ @""@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'EnumString where toJSON = A.toJSON . fromE'EnumString +instance A.FromJSON E'EnumString where parseJSON o = P.either P.fail (pure . P.id) . toE'EnumString =<< A.parseJSON o +instance WH.ToHttpApiData E'EnumString where toQueryParam = WH.toQueryParam . fromE'EnumString +instance WH.FromHttpApiData E'EnumString where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'EnumString +instance MimeRender MimeMultipartFormData E'EnumString where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'EnumString' enum +fromE'EnumString :: E'EnumString -> Text +fromE'EnumString = \case + E'EnumString'UPPER -> "UPPER" + E'EnumString'Lower -> "lower" + E'EnumString'Empty -> "" + +-- | parse 'E'EnumString' enum +toE'EnumString :: Text -> P.Either String E'EnumString +toE'EnumString = \case + "UPPER" -> P.Right E'EnumString'UPPER + "lower" -> P.Right E'EnumString'Lower + "" -> P.Right E'EnumString'Empty + s -> P.Left $ "toE'EnumString: enum parse failure: " P.++ P.show s + + +-- ** E'Inner + +-- | Enum of 'Text' +data E'Inner + = E'Inner'UPPER -- ^ @"UPPER"@ + | E'Inner'Lower -- ^ @"lower"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'Inner where toJSON = A.toJSON . fromE'Inner +instance A.FromJSON E'Inner where parseJSON o = P.either P.fail (pure . P.id) . toE'Inner =<< A.parseJSON o +instance WH.ToHttpApiData E'Inner where toQueryParam = WH.toQueryParam . fromE'Inner +instance WH.FromHttpApiData E'Inner where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'Inner +instance MimeRender MimeMultipartFormData E'Inner where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'Inner' enum +fromE'Inner :: E'Inner -> Text +fromE'Inner = \case + E'Inner'UPPER -> "UPPER" + E'Inner'Lower -> "lower" + +-- | parse 'E'Inner' enum +toE'Inner :: Text -> P.Either String E'Inner +toE'Inner = \case + "UPPER" -> P.Right E'Inner'UPPER + "lower" -> P.Right E'Inner'Lower + s -> P.Left $ "toE'Inner: enum parse failure: " P.++ P.show s + + +-- ** E'Inner2 + +-- | Enum of 'Text' +data E'Inner2 + = E'Inner2'GreaterThan -- ^ @">"@ + | E'Inner2'Dollar -- ^ @"$"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'Inner2 where toJSON = A.toJSON . fromE'Inner2 +instance A.FromJSON E'Inner2 where parseJSON o = P.either P.fail (pure . P.id) . toE'Inner2 =<< A.parseJSON o +instance WH.ToHttpApiData E'Inner2 where toQueryParam = WH.toQueryParam . fromE'Inner2 +instance WH.FromHttpApiData E'Inner2 where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'Inner2 +instance MimeRender MimeMultipartFormData E'Inner2 where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'Inner2' enum +fromE'Inner2 :: E'Inner2 -> Text +fromE'Inner2 = \case + E'Inner2'GreaterThan -> ">" + E'Inner2'Dollar -> "$" + +-- | parse 'E'Inner2' enum +toE'Inner2 :: Text -> P.Either String E'Inner2 +toE'Inner2 = \case + ">" -> P.Right E'Inner2'GreaterThan + "$" -> P.Right E'Inner2'Dollar + s -> P.Left $ "toE'Inner2: enum parse failure: " P.++ P.show s + + +-- ** E'JustSymbol + +-- | Enum of 'Text' +data E'JustSymbol + = E'JustSymbol'Greater_Than_Or_Equal_To -- ^ @">="@ + | E'JustSymbol'Dollar -- ^ @"$"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'JustSymbol where toJSON = A.toJSON . fromE'JustSymbol +instance A.FromJSON E'JustSymbol where parseJSON o = P.either P.fail (pure . P.id) . toE'JustSymbol =<< A.parseJSON o +instance WH.ToHttpApiData E'JustSymbol where toQueryParam = WH.toQueryParam . fromE'JustSymbol +instance WH.FromHttpApiData E'JustSymbol where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'JustSymbol +instance MimeRender MimeMultipartFormData E'JustSymbol where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'JustSymbol' enum +fromE'JustSymbol :: E'JustSymbol -> Text +fromE'JustSymbol = \case + E'JustSymbol'Greater_Than_Or_Equal_To -> ">=" + E'JustSymbol'Dollar -> "$" + +-- | parse 'E'JustSymbol' enum +toE'JustSymbol :: Text -> P.Either String E'JustSymbol +toE'JustSymbol = \case + ">=" -> P.Right E'JustSymbol'Greater_Than_Or_Equal_To + "$" -> P.Right E'JustSymbol'Dollar + s -> P.Left $ "toE'JustSymbol: enum parse failure: " P.++ P.show s + + +-- ** E'Status + +-- | Enum of 'Text' . +-- Order Status +data E'Status + = E'Status'Placed -- ^ @"placed"@ + | E'Status'Approved -- ^ @"approved"@ + | E'Status'Delivered -- ^ @"delivered"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'Status where toJSON = A.toJSON . fromE'Status +instance A.FromJSON E'Status where parseJSON o = P.either P.fail (pure . P.id) . toE'Status =<< A.parseJSON o +instance WH.ToHttpApiData E'Status where toQueryParam = WH.toQueryParam . fromE'Status +instance WH.FromHttpApiData E'Status where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'Status +instance MimeRender MimeMultipartFormData E'Status where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'Status' enum +fromE'Status :: E'Status -> Text +fromE'Status = \case + E'Status'Placed -> "placed" + E'Status'Approved -> "approved" + E'Status'Delivered -> "delivered" + +-- | parse 'E'Status' enum +toE'Status :: Text -> P.Either String E'Status +toE'Status = \case + "placed" -> P.Right E'Status'Placed + "approved" -> P.Right E'Status'Approved + "delivered" -> P.Right E'Status'Delivered + s -> P.Left $ "toE'Status: enum parse failure: " P.++ P.show s + + +-- ** E'Status2 + +-- | Enum of 'Text' . +-- pet status in the store +data E'Status2 + = E'Status2'Available -- ^ @"available"@ + | E'Status2'Pending -- ^ @"pending"@ + | E'Status2'Sold -- ^ @"sold"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON E'Status2 where toJSON = A.toJSON . fromE'Status2 +instance A.FromJSON E'Status2 where parseJSON o = P.either P.fail (pure . P.id) . toE'Status2 =<< A.parseJSON o +instance WH.ToHttpApiData E'Status2 where toQueryParam = WH.toQueryParam . fromE'Status2 +instance WH.FromHttpApiData E'Status2 where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toE'Status2 +instance MimeRender MimeMultipartFormData E'Status2 where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'E'Status2' enum +fromE'Status2 :: E'Status2 -> Text +fromE'Status2 = \case + E'Status2'Available -> "available" + E'Status2'Pending -> "pending" + E'Status2'Sold -> "sold" + +-- | parse 'E'Status2' enum +toE'Status2 :: Text -> P.Either String E'Status2 +toE'Status2 = \case + "available" -> P.Right E'Status2'Available + "pending" -> P.Right E'Status2'Pending + "sold" -> P.Right E'Status2'Sold + s -> P.Left $ "toE'Status2: enum parse failure: " P.++ P.show s + + +-- ** EnumClass + +-- | Enum of 'Text' +data EnumClass + = EnumClass'_abc -- ^ @"_abc"@ + | EnumClass'_efg -- ^ @"-efg"@ + | EnumClass'_xyz -- ^ @"(xyz)"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON EnumClass where toJSON = A.toJSON . fromEnumClass +instance A.FromJSON EnumClass where parseJSON o = P.either P.fail (pure . P.id) . toEnumClass =<< A.parseJSON o +instance WH.ToHttpApiData EnumClass where toQueryParam = WH.toQueryParam . fromEnumClass +instance WH.FromHttpApiData EnumClass where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toEnumClass +instance MimeRender MimeMultipartFormData EnumClass where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'EnumClass' enum +fromEnumClass :: EnumClass -> Text +fromEnumClass = \case + EnumClass'_abc -> "_abc" + EnumClass'_efg -> "-efg" + EnumClass'_xyz -> "(xyz)" + +-- | parse 'EnumClass' enum +toEnumClass :: Text -> P.Either String EnumClass +toEnumClass = \case + "_abc" -> P.Right EnumClass'_abc + "-efg" -> P.Right EnumClass'_efg + "(xyz)" -> P.Right EnumClass'_xyz + s -> P.Left $ "toEnumClass: enum parse failure: " P.++ P.show s + + +-- ** OuterEnum + +-- | Enum of 'Text' +data OuterEnum + = OuterEnum'Placed -- ^ @"placed"@ + | OuterEnum'Approved -- ^ @"approved"@ + | OuterEnum'Delivered -- ^ @"delivered"@ + deriving (P.Show, P.Eq, P.Typeable, P.Ord, P.Bounded, P.Enum) + +instance A.ToJSON OuterEnum where toJSON = A.toJSON . fromOuterEnum +instance A.FromJSON OuterEnum where parseJSON o = P.either P.fail (pure . P.id) . toOuterEnum =<< A.parseJSON o +instance WH.ToHttpApiData OuterEnum where toQueryParam = WH.toQueryParam . fromOuterEnum +instance WH.FromHttpApiData OuterEnum where parseQueryParam o = WH.parseQueryParam o >>= P.left T.pack . toOuterEnum +instance MimeRender MimeMultipartFormData OuterEnum where mimeRender _ = mimeRenderDefaultMultipartFormData + +-- | unwrap 'OuterEnum' enum +fromOuterEnum :: OuterEnum -> Text +fromOuterEnum = \case + OuterEnum'Placed -> "placed" + OuterEnum'Approved -> "approved" + OuterEnum'Delivered -> "delivered" + +-- | parse 'OuterEnum' enum +toOuterEnum :: Text -> P.Either String OuterEnum +toOuterEnum = \case + "placed" -> P.Right OuterEnum'Placed + "approved" -> P.Right OuterEnum'Approved + "delivered" -> P.Right OuterEnum'Delivered + s -> P.Left $ "toOuterEnum: enum parse failure: " P.++ P.show s diff --git a/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/ModelLens.hs b/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/ModelLens.hs index d9573a4c2c0..3193d0ac69c 100644 --- a/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/ModelLens.hs +++ b/samples/client/petstore/haskell-http-client/lib/SwaggerPetstore/ModelLens.hs @@ -194,12 +194,12 @@ clientClientL f Client{..} = (\clientClient -> Client { clientClient, ..} ) <$> -- * EnumArrays -- | 'enumArraysJustSymbol' Lens -enumArraysJustSymbolL :: Lens_' EnumArrays (Maybe Text) +enumArraysJustSymbolL :: Lens_' EnumArrays (Maybe E'JustSymbol) enumArraysJustSymbolL f EnumArrays{..} = (\enumArraysJustSymbol -> EnumArrays { enumArraysJustSymbol, ..} ) <$> f enumArraysJustSymbol {-# INLINE enumArraysJustSymbolL #-} -- | 'enumArraysArrayEnum' Lens -enumArraysArrayEnumL :: Lens_' EnumArrays (Maybe [Text]) +enumArraysArrayEnumL :: Lens_' EnumArrays (Maybe [E'ArrayEnum]) enumArraysArrayEnumL f EnumArrays{..} = (\enumArraysArrayEnum -> EnumArrays { enumArraysArrayEnum, ..} ) <$> f enumArraysArrayEnum {-# INLINE enumArraysArrayEnumL #-} @@ -212,17 +212,17 @@ enumArraysArrayEnumL f EnumArrays{..} = (\enumArraysArrayEnum -> EnumArrays { en -- * EnumTest -- | 'enumTestEnumString' Lens -enumTestEnumStringL :: Lens_' EnumTest (Maybe Text) +enumTestEnumStringL :: Lens_' EnumTest (Maybe E'EnumString) enumTestEnumStringL f EnumTest{..} = (\enumTestEnumString -> EnumTest { enumTestEnumString, ..} ) <$> f enumTestEnumString {-# INLINE enumTestEnumStringL #-} -- | 'enumTestEnumInteger' Lens -enumTestEnumIntegerL :: Lens_' EnumTest (Maybe Int) +enumTestEnumIntegerL :: Lens_' EnumTest (Maybe E'EnumInteger) enumTestEnumIntegerL f EnumTest{..} = (\enumTestEnumInteger -> EnumTest { enumTestEnumInteger, ..} ) <$> f enumTestEnumInteger {-# INLINE enumTestEnumIntegerL #-} -- | 'enumTestEnumNumber' Lens -enumTestEnumNumberL :: Lens_' EnumTest (Maybe Double) +enumTestEnumNumberL :: Lens_' EnumTest (Maybe E'EnumNumber) enumTestEnumNumberL f EnumTest{..} = (\enumTestEnumNumber -> EnumTest { enumTestEnumNumber, ..} ) <$> f enumTestEnumNumber {-# INLINE enumTestEnumNumberL #-} @@ -324,7 +324,7 @@ mapTestMapMapOfStringL f MapTest{..} = (\mapTestMapMapOfString -> MapTest { mapT {-# INLINE mapTestMapMapOfStringL #-} -- | 'mapTestMapOfEnumString' Lens -mapTestMapOfEnumStringL :: Lens_' MapTest (Maybe (Map.Map String Text)) +mapTestMapOfEnumStringL :: Lens_' MapTest (Maybe (Map.Map String E'Inner)) mapTestMapOfEnumStringL f MapTest{..} = (\mapTestMapOfEnumString -> MapTest { mapTestMapOfEnumString, ..} ) <$> f mapTestMapOfEnumString {-# INLINE mapTestMapOfEnumStringL #-} @@ -437,7 +437,7 @@ orderShipDateL f Order{..} = (\orderShipDate -> Order { orderShipDate, ..} ) <$> {-# INLINE orderShipDateL #-} -- | 'orderStatus' Lens -orderStatusL :: Lens_' Order (Maybe Text) +orderStatusL :: Lens_' Order (Maybe E'Status) orderStatusL f Order{..} = (\orderStatus -> Order { orderStatus, ..} ) <$> f orderStatus {-# INLINE orderStatusL #-} @@ -511,7 +511,7 @@ petTagsL f Pet{..} = (\petTags -> Pet { petTags, ..} ) <$> f petTags {-# INLINE petTagsL #-} -- | 'petStatus' Lens -petStatusL :: Lens_' Pet (Maybe Text) +petStatusL :: Lens_' Pet (Maybe E'Status2) petStatusL f Pet{..} = (\petStatus -> Pet { petStatus, ..} ) <$> f petStatus {-# INLINE petStatusL #-} diff --git a/samples/client/petstore/haskell-http-client/stack.yaml b/samples/client/petstore/haskell-http-client/stack.yaml index 174a76815bc..aa4a059faa5 100644 --- a/samples/client/petstore/haskell-http-client/stack.yaml +++ b/samples/client/petstore/haskell-http-client/stack.yaml @@ -1,4 +1,4 @@ -resolver: lts-9.0 +resolver: lts-9.10 build: haddock-arguments: haddock-args: diff --git a/samples/client/petstore/haskell-http-client/swagger-petstore.cabal b/samples/client/petstore/haskell-http-client/swagger-petstore.cabal index 36a8e7212c1..e5a712598f8 100644 --- a/samples/client/petstore/haskell-http-client/swagger-petstore.cabal +++ b/samples/client/petstore/haskell-http-client/swagger-petstore.cabal @@ -40,7 +40,7 @@ library , bytestring >=0.10.0 && <0.11 , base64-bytestring >1.0 && <2.0 , containers >=0.5.0.0 && <0.6 - , http-types >=0.8 && <0.10 + , http-types >=0.8 && <0.11 , http-client >=0.5 && <0.6 , http-client-tls , http-api-data >= 0.3.4 && <0.4 diff --git a/samples/client/petstore/haskell-http-client/swagger.yaml b/samples/client/petstore/haskell-http-client/swagger.yaml index 9a4097a9292..2721bfb19c9 100644 --- a/samples/client/petstore/haskell-http-client/swagger.yaml +++ b/samples/client/petstore/haskell-http-client/swagger.yaml @@ -918,6 +918,27 @@ paths: responses: 200: description: "successful operation" + /fake/inline-additionalProperties: + post: + tags: + - "fake" + summary: "test inline additionalProperties" + description: "" + operationId: "testInlineAdditionalProperties" + consumes: + - "application/json" + parameters: + - in: "body" + name: "param" + description: "request body" + required: true + schema: + type: "object" + additionalProperties: + type: "string" + responses: + 200: + description: "successful operation" /another-fake/dummy: patch: tags: @@ -966,15 +987,19 @@ definitions: id: type: "integer" format: "int64" + x-dataType: "Integer" petId: type: "integer" format: "int64" + x-dataType: "Integer" quantity: type: "integer" format: "int32" + x-dataType: "Int" shipDate: type: "string" format: "date-time" + x-dataType: "DateTime" status: type: "string" description: "Order Status" @@ -982,9 +1007,11 @@ definitions: - "placed" - "approved" - "delivered" + x-dataType: "E'Status" complete: type: "boolean" default: false + x-dataType: "Bool" example: petId: 6 quantity: 1 @@ -1003,8 +1030,10 @@ definitions: id: type: "integer" format: "int64" + x-dataType: "Integer" name: type: "string" + x-dataType: "Text" example: name: "name" id: 6 @@ -1017,22 +1046,30 @@ definitions: type: "integer" format: "int64" x-is-unique: true + x-dataType: "Integer" username: type: "string" + x-dataType: "Text" firstName: type: "string" + x-dataType: "Text" lastName: type: "string" + x-dataType: "Text" email: type: "string" + x-dataType: "Text" password: type: "string" + x-dataType: "Text" phone: type: "string" + x-dataType: "Text" userStatus: type: "integer" format: "int32" description: "User Status" + x-dataType: "Int" example: firstName: "firstName" lastName: "lastName" @@ -1053,8 +1090,10 @@ definitions: id: type: "integer" format: "int64" + x-dataType: "Integer" name: type: "string" + x-dataType: "Text" example: name: "name" id: 1 @@ -1070,11 +1109,14 @@ definitions: type: "integer" format: "int64" x-is-unique: true + x-dataType: "Integer" category: $ref: "#/definitions/Category" + x-dataType: "Category" name: type: "string" example: "doggie" + x-dataType: "Text" photoUrls: type: "array" xml: @@ -1082,6 +1124,7 @@ definitions: wrapped: true items: type: "string" + x-dataType: "[Text]" tags: type: "array" xml: @@ -1089,6 +1132,7 @@ definitions: wrapped: true items: $ref: "#/definitions/Tag" + x-dataType: "[Tag]" status: type: "string" description: "pet status in the store" @@ -1096,6 +1140,7 @@ definitions: - "available" - "pending" - "sold" + x-dataType: "E'Status2" example: photoUrls: - "photoUrls" @@ -1122,10 +1167,13 @@ definitions: code: type: "integer" format: "int32" + x-dataType: "Int" type: type: "string" + x-dataType: "Text" message: type: "string" + x-dataType: "Text" example: code: 0 type: "type" @@ -1135,6 +1183,7 @@ definitions: $special[property.name]: type: "integer" format: "int64" + x-dataType: "Integer" xml: name: "$special[model.name]" Return: @@ -1142,6 +1191,7 @@ definitions: return: type: "integer" format: "int32" + x-dataType: "Int" description: "Model for testing reserved words" xml: name: "Return" @@ -1152,15 +1202,19 @@ definitions: name: type: "integer" format: "int32" + x-dataType: "Int" snake_case: type: "integer" format: "int32" readOnly: true + x-dataType: "Int" property: type: "string" + x-dataType: "Text" 123Number: type: "integer" readOnly: true + x-dataType: "Int" description: "Model for testing model name same as property name" xml: name: "Name" @@ -1169,8 +1223,10 @@ definitions: name: type: "integer" format: "int32" + x-dataType: "Int" class: type: "string" + x-dataType: "Text" description: "Model for testing model name starting with number" xml: name: "Name" @@ -1178,6 +1234,7 @@ definitions: properties: _class: type: "string" + x-dataType: "Text" description: "Model for testing model with \"_class\" property" Dog: allOf: @@ -1186,6 +1243,7 @@ definitions: properties: breed: type: "string" + x-dataType: "Text" Cat: allOf: - $ref: "#/definitions/Animal" @@ -1193,6 +1251,7 @@ definitions: properties: declawed: type: "boolean" + x-dataType: "Bool" Animal: type: "object" required: @@ -1201,9 +1260,11 @@ definitions: properties: className: type: "string" + x-dataType: "Text" color: type: "string" default: "red" + x-dataType: "Text" AnimalFarm: type: "array" items: @@ -1220,52 +1281,65 @@ definitions: type: "integer" minimum: 10 maximum: 100 + x-dataType: "Int" int32: type: "integer" format: "int32" minimum: 20 maximum: 200 + x-dataType: "Int" int64: type: "integer" format: "int64" + x-dataType: "Integer" number: type: "number" minimum: 32.1 maximum: 543.2 + x-dataType: "Double" float: type: "number" format: "float" minimum: 54.3 maximum: 987.6 + x-dataType: "Float" double: type: "number" format: "double" minimum: 67.8 maximum: 123.4 + x-dataType: "Double" string: type: "string" pattern: "/[a-z]/i" + x-dataType: "Text" byte: type: "string" format: "byte" pattern: "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$" + x-dataType: "ByteArray" binary: type: "string" format: "binary" + x-dataType: "Binary" date: type: "string" format: "date" + x-dataType: "Date" dateTime: type: "string" format: "date-time" + x-dataType: "DateTime" uuid: type: "string" format: "uuid" + x-dataType: "Text" password: type: "string" format: "password" minLength: 10 maxLength: 64 + x-dataType: "Text" EnumClass: type: "string" enum: @@ -1282,20 +1356,24 @@ definitions: - "UPPER" - "lower" - "" + x-dataType: "E'EnumString" enum_integer: type: "integer" format: "int32" enum: - 1 - -1 + x-dataType: "E'EnumInteger" enum_number: type: "number" format: "double" enum: - 1.1 - -1.2 + x-dataType: "E'EnumNumber" outerEnum: $ref: "#/definitions/OuterEnum" + x-dataType: "OuterEnum" AdditionalPropertiesClass: type: "object" properties: @@ -1303,35 +1381,42 @@ definitions: type: "object" additionalProperties: type: "string" + x-dataType: "(Map.Map String Text)" map_of_map_property: type: "object" additionalProperties: type: "object" additionalProperties: type: "string" + x-dataType: "(Map.Map String (Map.Map String Text))" MixedPropertiesAndAdditionalPropertiesClass: type: "object" properties: uuid: type: "string" format: "uuid" + x-dataType: "Text" dateTime: type: "string" format: "date-time" + x-dataType: "DateTime" map: type: "object" additionalProperties: $ref: "#/definitions/Animal" + x-dataType: "(Map.Map String Animal)" List: type: "object" properties: 123-list: type: "string" + x-dataType: "Text" Client: type: "object" properties: client: type: "string" + x-dataType: "Text" example: client: "client" x-mimeTypes: @@ -1342,33 +1427,43 @@ definitions: bar: type: "string" readOnly: true + x-dataType: "Text" baz: type: "string" + x-dataType: "Text" hasOnlyReadOnly: type: "object" properties: bar: type: "string" readOnly: true + x-dataType: "Text" foo: type: "string" readOnly: true + x-dataType: "Text" Capitalization: type: "object" properties: smallCamel: type: "string" + x-dataType: "Text" CapitalCamel: type: "string" + x-dataType: "Text" small_Snake: type: "string" + x-dataType: "Text" Capital_Snake: type: "string" + x-dataType: "Text" SCA_ETH_Flow_Points: type: "string" + x-dataType: "Text" ATT_NAME: type: "string" description: "Name of the pet\n" + x-dataType: "Text" MapTest: type: "object" properties: @@ -1378,6 +1473,7 @@ definitions: type: "object" additionalProperties: type: "string" + x-dataType: "(Map.Map String (Map.Map String Text))" map_of_enum_string: type: "object" additionalProperties: @@ -1385,6 +1481,7 @@ definitions: enum: - "UPPER" - "lower" + x-dataType: "(Map.Map String E'Inner)" ArrayTest: type: "object" properties: @@ -1392,6 +1489,7 @@ definitions: type: "array" items: type: "string" + x-dataType: "[Text]" array_array_of_integer: type: "array" items: @@ -1399,17 +1497,20 @@ definitions: items: type: "integer" format: "int64" + x-dataType: "[[Integer]]" array_array_of_model: type: "array" items: type: "array" items: $ref: "#/definitions/ReadOnlyFirst" + x-dataType: "[[ReadOnlyFirst]]" NumberOnly: type: "object" properties: JustNumber: type: "number" + x-dataType: "Double" ArrayOfNumberOnly: type: "object" properties: @@ -1417,6 +1518,7 @@ definitions: type: "array" items: type: "number" + x-dataType: "[Double]" ArrayOfArrayOfNumberOnly: type: "object" properties: @@ -1426,6 +1528,7 @@ definitions: type: "array" items: type: "number" + x-dataType: "[[Double]]" EnumArrays: type: "object" properties: @@ -1434,6 +1537,7 @@ definitions: enum: - ">=" - "$" + x-dataType: "E'JustSymbol" array_enum: type: "array" items: @@ -1441,6 +1545,7 @@ definitions: enum: - "fish" - "crab" + x-dataType: "[E'ArrayEnum]" OuterEnum: type: "string" enum: @@ -1452,20 +1557,26 @@ definitions: properties: my_number: $ref: "#/definitions/OuterNumber" + x-dataType: "OuterNumber" my_string: $ref: "#/definitions/OuterString" + x-dataType: "OuterString" my_boolean: $ref: "#/definitions/OuterBoolean" + x-dataType: "OuterBoolean" example: my_string: {} my_number: {} my_boolean: {} OuterNumber: type: "number" + x-dataType: "Double" OuterString: type: "string" + x-dataType: "Text" OuterBoolean: type: "boolean" + x-dataType: "Bool" externalDocs: description: "Find out more about Swagger" url: "http://swagger.io" diff --git a/samples/client/petstore/haskell-http-client/tests-integration/tests/Test.hs b/samples/client/petstore/haskell-http-client/tests-integration/tests/Test.hs index a6563639f82..ed8da0fb728 100644 --- a/samples/client/petstore/haskell-http-client/tests-integration/tests/Test.hs +++ b/samples/client/petstore/haskell-http-client/tests-integration/tests/Test.hs @@ -84,8 +84,8 @@ testPetOps mgr config = it "addPet" $ do let addPetRequest = - S.addPet S.MimeJSON (S.mkPet "name" ["url1", "url2"]) - addPetResponse <- S.dispatchLbs mgr config addPetRequest S.MimeJSON + S.addPet (S.ContentType S.MimeJSON) (S.Accept S.MimeJSON) (S.mkPet "name" ["url1", "url2"]) + addPetResponse <- S.dispatchLbs mgr config addPetRequest NH.responseStatus addPetResponse `shouldBe` NH.status200 case A.eitherDecode (NH.responseBody addPetResponse) of Right pet -> do @@ -98,24 +98,27 @@ testPetOps mgr config = Just pet@S.Pet {S.petId = Just petId} -> go (petId, pet) _ -> pendingWith "no petId") $ it "getPetById" $ \(petId, pet) -> do - let getPetByIdRequest = S.getPetById (S.PetId petId) - getPetByIdRequestResult <- S.dispatchMime mgr config getPetByIdRequest S.MimeJSON + let getPetByIdRequest = S.getPetById (S.Accept S.MimeJSON) (S.PetId petId) + getPetByIdRequestResult <- S.dispatchMime mgr config getPetByIdRequest NH.responseStatus (S.mimeResultResponse getPetByIdRequestResult) `shouldBe` NH.status200 case S.mimeResult getPetByIdRequestResult of Right p -> p `shouldBe` pet Left (S.MimeError e _) -> assertFailure e it "findPetsByStatus" $ do - let findPetsByStatusRequest = S.findPetsByStatus (S.Status ["available","pending","sold"]) - findPetsByStatusResult <- S.dispatchMime mgr config findPetsByStatusRequest S.MimeJSON + let findPetsByStatusRequest = S.findPetsByStatus (S.Accept S.MimeJSON) + (S.Status [ S.E'Status2'Available + , S.E'Status2'Pending + , S.E'Status2'Sold]) + findPetsByStatusResult <- S.dispatchMime mgr config findPetsByStatusRequest NH.responseStatus (S.mimeResultResponse findPetsByStatusResult) `shouldBe` NH.status200 case S.mimeResult findPetsByStatusResult of Right r -> length r `shouldSatisfy` (> 0) Left (S.MimeError e _) -> assertFailure e it "findPetsByTags" $ do - let findPetsByTagsRequest = S.findPetsByTags (S.Tags ["name","tag1"]) - findPetsByTagsResult <- S.dispatchMime mgr config findPetsByTagsRequest S.MimeJSON + let findPetsByTagsRequest = S.findPetsByTags (S.Accept S.MimeJSON) (S.Tags ["name","tag1"]) + findPetsByTagsResult <- S.dispatchMime mgr config findPetsByTagsRequest NH.responseStatus (S.mimeResultResponse findPetsByTagsResult) `shouldBe` NH.status200 case S.mimeResult findPetsByTagsResult of Right r -> length r `shouldSatisfy` (> 0) @@ -126,20 +129,22 @@ testPetOps mgr config = Just pet -> go pet _ -> pendingWith "no pet") $ it "updatePet" $ \pet -> do - let updatePetRequest = S.updatePet S.MimeJSON $ pet - { S.petStatus = Just "available" - , S.petCategory = Just (S.Category (Just 3) (Just "catname")) - } - updatePetResponse <- S.dispatchLbs mgr config updatePetRequest S.MimeXML + let updatePetRequest = S.updatePet (S.ContentType S.MimeJSON) (S.Accept S.MimeXML) + (pet + { S.petStatus = Just S.E'Status2'Available + , S.petCategory = Just (S.Category (Just 3) (Just "catname")) + }) + updatePetResponse <- S.dispatchLbs mgr config updatePetRequest NH.responseStatus updatePetResponse `shouldBe` NH.status200 it "updatePetWithFormRequest" $ do readIORef _pet >>= \case Just S.Pet {S.petId = Just petId} -> do - let updatePetWithFormRequest = S.updatePetWithForm S.MimeFormUrlEncoded (S.PetId petId) - `S.applyOptionalParam` S.Name2 "petName" - `S.applyOptionalParam` S.StatusText "pending" - updatePetWithFormResponse <- S.dispatchLbs mgr config updatePetWithFormRequest S.MimeJSON + let updatePetWithFormRequest = S.updatePetWithForm (S.ContentType S.MimeFormUrlEncoded) (S.Accept S.MimeJSON) + (S.PetId petId) + `S.applyOptionalParam` S.Name2 "petName" + `S.applyOptionalParam` S.StatusText "pending" + updatePetWithFormResponse <- S.dispatchLbs mgr config updatePetWithFormRequest NH.responseStatus updatePetWithFormResponse `shouldBe` NH.status200 _ -> pendingWith "no pet" @@ -148,10 +153,11 @@ testPetOps mgr config = Just pet@S.Pet {S.petId = Just petId} -> go petId _ -> pendingWith "no petId") $ it "uploadFile" $ \petId -> do - let uploadFileRequest = S.uploadFile S.MimeMultipartFormData (S.PetId petId) + let uploadFileRequest = S.uploadFile (S.ContentType S.MimeMultipartFormData) (S.Accept S.MimeJSON) + (S.PetId petId) `S.applyOptionalParam` S.File "package.yaml" `S.applyOptionalParam` S.AdditionalMetadata "a package.yaml file" - uploadFileRequestResult <- S.dispatchMime mgr config uploadFileRequest S.MimeJSON + uploadFileRequestResult <- S.dispatchMime mgr config uploadFileRequest NH.responseStatus (S.mimeResultResponse uploadFileRequestResult) `shouldBe` NH.status200 case S.mimeResult uploadFileRequestResult of Right _ -> assertSuccess @@ -162,9 +168,9 @@ testPetOps mgr config = Just pet@S.Pet {S.petId = Just petId} -> go petId _ -> pendingWith "no petId") $ it "deletePet" $ \petId -> do - let deletePetRequest = S.deletePet (S.PetId petId) + let deletePetRequest = S.deletePet (S.Accept S.MimeJSON) (S.PetId petId) `S.applyOptionalParam` S.ApiKey "api key" - deletePetResponse <- S.dispatchLbs mgr config deletePetRequest S.MimeJSON + deletePetResponse <- S.dispatchLbs mgr config deletePetRequest NH.responseStatus deletePetResponse `shouldBe` NH.status200 -- * STORE TESTS @@ -178,9 +184,9 @@ testStoreOps mgr config = do _order <- runIO $ newIORef (Nothing :: Maybe S.Order) it "getInventory" $ do - let getInventoryRequest = S.getInventory + let getInventoryRequest = S.getInventory (S.Accept S.MimeJSON) `S.setHeader` [("api_key","special-key")] - getInventoryRequestRequestResult <- S.dispatchMime mgr config getInventoryRequest S.MimeJSON + getInventoryRequestRequestResult <- S.dispatchMime mgr config getInventoryRequest NH.responseStatus (S.mimeResultResponse getInventoryRequestRequestResult) `shouldBe` NH.status200 case S.mimeResult getInventoryRequestRequestResult of Right r -> length r `shouldSatisfy` (> 0) @@ -188,13 +194,13 @@ testStoreOps mgr config = do it "placeOrder" $ do now <- TI.getCurrentTime - let placeOrderRequest = S.placeOrder S.MimeJSON + let placeOrderRequest = S.placeOrder (S.ContentType S.MimeJSON) (S.Accept S.MimeJSON) (S.mkOrder { S.orderId = Just 21 , S.orderQuantity = Just 210 , S.orderShipDate = Just (S.DateTime now) }) - placeOrderResult <- S.dispatchMime mgr config placeOrderRequest S.MimeJSON + placeOrderResult <- S.dispatchMime mgr config placeOrderRequest NH.responseStatus (S.mimeResultResponse placeOrderResult) `shouldBe` NH.status200 case S.mimeResult placeOrderResult of Right order -> do @@ -207,8 +213,8 @@ testStoreOps mgr config = do Just order@S.Order {S.orderId = Just orderId} -> go (orderId, order) _ -> pendingWith "no orderId") $ it "getOrderById" $ \(orderId, order) -> do - let getOrderByIdRequest = S.getOrderById (S.OrderId orderId) - getOrderByIdRequestResult <- S.dispatchMime mgr config getOrderByIdRequest S.MimeJSON + let getOrderByIdRequest = S.getOrderById (S.Accept S.MimeJSON) (S.OrderId orderId) + getOrderByIdRequestResult <- S.dispatchMime mgr config getOrderByIdRequest NH.responseStatus (S.mimeResultResponse getOrderByIdRequestResult) `shouldBe` NH.status200 case S.mimeResult getOrderByIdRequestResult of Right o -> o `shouldBe` order @@ -219,8 +225,8 @@ testStoreOps mgr config = do Just S.Order {S.orderId = Just orderId} -> go (T.pack (show orderId)) _ -> pendingWith "no orderId") $ it "deleteOrder" $ \orderId -> do - let deleteOrderRequest = S.deleteOrder (S.OrderIdText orderId) - deleteOrderResult <- S.dispatchLbs mgr config deleteOrderRequest S.MimeJSON + let deleteOrderRequest = S.deleteOrder (S.Accept S.MimeJSON) (S.OrderIdText orderId) + deleteOrderResult <- S.dispatchLbs mgr config deleteOrderRequest NH.responseStatus deleteOrderResult `shouldBe` NH.status200 @@ -250,26 +256,26 @@ testUserOps mgr config = do before (pure _user) $ it "createUser" $ \user -> do - let createUserRequest = S.createUser S.MimeJSON user - createUserResult <- S.dispatchLbs mgr config createUserRequest S.MimeJSON + let createUserRequest = S.createUser (S.ContentType S.MimeJSON) (S.Accept S.MimeJSON) user + createUserResult <- S.dispatchLbs mgr config createUserRequest NH.responseStatus createUserResult `shouldBe` NH.status200 before (pure _users) $ it "createUsersWithArrayInput" $ \users -> do - let createUsersWithArrayInputRequest = S.createUsersWithArrayInput S.MimeJSON (S.Body users) - createUsersWithArrayInputResult <- S.dispatchLbs mgr config createUsersWithArrayInputRequest S.MimeNoContent + let createUsersWithArrayInputRequest = S.createUsersWithArrayInput (S.ContentType S.MimeJSON) (S.Accept S.MimeNoContent) (S.Body users) + createUsersWithArrayInputResult <- S.dispatchLbs mgr config createUsersWithArrayInputRequest NH.responseStatus createUsersWithArrayInputResult `shouldBe` NH.status200 before (pure _users) $ it "createUsersWithListInput" $ \users -> do - let createUsersWithListInputRequest = S.createUsersWithListInput S.MimeJSON (S.Body users) - createUsersWithListInputResult <- S.dispatchLbs mgr config createUsersWithListInputRequest S.MimeNoContent + let createUsersWithListInputRequest = S.createUsersWithListInput (S.ContentType S.MimeJSON) (S.Accept S.MimeNoContent) (S.Body users) + createUsersWithListInputResult <- S.dispatchLbs mgr config createUsersWithListInputRequest NH.responseStatus createUsersWithListInputResult `shouldBe` NH.status200 before (pure (_username, _user)) $ it "getUserByName" $ \(username, user) -> do - let getUserByNameRequest = S.getUserByName (S.Username username) - getUserByNameResult <- S.dispatchMime mgr config getUserByNameRequest S.MimeJSON + let getUserByNameRequest = S.getUserByName (S.Accept S.MimeJSON) (S.Username username) + getUserByNameResult <- S.dispatchMime mgr config getUserByNameRequest NH.responseStatus (S.mimeResultResponse getUserByNameResult) `shouldBe` NH.status200 case S.mimeResult getUserByNameResult of Right u -> u `shouldBe` user @@ -277,22 +283,22 @@ testUserOps mgr config = do before (pure (_username, _password)) $ it "loginUser" $ \(username, password) -> do - let loginUserRequest = S.loginUser (S.Username username) (S.Password password) - loginUserResult <- S.dispatchLbs mgr config loginUserRequest S.MimeJSON + let loginUserRequest = S.loginUser (S.Accept S.MimeJSON) (S.Username username) (S.Password password) + loginUserResult <- S.dispatchLbs mgr config loginUserRequest NH.responseStatus loginUserResult `shouldBe` NH.status200 before (pure (_username, _user)) $ it "updateUser" $ \(username, user) -> do - let updateUserRequest = S.updateUser S.MimeJSON (S.Username username) user - updateUserResult <- S.dispatchLbs mgr config updateUserRequest S.MimeJSON + let updateUserRequest = S.updateUser (S.ContentType S.MimeJSON) (S.Accept S.MimeJSON) (S.Username username) user + updateUserResult <- S.dispatchLbs mgr config updateUserRequest NH.responseStatus updateUserResult `shouldBe` NH.status200 it "logoutuser" $ do - logoutUserResult <- S.dispatchLbs mgr config S.logoutUser S.MimeJSON + logoutUserResult <- S.dispatchLbs mgr config (S.logoutUser (S.Accept S.MimeJSON)) NH.responseStatus logoutUserResult `shouldBe` NH.status200 before (pure _username) $ it "deleteUser" $ \username -> do - let deleteUserRequest = S.deleteUser (S.Username username) - deleteUserResult <- S.dispatchLbs mgr config deleteUserRequest S.MimeJSON + let deleteUserRequest = S.deleteUser (S.Accept S.MimeJSON) (S.Username username) + deleteUserResult <- S.dispatchLbs mgr config deleteUserRequest NH.responseStatus deleteUserResult `shouldBe` NH.status200 diff --git a/samples/client/petstore/haskell-http-client/tests/Instances.hs b/samples/client/petstore/haskell-http-client/tests/Instances.hs index 43cc2d9e622..18349ade341 100644 --- a/samples/client/petstore/haskell-http-client/tests/Instances.hs +++ b/samples/client/petstore/haskell-http-client/tests/Instances.hs @@ -95,20 +95,17 @@ instance Arbitrary AdditionalPropertiesClass where <$> arbitrary -- additionalPropertiesClassMapProperty :: Maybe (Map.Map String Text) <*> arbitrary -- additionalPropertiesClassMapOfMapProperty :: Maybe (Map.Map String (Map.Map String Text)) - instance Arbitrary Animal where arbitrary = Animal <$> arbitrary -- animalClassName :: Text <*> arbitrary -- animalColor :: Maybe Text - instance Arbitrary AnimalFarm where arbitrary = pure AnimalFarm - instance Arbitrary ApiResponse where arbitrary = ApiResponse @@ -116,19 +113,16 @@ instance Arbitrary ApiResponse where <*> arbitrary -- apiResponseType :: Maybe Text <*> arbitrary -- apiResponseMessage :: Maybe Text - instance Arbitrary ArrayOfArrayOfNumberOnly where arbitrary = ArrayOfArrayOfNumberOnly <$> arbitrary -- arrayOfArrayOfNumberOnlyArrayArrayNumber :: Maybe [[Double]] - instance Arbitrary ArrayOfNumberOnly where arbitrary = ArrayOfNumberOnly <$> arbitrary -- arrayOfNumberOnlyArrayNumber :: Maybe [Double] - instance Arbitrary ArrayTest where arbitrary = ArrayTest @@ -136,7 +130,6 @@ instance Arbitrary ArrayTest where <*> arbitrary -- arrayTestArrayArrayOfInteger :: Maybe [[Integer]] <*> arbitrary -- arrayTestArrayArrayOfModel :: Maybe [[ReadOnlyFirst]] - instance Arbitrary Capitalization where arbitrary = Capitalization @@ -147,39 +140,28 @@ instance Arbitrary Capitalization where <*> arbitrary -- capitalizationScaEthFlowPoints :: Maybe Text <*> arbitrary -- capitalizationAttName :: Maybe Text - instance Arbitrary Category where arbitrary = Category <$> arbitrary -- categoryId :: Maybe Integer <*> arbitrary -- categoryName :: Maybe Text - instance Arbitrary ClassModel where arbitrary = ClassModel <$> arbitrary -- classModelClass :: Maybe Text - instance Arbitrary Client where arbitrary = Client <$> arbitrary -- clientClient :: Maybe Text - instance Arbitrary EnumArrays where arbitrary = EnumArrays <$> arbitrary -- enumArraysJustSymbol :: Maybe Text <*> arbitrary -- enumArraysArrayEnum :: Maybe [Text] - -instance Arbitrary EnumClass where - arbitrary = - - pure EnumClass - - instance Arbitrary EnumTest where arbitrary = EnumTest @@ -188,7 +170,6 @@ instance Arbitrary EnumTest where <*> arbitrary -- enumTestEnumNumber :: Maybe Double <*> arbitrary -- enumTestOuterEnum :: Maybe OuterEnum - instance Arbitrary FormatTest where arbitrary = FormatTest @@ -206,21 +187,18 @@ instance Arbitrary FormatTest where <*> arbitrary -- formatTestUuid :: Maybe Text <*> arbitrary -- formatTestPassword :: Text - instance Arbitrary HasOnlyReadOnly where arbitrary = HasOnlyReadOnly <$> arbitrary -- hasOnlyReadOnlyBar :: Maybe Text <*> arbitrary -- hasOnlyReadOnlyFoo :: Maybe Text - instance Arbitrary MapTest where arbitrary = MapTest <$> arbitrary -- mapTestMapMapOfString :: Maybe (Map.Map String (Map.Map String Text)) <*> arbitrary -- mapTestMapOfEnumString :: Maybe (Map.Map String Text) - instance Arbitrary MixedPropertiesAndAdditionalPropertiesClass where arbitrary = MixedPropertiesAndAdditionalPropertiesClass @@ -228,26 +206,22 @@ instance Arbitrary MixedPropertiesAndAdditionalPropertiesClass where <*> arbitrary -- mixedPropertiesAndAdditionalPropertiesClassDateTime :: Maybe DateTime <*> arbitrary -- mixedPropertiesAndAdditionalPropertiesClassMap :: Maybe (Map.Map String Animal) - instance Arbitrary Model200Response where arbitrary = Model200Response <$> arbitrary -- model200ResponseName :: Maybe Int <*> arbitrary -- model200ResponseClass :: Maybe Text - instance Arbitrary ModelList where arbitrary = ModelList <$> arbitrary -- modelList123List :: Maybe Text - instance Arbitrary ModelReturn where arbitrary = ModelReturn <$> arbitrary -- modelReturnReturn :: Maybe Int - instance Arbitrary Name where arbitrary = Name @@ -256,13 +230,11 @@ instance Arbitrary Name where <*> arbitrary -- nameProperty :: Maybe Text <*> arbitrary -- name123Number :: Maybe Int - instance Arbitrary NumberOnly where arbitrary = NumberOnly <$> arbitrary -- numberOnlyJustNumber :: Maybe Double - instance Arbitrary Order where arbitrary = Order @@ -273,11 +245,9 @@ instance Arbitrary Order where <*> arbitrary -- orderStatus :: Maybe Text <*> arbitrary -- orderComplete :: Maybe Bool - instance Arbitrary OuterBoolean where arbitrary = OuterBoolean <$> arbitrary - instance Arbitrary OuterComposite where arbitrary = OuterComposite @@ -285,21 +255,12 @@ instance Arbitrary OuterComposite where <*> arbitrary -- outerCompositeMyString :: Maybe OuterString <*> arbitrary -- outerCompositeMyBoolean :: Maybe OuterBoolean - -instance Arbitrary OuterEnum where - arbitrary = - - pure OuterEnum - - instance Arbitrary OuterNumber where arbitrary = OuterNumber <$> arbitrary - instance Arbitrary OuterString where arbitrary = OuterString <$> arbitrary - instance Arbitrary Pet where arbitrary = Pet @@ -310,27 +271,23 @@ instance Arbitrary Pet where <*> arbitrary -- petTags :: Maybe [Tag] <*> arbitrary -- petStatus :: Maybe Text - instance Arbitrary ReadOnlyFirst where arbitrary = ReadOnlyFirst <$> arbitrary -- readOnlyFirstBar :: Maybe Text <*> arbitrary -- readOnlyFirstBaz :: Maybe Text - instance Arbitrary SpecialModelName where arbitrary = SpecialModelName <$> arbitrary -- specialModelNameSpecialPropertyName :: Maybe Integer - instance Arbitrary Tag where arbitrary = Tag <$> arbitrary -- tagId :: Maybe Integer <*> arbitrary -- tagName :: Maybe Text - instance Arbitrary User where arbitrary = User @@ -343,7 +300,6 @@ instance Arbitrary User where <*> arbitrary -- userPhone :: Maybe Text <*> arbitrary -- userUserStatus :: Maybe Int - instance Arbitrary Cat where arbitrary = Cat @@ -351,7 +307,6 @@ instance Arbitrary Cat where <*> arbitrary -- catColor :: Maybe Text <*> arbitrary -- catDeclawed :: Maybe Bool - instance Arbitrary Dog where arbitrary = Dog @@ -361,3 +316,42 @@ instance Arbitrary Dog where + +instance Arbitrary E'ArrayEnum where + arbitrary = arbitraryBoundedEnum + +instance Arbitrary E'EnumFormString where + arbitrary = arbitraryBoundedEnum + +instance Arbitrary E'EnumInteger where + arbitrary = arbitraryBoundedEnum + +instance Arbitrary E'EnumNumber where + arbitrary = arbitraryBoundedEnum + +instance Arbitrary E'EnumQueryInteger where + arbitrary = arbitraryBoundedEnum + +instance Arbitrary E'EnumString where + arbitrary = arbitraryBoundedEnum + +instance Arbitrary E'Inner where + arbitrary = arbitraryBoundedEnum + +instance Arbitrary E'Inner2 where + arbitrary = arbitraryBoundedEnum + +instance Arbitrary E'JustSymbol where + arbitrary = arbitraryBoundedEnum + +instance Arbitrary E'Status where + arbitrary = arbitraryBoundedEnum + +instance Arbitrary E'Status2 where + arbitrary = arbitraryBoundedEnum + +instance Arbitrary EnumClass where + arbitrary = arbitraryBoundedEnum + +instance Arbitrary OuterEnum where + arbitrary = arbitraryBoundedEnum 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 b757d44bbe9..613e8a22fe6 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 @@ -181,6 +181,18 @@ public interface FakeApi extends ApiClient.Api { } } + /** + * test inline additionalProperties + * + * @param param request body (required) + */ + @RequestLine("POST /fake/inline-additionalProperties") + @Headers({ + "Content-Type: application/json", + "Accept: application/json", + }) + void testInlineAdditionalProperties(Object param); + /** * test json serialization of form data * diff --git a/samples/client/petstore/java/google-api-client/.gitignore b/samples/client/petstore/java/google-api-client/.gitignore new file mode 100644 index 00000000000..a530464afa1 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/.gitignore @@ -0,0 +1,21 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/samples/client/petstore/java/google-api-client/.swagger-codegen-ignore b/samples/client/petstore/java/google-api-client/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/google-api-client/.swagger-codegen/VERSION b/samples/client/petstore/java/google-api-client/.swagger-codegen/VERSION new file mode 100644 index 00000000000..f9f7450d135 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/google-api-client/.travis.yml b/samples/client/petstore/java/google-api-client/.travis.yml new file mode 100644 index 00000000000..70cb81a67c2 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/.travis.yml @@ -0,0 +1,17 @@ +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +language: java +jdk: + - oraclejdk8 + - oraclejdk7 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + - mvn test + # uncomment below to test using gradle + # - gradle test + # uncomment below to test using sbt + # - sbt test diff --git a/samples/client/petstore/java/google-api-client/README.md b/samples/client/petstore/java/google-api-client/README.md new file mode 100644 index 00000000000..336f86aa4f9 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/README.md @@ -0,0 +1,198 @@ +# swagger-petstore-google-api-client + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + io.swagger + swagger-petstore-google-api-client + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "io.swagger:swagger-petstore-google-api-client:1.0.0" +``` + +### Others + +At first generate the JAR by executing: + + mvn package + +Then manually install the following JARs: + +* target/swagger-petstore-google-api-client-1.0.0.jar +* target/lib/*.jar + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +import io.swagger.client.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; +import io.swagger.client.api.AnotherFakeApi; + +import java.io.File; +import java.util.*; + +public class AnotherFakeApiExample { + + public static void main(String[] args) { + + AnotherFakeApi apiInstance = new AnotherFakeApi(); + Client body = new Client(); // Client | client model + try { + Client result = apiInstance.testSpecialTags(body); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AnotherFakeApi#testSpecialTags"); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AnotherFakeApi* | [**testSpecialTags**](docs/AnotherFakeApi.md#testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags +*FakeApi* | [**fakeOuterBooleanSerialize**](docs/FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | +*FakeApi* | [**fakeOuterCompositeSerialize**](docs/FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | +*FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | +*FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | +*FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model +*FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**testEnumParameters**](docs/FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**testInlineAdditionalProperties**](docs/FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeApi* | [**testJsonFormData**](docs/FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeClassnameTags123Api* | [**testClassname**](docs/FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case +*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +*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/{order_id} | 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/{order_id} | 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 + + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayTest](docs/ArrayTest.md) + - [Capitalization](docs/Capitalization.md) + - [Category](docs/Category.md) + - [ClassModel](docs/ClassModel.md) + - [Client](docs/Client.md) + - [EnumArrays](docs/EnumArrays.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [FormatTest](docs/FormatTest.md) + - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [MapTest](docs/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model200Response.md) + - [ModelApiResponse](docs/ModelApiResponse.md) + - [ModelReturn](docs/ModelReturn.md) + - [Name](docs/Name.md) + - [NumberOnly](docs/NumberOnly.md) + - [Order](docs/Order.md) + - [OuterComposite](docs/OuterComposite.md) + - [OuterEnum](docs/OuterEnum.md) + - [Pet](docs/Pet.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [SpecialModelName](docs/SpecialModelName.md) + - [Tag](docs/Tag.md) + - [User](docs/User.md) + - [Cat](docs/Cat.md) + - [Dog](docs/Dog.md) + + +## Documentation for Authorization + +Authentication schemes defined for the API: +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +### api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + +### http_basic_test + +- **Type**: HTTP basic authentication + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. + +## Author + +apiteam@swagger.io + diff --git a/samples/client/petstore/java/google-api-client/build.gradle b/samples/client/petstore/java/google-api-client/build.gradle new file mode 100644 index 00000000000..14a87c5a65b --- /dev/null +++ b/samples/client/petstore/java/google-api-client/build.gradle @@ -0,0 +1,116 @@ +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 22 + } + 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: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-google-api-client' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.15" + jackson_version = "2.8.9" + google_api_client_version = "1.23.0" + jersey_common_version = "2.25.1" + jodatime_version = "2.9.9" + junit_version = "4.12" + jackson_threeten_version = "2.6.4" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "com.google.api-client:google-api-client:${google_api_client_version}" + compile "org.glassfish.jersey.core:jersey-common:${jersey_common_version}" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" + compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version" + compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$jackson_threeten_version" + testCompile "junit:junit:$junit_version" +} diff --git a/samples/client/petstore/java/google-api-client/build.sbt b/samples/client/petstore/java/google-api-client/build.sbt new file mode 100644 index 00000000000..28f21979abf --- /dev/null +++ b/samples/client/petstore/java/google-api-client/build.sbt @@ -0,0 +1,22 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-petstore-google-api-client", + 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.15", + "com.google.api-client" % "google-api-client" % "1.23.0", + "org.glassfish.jersey.core" % "jersey-common" % "2.25.1", + "com.fasterxml.jackson.core" % "jackson-core" % "2.8.9" % "compile", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.8.9" % "compile", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.8.9" % "compile", + "com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.6.4" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/google-api-client/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/google-api-client/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..0437c4dd8cc --- /dev/null +++ b/samples/client/petstore/java/google-api-client/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/google-api-client/docs/Animal.md b/samples/client/petstore/java/google-api-client/docs/Animal.md new file mode 100644 index 00000000000..b3f325c3524 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/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/google-api-client/docs/AnimalFarm.md b/samples/client/petstore/java/google-api-client/docs/AnimalFarm.md new file mode 100644 index 00000000000..c7c7f1ddcce --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/AnimalFarm.md @@ -0,0 +1,9 @@ + +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/google-api-client/docs/AnotherFakeApi.md b/samples/client/petstore/java/google-api-client/docs/AnotherFakeApi.md new file mode 100644 index 00000000000..7a04619aaba --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/AnotherFakeApi.md @@ -0,0 +1,54 @@ +# AnotherFakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testSpecialTags**](AnotherFakeApi.md#testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags + + + +# **testSpecialTags** +> Client testSpecialTags(body) + +To test special tags + +To test special tags + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.AnotherFakeApi; + + +AnotherFakeApi apiInstance = new AnotherFakeApi(); +Client body = new Client(); // Client | client model +try { + Client result = apiInstance.testSpecialTags(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling AnotherFakeApi#testSpecialTags"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/samples/client/petstore/java/google-api-client/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/google-api-client/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..77292549927 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ + +# ArrayOfArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayArrayNumber** | [**List<List<BigDecimal>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/google-api-client/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/google-api-client/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..e8cc4cd36dc --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ + +# ArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayNumber** | [**List<BigDecimal>**](BigDecimal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/google-api-client/docs/ArrayTest.md b/samples/client/petstore/java/google-api-client/docs/ArrayTest.md new file mode 100644 index 00000000000..9feee16427f --- /dev/null +++ b/samples/client/petstore/java/google-api-client/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/google-api-client/docs/Capitalization.md b/samples/client/petstore/java/google-api-client/docs/Capitalization.md new file mode 100644 index 00000000000..0f3064c1996 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/Capitalization.md @@ -0,0 +1,15 @@ + +# Capitalization + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**smallCamel** | **String** | | [optional] +**capitalCamel** | **String** | | [optional] +**smallSnake** | **String** | | [optional] +**capitalSnake** | **String** | | [optional] +**scAETHFlowPoints** | **String** | | [optional] +**ATT_NAME** | **String** | Name of the pet | [optional] + + + diff --git a/samples/client/petstore/java/google-api-client/docs/Cat.md b/samples/client/petstore/java/google-api-client/docs/Cat.md new file mode 100644 index 00000000000..6e9f71ce7dd --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/Cat.md @@ -0,0 +1,10 @@ + +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/google-api-client/docs/Category.md b/samples/client/petstore/java/google-api-client/docs/Category.md new file mode 100644 index 00000000000..e2df0803278 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/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/google-api-client/docs/ClassModel.md b/samples/client/petstore/java/google-api-client/docs/ClassModel.md new file mode 100644 index 00000000000..64f880c8786 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/ClassModel.md @@ -0,0 +1,10 @@ + +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**propertyClass** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/google-api-client/docs/Client.md b/samples/client/petstore/java/google-api-client/docs/Client.md new file mode 100644 index 00000000000..5c490ea166c --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/Client.md @@ -0,0 +1,10 @@ + +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/google-api-client/docs/Dog.md b/samples/client/petstore/java/google-api-client/docs/Dog.md new file mode 100644 index 00000000000..ac7cea323ff --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/Dog.md @@ -0,0 +1,10 @@ + +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/google-api-client/docs/EnumArrays.md b/samples/client/petstore/java/google-api-client/docs/EnumArrays.md new file mode 100644 index 00000000000..4dddc0bfd27 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/EnumArrays.md @@ -0,0 +1,27 @@ + +# EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justSymbol** | [**JustSymbolEnum**](#JustSymbolEnum) | | [optional] +**arrayEnum** | [**List<ArrayEnumEnum>**](#List<ArrayEnumEnum>) | | [optional] + + + +## Enum: JustSymbolEnum +Name | Value +---- | ----- +GREATER_THAN_OR_EQUAL_TO | ">=" +DOLLAR | "$" + + + +## Enum: List<ArrayEnumEnum> +Name | Value +---- | ----- +FISH | "fish" +CRAB | "crab" + + + diff --git a/samples/client/petstore/java/google-api-client/docs/EnumClass.md b/samples/client/petstore/java/google-api-client/docs/EnumClass.md new file mode 100644 index 00000000000..c746edc3cb1 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/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/google-api-client/docs/EnumTest.md b/samples/client/petstore/java/google-api-client/docs/EnumTest.md new file mode 100644 index 00000000000..08fee344882 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/EnumTest.md @@ -0,0 +1,38 @@ + +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] +**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] +**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] +**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] + + + +## Enum: EnumStringEnum +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" +EMPTY | "" + + + +## Enum: EnumIntegerEnum +Name | Value +---- | ----- +NUMBER_1 | 1 +NUMBER_MINUS_1 | -1 + + + +## Enum: EnumNumberEnum +Name | Value +---- | ----- +NUMBER_1_DOT_1 | 1.1 +NUMBER_MINUS_1_DOT_2 | -1.2 + + + diff --git a/samples/client/petstore/java/google-api-client/docs/FakeApi.md b/samples/client/petstore/java/google-api-client/docs/FakeApi.md new file mode 100644 index 00000000000..88bb107629e --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/FakeApi.md @@ -0,0 +1,469 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**fakeOuterBooleanSerialize**](FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | +[**fakeOuterCompositeSerialize**](FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | +[**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | +[**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | +[**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data + + + +# **fakeOuterBooleanSerialize** +> Boolean fakeOuterBooleanSerialize(body) + + + +Test serialization of outer boolean types + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Boolean body = true; // Boolean | Input boolean as post body +try { + Boolean result = apiInstance.fakeOuterBooleanSerialize(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterBooleanSerialize"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Boolean**](Boolean.md)| Input boolean as post body | [optional] + +### Return type + +**Boolean** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **fakeOuterCompositeSerialize** +> OuterComposite fakeOuterCompositeSerialize(body) + + + +Test serialization of object with outer number type + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +OuterComposite body = new OuterComposite(); // OuterComposite | Input composite as post body +try { + OuterComposite result = apiInstance.fakeOuterCompositeSerialize(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterCompositeSerialize"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] + +### Return type + +[**OuterComposite**](OuterComposite.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **fakeOuterNumberSerialize** +> BigDecimal fakeOuterNumberSerialize(body) + + + +Test serialization of outer number types + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +BigDecimal body = new BigDecimal(); // BigDecimal | Input number as post body +try { + BigDecimal result = apiInstance.fakeOuterNumberSerialize(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterNumberSerialize"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**BigDecimal**](BigDecimal.md)| Input number as post body | [optional] + +### Return type + +[**BigDecimal**](BigDecimal.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **fakeOuterStringSerialize** +> String fakeOuterStringSerialize(body) + + + +Test serialization of outer string types + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +String body = "body_example"; // String | Input string as post body +try { + String result = apiInstance.fakeOuterStringSerialize(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterStringSerialize"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**String**](String.md)| Input string as post body | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **testClientModel** +> Client testClientModel(body) + +To test \"client\" model + +To test \"client\" model + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Client body = new Client(); // Client | client model +try { + Client result = apiInstance.testClientModel(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testClientModel"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +# **testEndpointParameters** +> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.FakeApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure HTTP basic authorization: http_basic_test +HttpBasicAuth http_basic_test = (HttpBasicAuth) defaultClient.getAuthentication("http_basic_test"); +http_basic_test.setUsername("YOUR USERNAME"); +http_basic_test.setPassword("YOUR PASSWORD"); + +FakeApi apiInstance = new FakeApi(); +BigDecimal number = new BigDecimal(); // BigDecimal | None +Double _double = 3.4D; // Double | None +String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None +byte[] _byte = _byte_example; // byte[] | None +Integer integer = 56; // Integer | None +Integer int32 = 56; // Integer | None +Long int64 = 789L; // Long | None +Float _float = 3.4F; // Float | None +String string = "string_example"; // String | None +byte[] binary = B; // byte[] | None +LocalDate date = new LocalDate(); // LocalDate | None +OffsetDateTime dateTime = new OffsetDateTime(); // OffsetDateTime | None +String password = "password_example"; // String | None +String paramCallback = "paramCallback_example"; // String | None +try { + apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **BigDecimal**| None | + **_double** | **Double**| None | + **patternWithoutDelimiter** | **String**| None | + **_byte** | **byte[]**| None | + **integer** | **Integer**| None | [optional] + **int32** | **Integer**| None | [optional] + **int64** | **Long**| None | [optional] + **_float** | **Float**| None | [optional] + **string** | **String**| None | [optional] + **binary** | **byte[]**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **OffsetDateTime**| None | [optional] + **password** | **String**| None | [optional] + **paramCallback** | **String**| None | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### 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 + + +# **testEnumParameters** +> testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble) + +To test enum parameters + +To test enum parameters + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +List enumFormStringArray = Arrays.asList("enumFormStringArray_example"); // List | Form parameter enum test (string array) +String enumFormString = "-efg"; // String | Form parameter enum test (string) +List enumHeaderStringArray = Arrays.asList("enumHeaderStringArray_example"); // List | Header parameter enum test (string array) +String enumHeaderString = "-efg"; // String | Header parameter enum test (string) +List enumQueryStringArray = Arrays.asList("enumQueryStringArray_example"); // List | Query parameter enum test (string array) +String enumQueryString = "-efg"; // String | Query parameter enum test (string) +Integer enumQueryInteger = 56; // Integer | Query parameter enum test (double) +Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) +try { + apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEnumParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumFormStringArray** | [**List<String>**](String.md)| Form parameter enum test (string array) | [optional] [enum: >, $] + **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumHeaderStringArray** | [**List<String>**](String.md)| Header parameter enum test (string array) | [optional] [enum: >, $] + **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] + **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryInteger** | **Integer**| Query parameter enum test (double) | [optional] [enum: 1, -2] + **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] [enum: 1.1, -1.2] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: */* + - **Accept**: */* + + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Object param = null; // Object | request body +try { + apiInstance.testInlineAdditionalProperties(param); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +# **testJsonFormData** +> testJsonFormData(param, param2) + +test json serialization of form data + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +String param = "param_example"; // String | field1 +String param2 = "param2_example"; // String | field2 +try { + apiInstance.testJsonFormData(param, param2); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testJsonFormData"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **String**| field1 | + **param2** | **String**| field2 | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + diff --git a/samples/client/petstore/java/google-api-client/docs/FakeClassnameTags123Api.md b/samples/client/petstore/java/google-api-client/docs/FakeClassnameTags123Api.md new file mode 100644 index 00000000000..bc728bfce5b --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/FakeClassnameTags123Api.md @@ -0,0 +1,62 @@ +# FakeClassnameTags123Api + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testClassname**](FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case + + + +# **testClassname** +> Client testClassname(body) + +To test class name in snake case + +### 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.FakeClassnameTags123Api; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key_query +ApiKeyAuth api_key_query = (ApiKeyAuth) defaultClient.getAuthentication("api_key_query"); +api_key_query.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key_query.setApiKeyPrefix("Token"); + +FakeClassnameTags123Api apiInstance = new FakeClassnameTags123Api(); +Client body = new Client(); // Client | client model +try { + Client result = apiInstance.testClassname(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeClassnameTags123Api#testClassname"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/samples/client/petstore/java/google-api-client/docs/FormatTest.md b/samples/client/petstore/java/google-api-client/docs/FormatTest.md new file mode 100644 index 00000000000..c7a3acb3cb7 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/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** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional] +**uuid** | [**UUID**](UUID.md) | | [optional] +**password** | **String** | | + + + diff --git a/samples/client/petstore/java/google-api-client/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/google-api-client/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..c1d0aac5672 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ + +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**foo** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/google-api-client/docs/MapTest.md b/samples/client/petstore/java/google-api-client/docs/MapTest.md new file mode 100644 index 00000000000..714a97a40d9 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/MapTest.md @@ -0,0 +1,19 @@ + +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapMapOfString** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] +**mapOfEnumString** | [**Map<String, InnerEnum>**](#Map<String, InnerEnum>) | | [optional] + + + +## Enum: Map<String, InnerEnum> +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" + + + diff --git a/samples/client/petstore/java/google-api-client/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/google-api-client/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..b12e2cd70e6 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ + +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | [**UUID**](UUID.md) | | [optional] +**dateTime** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/google-api-client/docs/Model200Response.md b/samples/client/petstore/java/google-api-client/docs/Model200Response.md new file mode 100644 index 00000000000..5b3a9a0e46d --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/Model200Response.md @@ -0,0 +1,11 @@ + +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | [optional] +**propertyClass** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/google-api-client/docs/ModelApiResponse.md b/samples/client/petstore/java/google-api-client/docs/ModelApiResponse.md new file mode 100644 index 00000000000..3eec8686cc9 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/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/google-api-client/docs/ModelReturn.md b/samples/client/petstore/java/google-api-client/docs/ModelReturn.md new file mode 100644 index 00000000000..a679b04953e --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/ModelReturn.md @@ -0,0 +1,10 @@ + +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/google-api-client/docs/Name.md b/samples/client/petstore/java/google-api-client/docs/Name.md new file mode 100644 index 00000000000..ce2fb4dee50 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/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/google-api-client/docs/NumberOnly.md b/samples/client/petstore/java/google-api-client/docs/NumberOnly.md new file mode 100644 index 00000000000..a3feac7fadc --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/NumberOnly.md @@ -0,0 +1,10 @@ + +# NumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justNumber** | [**BigDecimal**](BigDecimal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/google-api-client/docs/Order.md b/samples/client/petstore/java/google-api-client/docs/Order.md new file mode 100644 index 00000000000..268c617d1ff --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/Order.md @@ -0,0 +1,24 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" + + + diff --git a/samples/client/petstore/java/google-api-client/docs/OuterComposite.md b/samples/client/petstore/java/google-api-client/docs/OuterComposite.md new file mode 100644 index 00000000000..3f5a633c998 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/OuterComposite.md @@ -0,0 +1,12 @@ + +# OuterComposite + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**myNumber** | [**BigDecimal**](BigDecimal.md) | | [optional] +**myString** | **String** | | [optional] +**myBoolean** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/google-api-client/docs/OuterEnum.md b/samples/client/petstore/java/google-api-client/docs/OuterEnum.md new file mode 100644 index 00000000000..ed2cb206789 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/OuterEnum.md @@ -0,0 +1,14 @@ + +# OuterEnum + +## Enum + + +* `PLACED` (value: `"placed"`) + +* `APPROVED` (value: `"approved"`) + +* `DELIVERED` (value: `"delivered"`) + + + diff --git a/samples/client/petstore/java/google-api-client/docs/Pet.md b/samples/client/petstore/java/google-api-client/docs/Pet.md new file mode 100644 index 00000000000..5b63109ef92 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/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/google-api-client/docs/PetApi.md b/samples/client/petstore/java/google-api-client/docs/PetApi.md new file mode 100644 index 00000000000..b5fa395947d --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/PetApi.md @@ -0,0 +1,448 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> addPet(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 { + apiInstance.addPet(body); +} 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 + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **deletePet** +> 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 { + apiInstance.deletePet(petId, apiKey); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: 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 | [enum: available, pending, sold] + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByTags** +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```java +// Import classes: +//import 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** +> 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 { + apiInstance.updatePet(body); +} 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 + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **updatePetWithForm** +> 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 { + apiInstance.updatePetWithForm(petId, name, status); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] + **status** | **String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### 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/google-api-client/docs/ReadOnlyFirst.md b/samples/client/petstore/java/google-api-client/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..426b7cde95a --- /dev/null +++ b/samples/client/petstore/java/google-api-client/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/google-api-client/docs/SpecialModelName.md b/samples/client/petstore/java/google-api-client/docs/SpecialModelName.md new file mode 100644 index 00000000000..c2c6117c552 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/SpecialModelName.md @@ -0,0 +1,10 @@ + +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Long** | | [optional] + + + diff --git a/samples/client/petstore/java/google-api-client/docs/StoreApi.md b/samples/client/petstore/java/google-api-client/docs/StoreApi.md new file mode 100644 index 00000000000..7aed6450e6a --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/StoreApi.md @@ -0,0 +1,197 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{order_id} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```java +// Import classes: +//import 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 { + apiInstance.deleteOrder(orderId); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: 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>** + +### 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/google-api-client/docs/Tag.md b/samples/client/petstore/java/google-api-client/docs/Tag.md new file mode 100644 index 00000000000..de6814b55d5 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/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/google-api-client/docs/User.md b/samples/client/petstore/java/google-api-client/docs/User.md new file mode 100644 index 00000000000..8b6753dd284 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/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/google-api-client/docs/UserApi.md b/samples/client/petstore/java/google-api-client/docs/UserApi.md new file mode 100644 index 00000000000..2e6987951c8 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/docs/UserApi.md @@ -0,0 +1,370 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> createUser(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 { + apiInstance.createUser(body); +} 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 + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithArrayInput** +> 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 { + apiInstance.createUsersWithArrayInput(body); +} 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 + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithListInput** +> 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 { + apiInstance.createUsersWithListInput(body); +} 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 + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **deleteUser** +> 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 { + apiInstance.deleteUser(username); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: 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** +> 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 { + apiInstance.logoutUser(); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updateUser** +> 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 { + apiInstance.updateUser(username, body); +} 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 + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/google-api-client/git_push.sh b/samples/client/petstore/java/google-api-client/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git 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/samples/client/petstore/java/google-api-client/gradle.properties b/samples/client/petstore/java/google-api-client/gradle.properties new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/samples/client/petstore/java/google-api-client/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/client/petstore/java/google-api-client/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/google-api-client/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/samples/client/petstore/java/google-api-client/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/java/google-api-client/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/google-api-client/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/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/google-api-client/gradlew b/samples/client/petstore/java/google-api-client/gradlew new file mode 100644 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/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/google-api-client/gradlew.bat b/samples/client/petstore/java/google-api-client/gradlew.bat new file mode 100644 index 00000000000..5f192121eb4 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/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/google-api-client/pom.xml b/samples/client/petstore/java/google-api-client/pom.xml new file mode 100644 index 00000000000..fe773937c95 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/pom.xml @@ -0,0 +1,238 @@ + + 4.0.0 + io.swagger + swagger-petstore-google-api-client + jar + swagger-petstore-google-api-client + 1.0.0 + https://github.com/swagger-api/swagger-codegen + Swagger Java + + scm:git:git@github.com:swagger-api/swagger-codegen.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + + + + Swagger + apiteam@swagger.io + Swagger + http://swagger.io + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.10 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.1 + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + com.google.api-client + google-api-client + ${google-api-client-version} + + + + org.glassfish.jersey.core + jersey-common + ${jersey-common-version} + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + com.github.joschi.jackson + jackson-datatype-threetenbp + ${jackson-threetenbp-version} + + + + + junit + junit + ${junit-version} + test + + + + UTF-8 + 1.5.15 + 1.23.0 + 2.25.1 + 2.8.9 + 2.6.4 + 1.0.0 + 4.12 + + diff --git a/samples/client/petstore/java/google-api-client/settings.gradle b/samples/client/petstore/java/google-api-client/settings.gradle new file mode 100644 index 00000000000..35a7b0d0442 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-petstore-google-api-client" \ No newline at end of file diff --git a/samples/client/petstore/java/google-api-client/src/main/AndroidManifest.xml b/samples/client/petstore/java/google-api-client/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..465dcb520c4 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 00000000000..bef5c082b6b --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,114 @@ +package io.swagger.client; + +import io.swagger.client.api.*; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; + import org.threeten.bp.*; +import com.google.api.client.googleapis.util.Utils; +import com.google.api.client.http.AbstractHttpContent; +import com.google.api.client.http.HttpRequestFactory; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.HttpTransport; +import com.google.api.client.json.Json; + +import java.io.IOException; +import java.io.OutputStream; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + + +public class ApiClient { + private final String basePath; + private final HttpRequestFactory httpRequestFactory; + private final ObjectMapper objectMapper; + + private static final String defaultBasePath = "http://petstore.swagger.io:80/v2"; + + // A reasonable default object mapper. Client can pass in a chosen ObjectMapper anyway, this is just for reasonable defaults. + private static ObjectMapper createDefaultObjectMapper() { + ObjectMapper objectMapper = new ObjectMapper() + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .setDateFormat(new RFC3339DateFormat()); + ThreeTenModule module = new ThreeTenModule(); + module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT); + module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME); + module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME); + objectMapper.registerModule(module); + return objectMapper; + } + + public ApiClient() { + this(null, null, null, null); + } + + public ApiClient( + String basePath, + HttpTransport httpTransport, + HttpRequestInitializer initializer, + ObjectMapper objectMapper + ) { + this.basePath = basePath == null ? defaultBasePath : ( + basePath.endsWith("/") ? basePath.substring(0, basePath.length() - 1) : basePath + ); + this.httpRequestFactory = (httpTransport == null ? Utils.getDefaultTransport() : httpTransport).createRequestFactory(initializer); + this.objectMapper = (objectMapper == null ? createDefaultObjectMapper() : objectMapper); + } + + public HttpRequestFactory getHttpRequestFactory() { + return httpRequestFactory; + } + + public String getBasePath() { + return basePath; + } + + public ObjectMapper getObjectMapper() { + return objectMapper; + } + + public class JacksonJsonHttpContent extends AbstractHttpContent { + /* A POJO that can be serialized with a com.fasterxml Jackson ObjectMapper */ + private final Object data; + + public JacksonJsonHttpContent(Object data) { + super(Json.MEDIA_TYPE); + this.data = data; + } + + @Override + public void writeTo(OutputStream out) throws IOException { + objectMapper.writeValue(out, data); + } + } + + // Builder pattern to get API instances for this client. + + public AnotherFakeApi anotherFakeApi() { + return new AnotherFakeApi(this); + } + + public FakeApi fakeApi() { + return new FakeApi(this); + } + + public FakeClassnameTags123Api fakeClassnameTags123Api() { + return new FakeClassnameTags123Api(this); + } + + public PetApi petApi() { + return new PetApi(this); + } + + public StoreApi storeApi() { + return new StoreApi(this); + } + + public UserApi userApi() { + return new UserApi(this); + } + +} diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/CustomInstantDeserializer.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/CustomInstantDeserializer.java new file mode 100644 index 00000000000..5ed8ba446ec --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/CustomInstantDeserializer.java @@ -0,0 +1,232 @@ +package io.swagger.client; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonTokenId; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.datatype.threetenbp.DateTimeUtils; +import com.fasterxml.jackson.datatype.threetenbp.DecimalUtils; +import com.fasterxml.jackson.datatype.threetenbp.deser.ThreeTenDateTimeDeserializerBase; +import com.fasterxml.jackson.datatype.threetenbp.function.BiFunction; +import com.fasterxml.jackson.datatype.threetenbp.function.Function; +import org.threeten.bp.DateTimeException; +import org.threeten.bp.Instant; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.ZoneId; +import org.threeten.bp.ZonedDateTime; +import org.threeten.bp.format.DateTimeFormatter; +import org.threeten.bp.temporal.Temporal; +import org.threeten.bp.temporal.TemporalAccessor; + +import java.io.IOException; +import java.math.BigDecimal; + +/** + * Deserializer for ThreeTen temporal {@link Instant}s, {@link OffsetDateTime}, and {@link ZonedDateTime}s. + * Adapted from the jackson threetenbp InstantDeserializer to add support for deserializing rfc822 format. + * + * @author Nick Williams + */ +public class CustomInstantDeserializer + extends ThreeTenDateTimeDeserializerBase { + private static final long serialVersionUID = 1L; + + public static final CustomInstantDeserializer INSTANT = new CustomInstantDeserializer( + Instant.class, DateTimeFormatter.ISO_INSTANT, + new Function() { + @Override + public Instant apply(TemporalAccessor temporalAccessor) { + return Instant.from(temporalAccessor); + } + }, + new Function() { + @Override + public Instant apply(FromIntegerArguments a) { + return Instant.ofEpochMilli(a.value); + } + }, + new Function() { + @Override + public Instant apply(FromDecimalArguments a) { + return Instant.ofEpochSecond(a.integer, a.fraction); + } + }, + null + ); + + public static final CustomInstantDeserializer OFFSET_DATE_TIME = new CustomInstantDeserializer( + OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME, + new Function() { + @Override + public OffsetDateTime apply(TemporalAccessor temporalAccessor) { + return OffsetDateTime.from(temporalAccessor); + } + }, + new Function() { + @Override + public OffsetDateTime apply(FromIntegerArguments a) { + return OffsetDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); + } + }, + new Function() { + @Override + public OffsetDateTime apply(FromDecimalArguments a) { + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); + } + }, + new BiFunction() { + @Override + public OffsetDateTime apply(OffsetDateTime d, ZoneId z) { + return d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime())); + } + } + ); + + public static final CustomInstantDeserializer ZONED_DATE_TIME = new CustomInstantDeserializer( + ZonedDateTime.class, DateTimeFormatter.ISO_ZONED_DATE_TIME, + new Function() { + @Override + public ZonedDateTime apply(TemporalAccessor temporalAccessor) { + return ZonedDateTime.from(temporalAccessor); + } + }, + new Function() { + @Override + public ZonedDateTime apply(FromIntegerArguments a) { + return ZonedDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); + } + }, + new Function() { + @Override + public ZonedDateTime apply(FromDecimalArguments a) { + return ZonedDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); + } + }, + new BiFunction() { + @Override + public ZonedDateTime apply(ZonedDateTime zonedDateTime, ZoneId zoneId) { + return zonedDateTime.withZoneSameInstant(zoneId); + } + } + ); + + protected final Function fromMilliseconds; + + protected final Function fromNanoseconds; + + protected final Function parsedToValue; + + protected final BiFunction adjust; + + protected CustomInstantDeserializer(Class supportedType, + DateTimeFormatter parser, + Function parsedToValue, + Function fromMilliseconds, + Function fromNanoseconds, + BiFunction adjust) { + super(supportedType, parser); + this.parsedToValue = parsedToValue; + this.fromMilliseconds = fromMilliseconds; + this.fromNanoseconds = fromNanoseconds; + this.adjust = adjust == null ? new BiFunction() { + @Override + public T apply(T t, ZoneId zoneId) { + return t; + } + } : adjust; + } + + @SuppressWarnings("unchecked") + protected CustomInstantDeserializer(CustomInstantDeserializer base, DateTimeFormatter f) { + super((Class) base.handledType(), f); + parsedToValue = base.parsedToValue; + fromMilliseconds = base.fromMilliseconds; + fromNanoseconds = base.fromNanoseconds; + adjust = base.adjust; + } + + @Override + protected JsonDeserializer withDateFormat(DateTimeFormatter dtf) { + if (dtf == _formatter) { + return this; + } + return new CustomInstantDeserializer(this, dtf); + } + + @Override + public T deserialize(JsonParser parser, DeserializationContext context) throws IOException { + //NOTE: Timestamps contain no timezone info, and are always in configured TZ. Only + //string values have to be adjusted to the configured TZ. + switch (parser.getCurrentTokenId()) { + case JsonTokenId.ID_NUMBER_FLOAT: { + BigDecimal value = parser.getDecimalValue(); + long seconds = value.longValue(); + int nanoseconds = DecimalUtils.extractNanosecondDecimal(value, seconds); + return fromNanoseconds.apply(new FromDecimalArguments( + seconds, nanoseconds, getZone(context))); + } + + case JsonTokenId.ID_NUMBER_INT: { + long timestamp = parser.getLongValue(); + if (context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)) { + return this.fromNanoseconds.apply(new FromDecimalArguments( + timestamp, 0, this.getZone(context) + )); + } + return this.fromMilliseconds.apply(new FromIntegerArguments( + timestamp, this.getZone(context) + )); + } + + case JsonTokenId.ID_STRING: { + String string = parser.getText().trim(); + if (string.length() == 0) { + return null; + } + if (string.endsWith("+0000")) { + string = string.substring(0, string.length() - 5) + "Z"; + } + T value; + try { + TemporalAccessor acc = _formatter.parse(string); + value = parsedToValue.apply(acc); + if (context.isEnabled(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)) { + return adjust.apply(value, this.getZone(context)); + } + } catch (DateTimeException e) { + throw _peelDTE(e); + } + return value; + } + } + throw context.mappingException("Expected type float, integer, or string."); + } + + private ZoneId getZone(DeserializationContext context) { + // Instants are always in UTC, so don't waste compute cycles + return (_valueClass == Instant.class) ? null : DateTimeUtils.timeZoneToZoneId(context.getTimeZone()); + } + + private static class FromIntegerArguments { + public final long value; + public final ZoneId zoneId; + + private FromIntegerArguments(long value, ZoneId zoneId) { + this.value = value; + this.zoneId = zoneId; + } + } + + private static class FromDecimalArguments { + public final long integer; + public final int fraction; + public final ZoneId zoneId; + + private FromDecimalArguments(long integer, int fraction, ZoneId zoneId) { + this.integer = integer; + this.fraction = fraction; + this.zoneId = zoneId; + } + } +} diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/RFC3339DateFormat.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/RFC3339DateFormat.java new file mode 100644 index 00000000000..e8df24310aa --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/RFC3339DateFormat.java @@ -0,0 +1,32 @@ +/* + * 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. + */ + +package io.swagger.client; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/StringUtil.java new file mode 100644 index 00000000000..339a3fb36d5 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/StringUtil.java @@ -0,0 +1,55 @@ +/* + * 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. + */ + + +package io.swagger.client; + + +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

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

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } +} diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/AnotherFakeApi.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/AnotherFakeApi.java new file mode 100644 index 00000000000..d22b285c2d9 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/AnotherFakeApi.java @@ -0,0 +1,123 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; + +import io.swagger.client.model.Client; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.api.client.http.GenericUrl; +import com.google.api.client.http.HttpContent; +import com.google.api.client.http.HttpMethods; +import com.google.api.client.http.HttpResponse; + +import javax.ws.rs.core.UriBuilder; +import java.io.IOException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.List; +import java.util.ArrayList; + + +public class AnotherFakeApi { + private ApiClient apiClient; + + public AnotherFakeApi() { + this(new ApiClient()); + } + + public AnotherFakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * To test special tags + * To test special tags + *

200 - successful operation + * @param body client model + * @return Client + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public Client testSpecialTags(Client body) throws IOException { + HttpResponse response = testSpecialTagsForHttpResponse(body); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + /** + * To test special tags + * To test special tags + *

200 - successful operation + * @param body client model + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @return Client + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public Client testSpecialTags(Client body, Map params) throws IOException { + HttpResponse response = testSpecialTagsForHttpResponse(body, params); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + public HttpResponse testSpecialTagsForHttpResponse(Client body) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling testSpecialTags"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/another-fake/dummy"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.PATCH, genericUrl, content).execute(); + } + + public HttpResponse testSpecialTagsForHttpResponse(Client body, Map params) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling testSpecialTags"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/another-fake/dummy"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.PATCH, genericUrl, content).execute(); + } + + +} diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/FakeApi.java new file mode 100644 index 00000000000..6daa67575ee --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/FakeApi.java @@ -0,0 +1,776 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; + +import java.math.BigDecimal; +import io.swagger.client.model.Client; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import io.swagger.client.model.OuterComposite; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.api.client.http.GenericUrl; +import com.google.api.client.http.HttpContent; +import com.google.api.client.http.HttpMethods; +import com.google.api.client.http.HttpResponse; + +import javax.ws.rs.core.UriBuilder; +import java.io.IOException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.List; +import java.util.ArrayList; + + +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(new ApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Test serialization of outer boolean types + *

200 - Output boolean + * @param body Input boolean as post body + * @return Boolean + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public Boolean fakeOuterBooleanSerialize(Boolean body) throws IOException { + HttpResponse response = fakeOuterBooleanSerializeForHttpResponse(body); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + /** + * Test serialization of outer boolean types + *

200 - Output boolean + * @param body Input boolean as post body + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @return Boolean + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public Boolean fakeOuterBooleanSerialize(Boolean body, Map params) throws IOException { + HttpResponse response = fakeOuterBooleanSerializeForHttpResponse(body, params); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + public HttpResponse fakeOuterBooleanSerializeForHttpResponse(Boolean body) throws IOException { + Object postBody = body; + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/outer/boolean"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + public HttpResponse fakeOuterBooleanSerializeForHttpResponse(Boolean body, Map params) throws IOException { + Object postBody = body; + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/outer/boolean"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + + /** + * Test serialization of object with outer number type + *

200 - Output composite + * @param body Input composite as post body + * @return OuterComposite + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public OuterComposite fakeOuterCompositeSerialize(OuterComposite body) throws IOException { + HttpResponse response = fakeOuterCompositeSerializeForHttpResponse(body); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + /** + * Test serialization of object with outer number type + *

200 - Output composite + * @param body Input composite as post body + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @return OuterComposite + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public OuterComposite fakeOuterCompositeSerialize(OuterComposite body, Map params) throws IOException { + HttpResponse response = fakeOuterCompositeSerializeForHttpResponse(body, params); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + public HttpResponse fakeOuterCompositeSerializeForHttpResponse(OuterComposite body) throws IOException { + Object postBody = body; + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/outer/composite"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + public HttpResponse fakeOuterCompositeSerializeForHttpResponse(OuterComposite body, Map params) throws IOException { + Object postBody = body; + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/outer/composite"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + + /** + * Test serialization of outer number types + *

200 - Output number + * @param body Input number as post body + * @return BigDecimal + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public BigDecimal fakeOuterNumberSerialize(BigDecimal body) throws IOException { + HttpResponse response = fakeOuterNumberSerializeForHttpResponse(body); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + /** + * Test serialization of outer number types + *

200 - Output number + * @param body Input number as post body + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @return BigDecimal + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public BigDecimal fakeOuterNumberSerialize(BigDecimal body, Map params) throws IOException { + HttpResponse response = fakeOuterNumberSerializeForHttpResponse(body, params); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + public HttpResponse fakeOuterNumberSerializeForHttpResponse(BigDecimal body) throws IOException { + Object postBody = body; + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/outer/number"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + public HttpResponse fakeOuterNumberSerializeForHttpResponse(BigDecimal body, Map params) throws IOException { + Object postBody = body; + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/outer/number"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + + /** + * Test serialization of outer string types + *

200 - Output string + * @param body Input string as post body + * @return String + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public String fakeOuterStringSerialize(String body) throws IOException { + HttpResponse response = fakeOuterStringSerializeForHttpResponse(body); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + /** + * Test serialization of outer string types + *

200 - Output string + * @param body Input string as post body + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @return String + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public String fakeOuterStringSerialize(String body, Map params) throws IOException { + HttpResponse response = fakeOuterStringSerializeForHttpResponse(body, params); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + public HttpResponse fakeOuterStringSerializeForHttpResponse(String body) throws IOException { + Object postBody = body; + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/outer/string"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + public HttpResponse fakeOuterStringSerializeForHttpResponse(String body, Map params) throws IOException { + Object postBody = body; + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/outer/string"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + + /** + * To test \"client\" model + * To test \"client\" model + *

200 - successful operation + * @param body client model + * @return Client + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public Client testClientModel(Client body) throws IOException { + HttpResponse response = testClientModelForHttpResponse(body); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + /** + * To test \"client\" model + * To test \"client\" model + *

200 - successful operation + * @param body client model + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @return Client + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public Client testClientModel(Client body, Map params) throws IOException { + HttpResponse response = testClientModelForHttpResponse(body, params); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + public HttpResponse testClientModelForHttpResponse(Client body) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling testClientModel"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.PATCH, genericUrl, content).execute(); + } + + public HttpResponse testClientModelForHttpResponse(Client body, Map params) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling testClientModel"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.PATCH, genericUrl, content).execute(); + } + + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + *

400 - Invalid username supplied + *

404 - User not found + * @param number None + * @param _double None + * @param patternWithoutDelimiter None + * @param _byte None + * @param integer None + * @param int32 None + * @param int64 None + * @param _float None + * @param string None + * @param binary None + * @param date None + * @param dateTime None + * @param password None + * @param paramCallback None + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws IOException { + testEndpointParametersForHttpResponse(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + *

400 - Invalid username supplied + *

404 - User not found + * @param number None + * @param _double None + * @param patternWithoutDelimiter None + * @param _byte None + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Map params) throws IOException { + testEndpointParametersForHttpResponse(number, _double, patternWithoutDelimiter, _byte, params); + } + + public HttpResponse testEndpointParametersForHttpResponse(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws IOException { + Object postBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new IllegalArgumentException("Missing the required parameter 'number' when calling testEndpointParameters"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new IllegalArgumentException("Missing the required parameter '_double' when calling testEndpointParameters"); + } + + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) { + throw new IllegalArgumentException("Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new IllegalArgumentException("Missing the required parameter '_byte' when calling testEndpointParameters"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + public HttpResponse testEndpointParametersForHttpResponse(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Map params) throws IOException { + Object postBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new IllegalArgumentException("Missing the required parameter 'number' when calling testEndpointParameters"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new IllegalArgumentException("Missing the required parameter '_double' when calling testEndpointParameters"); + } + + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) { + throw new IllegalArgumentException("Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new IllegalArgumentException("Missing the required parameter '_byte' when calling testEndpointParameters"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + + /** + * To test enum parameters + * To test enum parameters + *

400 - Invalid request + *

404 - Not found + * @param enumFormStringArray Form parameter enum test (string array) + * @param enumFormString Form parameter enum test (string) + * @param enumHeaderStringArray Header parameter enum test (string array) + * @param enumHeaderString Header parameter enum test (string) + * @param enumQueryStringArray Query parameter enum test (string array) + * @param enumQueryString Query parameter enum test (string) + * @param enumQueryInteger Query parameter enum test (double) + * @param enumQueryDouble Query parameter enum test (double) + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws IOException { + testEnumParametersForHttpResponse(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + } + + /** + * To test enum parameters + * To test enum parameters + *

400 - Invalid request + *

404 - Not found + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void testEnumParameters(Map params) throws IOException { + testEnumParametersForHttpResponse(params); + } + + public HttpResponse testEnumParametersForHttpResponse(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws IOException { + Object postBody = null; + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake"); + if (enumQueryStringArray != null) { + uriBuilder = uriBuilder.queryParam("enum_query_string_array", enumQueryStringArray); + }if (enumQueryString != null) { + uriBuilder = uriBuilder.queryParam("enum_query_string", enumQueryString); + }if (enumQueryInteger != null) { + uriBuilder = uriBuilder.queryParam("enum_query_integer", enumQueryInteger); + } + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + public HttpResponse testEnumParametersForHttpResponse(Map params) throws IOException { + Object postBody = null; + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + + /** + * test inline additionalProperties + * + *

200 - successful operation + * @param param request body + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void testInlineAdditionalProperties(Object param) throws IOException { + testInlineAdditionalPropertiesForHttpResponse(param); + } + + /** + * test inline additionalProperties + * + *

200 - successful operation + * @param param request body + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void testInlineAdditionalProperties(Object param, Map params) throws IOException { + testInlineAdditionalPropertiesForHttpResponse(param, params); + } + + public HttpResponse testInlineAdditionalPropertiesForHttpResponse(Object param) throws IOException { + Object postBody = param; + + // verify the required parameter 'param' is set + if (param == null) { + throw new IllegalArgumentException("Missing the required parameter 'param' when calling testInlineAdditionalProperties"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/inline-additionalProperties"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + public HttpResponse testInlineAdditionalPropertiesForHttpResponse(Object param, Map params) throws IOException { + Object postBody = param; + + // verify the required parameter 'param' is set + if (param == null) { + throw new IllegalArgumentException("Missing the required parameter 'param' when calling testInlineAdditionalProperties"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/inline-additionalProperties"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + + /** + * test json serialization of form data + * + *

200 - successful operation + * @param param field1 + * @param param2 field2 + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void testJsonFormData(String param, String param2) throws IOException { + testJsonFormDataForHttpResponse(param, param2); + } + + /** + * test json serialization of form data + * + *

200 - successful operation + * @param param field1 + * @param param2 field2 + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void testJsonFormData(String param, String param2, Map params) throws IOException { + testJsonFormDataForHttpResponse(param, param2, params); + } + + public HttpResponse testJsonFormDataForHttpResponse(String param, String param2) throws IOException { + Object postBody = null; + + // verify the required parameter 'param' is set + if (param == null) { + throw new IllegalArgumentException("Missing the required parameter 'param' when calling testJsonFormData"); + } + + // verify the required parameter 'param2' is set + if (param2 == null) { + throw new IllegalArgumentException("Missing the required parameter 'param2' when calling testJsonFormData"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/jsonFormData"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + public HttpResponse testJsonFormDataForHttpResponse(String param, String param2, Map params) throws IOException { + Object postBody = null; + + // verify the required parameter 'param' is set + if (param == null) { + throw new IllegalArgumentException("Missing the required parameter 'param' when calling testJsonFormData"); + } + + // verify the required parameter 'param2' is set + if (param2 == null) { + throw new IllegalArgumentException("Missing the required parameter 'param2' when calling testJsonFormData"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/jsonFormData"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + +} diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/FakeClassnameTags123Api.java new file mode 100644 index 00000000000..30de3e3f702 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/FakeClassnameTags123Api.java @@ -0,0 +1,121 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; + +import io.swagger.client.model.Client; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.api.client.http.GenericUrl; +import com.google.api.client.http.HttpContent; +import com.google.api.client.http.HttpMethods; +import com.google.api.client.http.HttpResponse; + +import javax.ws.rs.core.UriBuilder; +import java.io.IOException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.List; +import java.util.ArrayList; + + +public class FakeClassnameTags123Api { + private ApiClient apiClient; + + public FakeClassnameTags123Api() { + this(new ApiClient()); + } + + public FakeClassnameTags123Api(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * To test class name in snake case + *

200 - successful operation + * @param body client model + * @return Client + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public Client testClassname(Client body) throws IOException { + HttpResponse response = testClassnameForHttpResponse(body); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + /** + * To test class name in snake case + *

200 - successful operation + * @param body client model + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @return Client + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public Client testClassname(Client body, Map params) throws IOException { + HttpResponse response = testClassnameForHttpResponse(body, params); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + public HttpResponse testClassnameForHttpResponse(Client body) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling testClassname"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake_classname_test"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.PATCH, genericUrl, content).execute(); + } + + public HttpResponse testClassnameForHttpResponse(Client body, Map params) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling testClassname"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake_classname_test"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.PATCH, genericUrl, content).execute(); + } + + +} diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/PetApi.java new file mode 100644 index 00000000000..a6e1d7120bb --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,728 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; + +import java.io.File; +import io.swagger.client.model.ModelApiResponse; +import io.swagger.client.model.Pet; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.api.client.http.GenericUrl; +import com.google.api.client.http.HttpContent; +import com.google.api.client.http.HttpMethods; +import com.google.api.client.http.HttpResponse; + +import javax.ws.rs.core.UriBuilder; +import java.io.IOException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.List; +import java.util.ArrayList; + + +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(new ApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Add a new pet to the store + * + *

405 - Invalid input + * @param body Pet object that needs to be added to the store + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void addPet(Pet body) throws IOException { + addPetForHttpResponse(body); + } + + /** + * Add a new pet to the store + * + *

405 - Invalid input + * @param body Pet object that needs to be added to the store + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void addPet(Pet body, Map params) throws IOException { + addPetForHttpResponse(body, params); + } + + public HttpResponse addPetForHttpResponse(Pet body) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling addPet"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + public HttpResponse addPetForHttpResponse(Pet body, Map params) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling addPet"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + + /** + * Deletes a pet + * + *

400 - Invalid pet value + * @param petId Pet id to delete + * @param apiKey The apiKey parameter + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void deletePet(Long petId, String apiKey) throws IOException { + deletePetForHttpResponse(petId, apiKey); + } + + /** + * Deletes a pet + * + *

400 - Invalid pet value + * @param petId Pet id to delete + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void deletePet(Long petId, Map params) throws IOException { + deletePetForHttpResponse(petId, params); + } + + public HttpResponse deletePetForHttpResponse(Long petId, String apiKey) throws IOException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new IllegalArgumentException("Missing the required parameter 'petId' when calling deletePet"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet/{petId}"); + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.DELETE, genericUrl, content).execute(); + } + + public HttpResponse deletePetForHttpResponse(Long petId, Map params) throws IOException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new IllegalArgumentException("Missing the required parameter 'petId' when calling deletePet"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet/{petId}"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.DELETE, genericUrl, content).execute(); + } + + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + *

200 - successful operation + *

400 - Invalid status value + * @param status Status values that need to be considered for filter + * @return List<Pet> + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public List findPetsByStatus(List status) throws IOException { + HttpResponse response = findPetsByStatusForHttpResponse(status); + TypeReference typeRef = new TypeReference>() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + *

200 - successful operation + *

400 - Invalid status value + * @param status Status values that need to be considered for filter + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @return List<Pet> + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public List findPetsByStatus(List status, Map params) throws IOException { + HttpResponse response = findPetsByStatusForHttpResponse(status, params); + TypeReference typeRef = new TypeReference>() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + public HttpResponse findPetsByStatusForHttpResponse(List status) throws IOException { + Object postBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new IllegalArgumentException("Missing the required parameter 'status' when calling findPetsByStatus"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet/findByStatus"); + if (status != null) { + uriBuilder = uriBuilder.queryParam("status", status); + } + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + public HttpResponse findPetsByStatusForHttpResponse(List status, Map params) throws IOException { + Object postBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new IllegalArgumentException("Missing the required parameter 'status' when calling findPetsByStatus"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet/findByStatus"); + + if (params == null) { + params = new HashMap(); + } + + // Add the required query param 'status' to the map of query params + params.put("status", status); + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + *

200 - successful operation + *

400 - Invalid tag value + * @param tags Tags to filter by + * @return List<Pet> + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public List findPetsByTags(List tags) throws IOException { + HttpResponse response = findPetsByTagsForHttpResponse(tags); + TypeReference typeRef = new TypeReference>() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + *

200 - successful operation + *

400 - Invalid tag value + * @param tags Tags to filter by + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @return List<Pet> + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public List findPetsByTags(List tags, Map params) throws IOException { + HttpResponse response = findPetsByTagsForHttpResponse(tags, params); + TypeReference typeRef = new TypeReference>() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + public HttpResponse findPetsByTagsForHttpResponse(List tags) throws IOException { + Object postBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new IllegalArgumentException("Missing the required parameter 'tags' when calling findPetsByTags"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet/findByTags"); + if (tags != null) { + uriBuilder = uriBuilder.queryParam("tags", tags); + } + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + public HttpResponse findPetsByTagsForHttpResponse(List tags, Map params) throws IOException { + Object postBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new IllegalArgumentException("Missing the required parameter 'tags' when calling findPetsByTags"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet/findByTags"); + + if (params == null) { + params = new HashMap(); + } + + // Add the required query param 'tags' to the map of query params + params.put("tags", tags); + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + + /** + * Find pet by ID + * Returns a single pet + *

200 - successful operation + *

400 - Invalid ID supplied + *

404 - Pet not found + * @param petId ID of pet to return + * @return Pet + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public Pet getPetById(Long petId) throws IOException { + HttpResponse response = getPetByIdForHttpResponse(petId); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + /** + * Find pet by ID + * Returns a single pet + *

200 - successful operation + *

400 - Invalid ID supplied + *

404 - Pet not found + * @param petId ID of pet to return + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @return Pet + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public Pet getPetById(Long petId, Map params) throws IOException { + HttpResponse response = getPetByIdForHttpResponse(petId, params); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + public HttpResponse getPetByIdForHttpResponse(Long petId) throws IOException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new IllegalArgumentException("Missing the required parameter 'petId' when calling getPetById"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet/{petId}"); + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + public HttpResponse getPetByIdForHttpResponse(Long petId, Map params) throws IOException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new IllegalArgumentException("Missing the required parameter 'petId' when calling getPetById"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet/{petId}"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + + /** + * Update an existing pet + * + *

400 - Invalid ID supplied + *

404 - Pet not found + *

405 - Validation exception + * @param body Pet object that needs to be added to the store + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void updatePet(Pet body) throws IOException { + updatePetForHttpResponse(body); + } + + /** + * Update an existing pet + * + *

400 - Invalid ID supplied + *

404 - Pet not found + *

405 - Validation exception + * @param body Pet object that needs to be added to the store + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void updatePet(Pet body, Map params) throws IOException { + updatePetForHttpResponse(body, params); + } + + public HttpResponse updatePetForHttpResponse(Pet body) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling updatePet"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.PUT, genericUrl, content).execute(); + } + + public HttpResponse updatePetForHttpResponse(Pet body, Map params) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling updatePet"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.PUT, genericUrl, content).execute(); + } + + + /** + * Updates a pet in the store with form data + * + *

405 - Invalid input + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void updatePetWithForm(Long petId, String name, String status) throws IOException { + updatePetWithFormForHttpResponse(petId, name, status); + } + + /** + * Updates a pet in the store with form data + * + *

405 - Invalid input + * @param petId ID of pet that needs to be updated + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void updatePetWithForm(Long petId, Map params) throws IOException { + updatePetWithFormForHttpResponse(petId, params); + } + + public HttpResponse updatePetWithFormForHttpResponse(Long petId, String name, String status) throws IOException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new IllegalArgumentException("Missing the required parameter 'petId' when calling updatePetWithForm"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet/{petId}"); + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + public HttpResponse updatePetWithFormForHttpResponse(Long petId, Map params) throws IOException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new IllegalArgumentException("Missing the required parameter 'petId' when calling updatePetWithForm"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet/{petId}"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + + /** + * uploads an image + * + *

200 - successful operation + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @return ModelApiResponse + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws IOException { + HttpResponse response = uploadFileForHttpResponse(petId, additionalMetadata, file); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + /** + * uploads an image + * + *

200 - successful operation + * @param petId ID of pet to update + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @return ModelApiResponse + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public ModelApiResponse uploadFile(Long petId, Map params) throws IOException { + HttpResponse response = uploadFileForHttpResponse(petId, params); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + public HttpResponse uploadFileForHttpResponse(Long petId, String additionalMetadata, File file) throws IOException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new IllegalArgumentException("Missing the required parameter 'petId' when calling uploadFile"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet/{petId}/uploadImage"); + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + public HttpResponse uploadFileForHttpResponse(Long petId, Map params) throws IOException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new IllegalArgumentException("Missing the required parameter 'petId' when calling uploadFile"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet/{petId}/uploadImage"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + +} diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 00000000000..9f104855514 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,371 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; + +import io.swagger.client.model.Order; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.api.client.http.GenericUrl; +import com.google.api.client.http.HttpContent; +import com.google.api.client.http.HttpMethods; +import com.google.api.client.http.HttpResponse; + +import javax.ws.rs.core.UriBuilder; +import java.io.IOException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.List; +import java.util.ArrayList; + + +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(new ApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + *

400 - Invalid ID supplied + *

404 - Order not found + * @param orderId ID of the order that needs to be deleted + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void deleteOrder(String orderId) throws IOException { + deleteOrderForHttpResponse(orderId); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + *

400 - Invalid ID supplied + *

404 - Order not found + * @param orderId ID of the order that needs to be deleted + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void deleteOrder(String orderId, Map params) throws IOException { + deleteOrderForHttpResponse(orderId, params); + } + + public HttpResponse deleteOrderForHttpResponse(String orderId) throws IOException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new IllegalArgumentException("Missing the required parameter 'orderId' when calling deleteOrder"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("order_id", orderId); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/store/order/{order_id}"); + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.DELETE, genericUrl, content).execute(); + } + + public HttpResponse deleteOrderForHttpResponse(String orderId, Map params) throws IOException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new IllegalArgumentException("Missing the required parameter 'orderId' when calling deleteOrder"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("order_id", orderId); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/store/order/{order_id}"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.DELETE, genericUrl, content).execute(); + } + + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + *

200 - successful operation + * @return Map<String, Integer> + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public Map getInventory() throws IOException { + HttpResponse response = getInventoryForHttpResponse(); + TypeReference typeRef = new TypeReference>() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + *

200 - successful operation + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @return Map<String, Integer> + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public Map getInventory(Map params) throws IOException { + HttpResponse response = getInventoryForHttpResponse(params); + TypeReference typeRef = new TypeReference>() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + public HttpResponse getInventoryForHttpResponse() throws IOException { + Object postBody = null; + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/store/inventory"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + public HttpResponse getInventoryForHttpResponse(Map params) throws IOException { + Object postBody = null; + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/store/inventory"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + *

200 - successful operation + *

400 - Invalid ID supplied + *

404 - Order not found + * @param orderId ID of pet that needs to be fetched + * @return Order + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public Order getOrderById(Long orderId) throws IOException { + HttpResponse response = getOrderByIdForHttpResponse(orderId); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + *

200 - successful operation + *

400 - Invalid ID supplied + *

404 - Order not found + * @param orderId ID of pet that needs to be fetched + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @return Order + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public Order getOrderById(Long orderId, Map params) throws IOException { + HttpResponse response = getOrderByIdForHttpResponse(orderId, params); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + public HttpResponse getOrderByIdForHttpResponse(Long orderId) throws IOException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new IllegalArgumentException("Missing the required parameter 'orderId' when calling getOrderById"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("order_id", orderId); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/store/order/{order_id}"); + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + public HttpResponse getOrderByIdForHttpResponse(Long orderId, Map params) throws IOException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new IllegalArgumentException("Missing the required parameter 'orderId' when calling getOrderById"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("order_id", orderId); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/store/order/{order_id}"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + + /** + * Place an order for a pet + * + *

200 - successful operation + *

400 - Invalid Order + * @param body order placed for purchasing the pet + * @return Order + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public Order placeOrder(Order body) throws IOException { + HttpResponse response = placeOrderForHttpResponse(body); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + /** + * Place an order for a pet + * + *

200 - successful operation + *

400 - Invalid Order + * @param body order placed for purchasing the pet + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @return Order + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public Order placeOrder(Order body, Map params) throws IOException { + HttpResponse response = placeOrderForHttpResponse(body, params); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + public HttpResponse placeOrderForHttpResponse(Order body) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling placeOrder"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/store/order"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + public HttpResponse placeOrderForHttpResponse(Order body, Map params) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling placeOrder"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/store/order"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + +} diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 00000000000..259af327076 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,712 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; + +import io.swagger.client.model.User; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.api.client.http.GenericUrl; +import com.google.api.client.http.HttpContent; +import com.google.api.client.http.HttpMethods; +import com.google.api.client.http.HttpResponse; + +import javax.ws.rs.core.UriBuilder; +import java.io.IOException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.List; +import java.util.ArrayList; + + +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(new ApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create user + * This can only be done by the logged in user. + *

0 - successful operation + * @param body Created user object + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void createUser(User body) throws IOException { + createUserForHttpResponse(body); + } + + /** + * Create user + * This can only be done by the logged in user. + *

0 - successful operation + * @param body Created user object + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void createUser(User body, Map params) throws IOException { + createUserForHttpResponse(body, params); + } + + public HttpResponse createUserForHttpResponse(User body) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling createUser"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + public HttpResponse createUserForHttpResponse(User body, Map params) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling createUser"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + + /** + * Creates list of users with given input array + * + *

0 - successful operation + * @param body List of user object + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void createUsersWithArrayInput(List body) throws IOException { + createUsersWithArrayInputForHttpResponse(body); + } + + /** + * Creates list of users with given input array + * + *

0 - successful operation + * @param body List of user object + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void createUsersWithArrayInput(List body, Map params) throws IOException { + createUsersWithArrayInputForHttpResponse(body, params); + } + + public HttpResponse createUsersWithArrayInputForHttpResponse(List body) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling createUsersWithArrayInput"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/createWithArray"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + public HttpResponse createUsersWithArrayInputForHttpResponse(List body, Map params) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling createUsersWithArrayInput"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/createWithArray"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + + /** + * Creates list of users with given input array + * + *

0 - successful operation + * @param body List of user object + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void createUsersWithListInput(List body) throws IOException { + createUsersWithListInputForHttpResponse(body); + } + + /** + * Creates list of users with given input array + * + *

0 - successful operation + * @param body List of user object + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void createUsersWithListInput(List body, Map params) throws IOException { + createUsersWithListInputForHttpResponse(body, params); + } + + public HttpResponse createUsersWithListInputForHttpResponse(List body) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling createUsersWithListInput"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/createWithList"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + public HttpResponse createUsersWithListInputForHttpResponse(List body, Map params) throws IOException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling createUsersWithListInput"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/createWithList"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute(); + } + + + /** + * Delete user + * This can only be done by the logged in user. + *

400 - Invalid username supplied + *

404 - User not found + * @param username The name that needs to be deleted + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void deleteUser(String username) throws IOException { + deleteUserForHttpResponse(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + *

400 - Invalid username supplied + *

404 - User not found + * @param username The name that needs to be deleted + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void deleteUser(String username, Map params) throws IOException { + deleteUserForHttpResponse(username, params); + } + + public HttpResponse deleteUserForHttpResponse(String username) throws IOException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new IllegalArgumentException("Missing the required parameter 'username' when calling deleteUser"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("username", username); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/{username}"); + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.DELETE, genericUrl, content).execute(); + } + + public HttpResponse deleteUserForHttpResponse(String username, Map params) throws IOException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new IllegalArgumentException("Missing the required parameter 'username' when calling deleteUser"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("username", username); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/{username}"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.DELETE, genericUrl, content).execute(); + } + + + /** + * Get user by user name + * + *

200 - successful operation + *

400 - Invalid username supplied + *

404 - User not found + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public User getUserByName(String username) throws IOException { + HttpResponse response = getUserByNameForHttpResponse(username); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + /** + * Get user by user name + * + *

200 - successful operation + *

400 - Invalid username supplied + *

404 - User not found + * @param username The name that needs to be fetched. Use user1 for testing. + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @return User + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public User getUserByName(String username, Map params) throws IOException { + HttpResponse response = getUserByNameForHttpResponse(username, params); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + public HttpResponse getUserByNameForHttpResponse(String username) throws IOException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new IllegalArgumentException("Missing the required parameter 'username' when calling getUserByName"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("username", username); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/{username}"); + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + public HttpResponse getUserByNameForHttpResponse(String username, Map params) throws IOException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new IllegalArgumentException("Missing the required parameter 'username' when calling getUserByName"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("username", username); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/{username}"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + + /** + * Logs user into the system + * + *

200 - successful operation + *

400 - Invalid username/password supplied + * @param username The user name for login + * @param password The password for login in clear text + * @return String + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public String loginUser(String username, String password) throws IOException { + HttpResponse response = loginUserForHttpResponse(username, password); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + /** + * Logs user into the system + * + *

200 - successful operation + *

400 - Invalid username/password supplied + * @param username The user name for login + * @param password The password for login in clear text + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @return String + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public String loginUser(String username, String password, Map params) throws IOException { + HttpResponse response = loginUserForHttpResponse(username, password, params); + TypeReference typeRef = new TypeReference() {}; + return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); + } + + public HttpResponse loginUserForHttpResponse(String username, String password) throws IOException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new IllegalArgumentException("Missing the required parameter 'username' when calling loginUser"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new IllegalArgumentException("Missing the required parameter 'password' when calling loginUser"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/login"); + if (username != null) { + uriBuilder = uriBuilder.queryParam("username", username); + }if (password != null) { + uriBuilder = uriBuilder.queryParam("password", password); + } + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + public HttpResponse loginUserForHttpResponse(String username, String password, Map params) throws IOException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new IllegalArgumentException("Missing the required parameter 'username' when calling loginUser"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new IllegalArgumentException("Missing the required parameter 'password' when calling loginUser"); + } + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/login"); + + if (params == null) { + params = new HashMap(); + } + + // Add the required query param 'username' to the map of query params + params.put("username", username); + + // Add the required query param 'password' to the map of query params + params.put("password", password); + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + + /** + * Logs out current logged in user session + * + *

0 - successful operation + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void logoutUser() throws IOException { + logoutUserForHttpResponse(); + } + + /** + * Logs out current logged in user session + * + *

0 - successful operation + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void logoutUser(Map params) throws IOException { + logoutUserForHttpResponse(params); + } + + public HttpResponse logoutUserForHttpResponse() throws IOException { + Object postBody = null; + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/logout"); + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + public HttpResponse logoutUserForHttpResponse(Map params) throws IOException { + Object postBody = null; + + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/logout"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.build().toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute(); + } + + + /** + * Updated user + * This can only be done by the logged in user. + *

400 - Invalid user supplied + *

404 - User not found + * @param username name that need to be deleted + * @param body Updated user object + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void updateUser(String username, User body) throws IOException { + updateUserForHttpResponse(username, body); + } + + /** + * Updated user + * This can only be done by the logged in user. + *

400 - Invalid user supplied + *

404 - User not found + * @param username name that need to be deleted + * @param body Updated user object + * @param params Map of query params. A collection will be interpreted as passing in multiple instances of the same query param. + * @throws IOException if an error occurs while attempting to invoke the API + **/ + public void updateUser(String username, User body, Map params) throws IOException { + updateUserForHttpResponse(username, body, params); + } + + public HttpResponse updateUserForHttpResponse(String username, User body) throws IOException { + Object postBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new IllegalArgumentException("Missing the required parameter 'username' when calling updateUser"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling updateUser"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("username", username); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/{username}"); + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.PUT, genericUrl, content).execute(); + } + + public HttpResponse updateUserForHttpResponse(String username, User body, Map params) throws IOException { + Object postBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new IllegalArgumentException("Missing the required parameter 'username' when calling updateUser"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new IllegalArgumentException("Missing the required parameter 'body' when calling updateUser"); + } + + // create a map of path variables + final Map uriVariables = new HashMap(); + uriVariables.put("username", username); + UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/{username}"); + + if (params == null) { + params = new HashMap(); + } + + for (Map.Entry entry: params.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key != null && value != null) { + if (value instanceof Collection) { + uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); + } else { + uriBuilder = uriBuilder.queryParam(key, value); + } + } + } + + + String url = uriBuilder.buildFromMap(uriVariables).toString(); + GenericUrl genericUrl = new GenericUrl(url); + + HttpContent content = postBody == null ? null : apiClient.new JacksonJsonHttpContent(postBody); + return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.PUT, genericUrl, content).execute(); + } + + +} diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..7fe69e168fd --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,132 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + @JsonProperty("map_property") + private Map mapProperty = null; + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = null; + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + if (this.mapProperty == null) { + this.mapProperty = new HashMap(); + } + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(value = "") + public Map getMapProperty() { + return mapProperty; + } + + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + if (this.mapOfMapProperty == null) { + this.mapOfMapProperty = new HashMap>(); + } + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @ApiModelProperty(value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Animal.java new file mode 100644 index 00000000000..590f36c0ae0 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Animal.java @@ -0,0 +1,120 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Animal + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className", visible = true ) +@JsonSubTypes({ + @JsonSubTypes.Type(value = Dog.class, name = "Dog"), + @JsonSubTypes.Type(value = Cat.class, name = "Cat"), +}) + +public class Animal { + @JsonProperty("className") + private String className = null; + + @JsonProperty("color") + private String color = "red"; + + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @ApiModelProperty(required = true, value = "") + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Animal color(String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); + } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/AnimalFarm.java new file mode 100644 index 00000000000..0b1d6a74cc6 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -0,0 +1,65 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.client.model.Animal; +import java.util.ArrayList; +import java.util.List; + +/** + * AnimalFarm + */ + +public class AnimalFarm extends ArrayList { + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..b7e59a030a4 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,101 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") + private List> arrayArrayNumber = null; + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + if (this.arrayArrayNumber == null) { + this.arrayArrayNumber = new ArrayList>(); + } + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..fdfeb6856f3 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,101 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") + private List arrayNumber = null; + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + if (this.arrayNumber == null) { + this.arrayNumber = new ArrayList(); + } + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(value = "") + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ArrayTest.java new file mode 100644 index 00000000000..62665c2536a --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ArrayTest.java @@ -0,0 +1,163 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayTest + */ + +public class ArrayTest { + @JsonProperty("array_of_string") + private List arrayOfString = null; + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = null; + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = null; + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + if (this.arrayOfString == null) { + this.arrayOfString = new ArrayList(); + } + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(value = "") + public List getArrayOfString() { + return arrayOfString; + } + + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + if (this.arrayArrayOfInteger == null) { + this.arrayArrayOfInteger = new ArrayList>(); + } + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + if (this.arrayArrayOfModel == null) { + this.arrayArrayOfModel = new ArrayList>(); + } + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Capitalization.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Capitalization.java new file mode 100644 index 00000000000..a72b0a72f46 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Capitalization.java @@ -0,0 +1,205 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Cat.java new file mode 100644 index 00000000000..b882da0ad90 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Cat.java @@ -0,0 +1,92 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; + +/** + * Cat + */ + +public class Cat extends Animal { + @JsonProperty("declawed") + private Boolean declawed = null; + + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + /** + * Get declawed + * @return declawed + **/ + @ApiModelProperty(value = "") + public Boolean isDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 00000000000..464f4375c4b --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,113 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Category + */ + +public class Category { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Category name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ClassModel.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ClassModel.java new file mode 100644 index 00000000000..4f764fde68d --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ClassModel.java @@ -0,0 +1,91 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Client.java new file mode 100644 index 00000000000..a7c4253499c --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Client.java @@ -0,0 +1,90 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Client + */ + +public class Client { + @JsonProperty("client") + private String client = null; + + public Client client(String client) { + this.client = client; + return this; + } + + /** + * Get client + * @return client + **/ + @ApiModelProperty(value = "") + public String getClient() { + return client; + } + + public void setClient(String client) { + this.client = client; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Client client = (Client) o; + return Objects.equals(this.client, client.client); + } + + @Override + public int hashCode() { + return Objects.hash(client); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Dog.java new file mode 100644 index 00000000000..7de179b2ade --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Dog.java @@ -0,0 +1,92 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; + +/** + * Dog + */ + +public class Dog extends Animal { + @JsonProperty("breed") + private String breed = null; + + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + /** + * Get breed + * @return breed + **/ + @ApiModelProperty(value = "") + public String getBreed() { + return breed; + } + + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(this.breed, dog.breed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(breed, super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/EnumArrays.java new file mode 100644 index 00000000000..12caa480285 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/EnumArrays.java @@ -0,0 +1,193 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + +/** + * EnumArrays + */ + +public class EnumArrays { + /** + * Gets or Sets justSymbol + */ + public enum JustSymbolEnum { + GREATER_THAN_OR_EQUAL_TO(">="), + + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static JustSymbolEnum fromValue(String text) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("just_symbol") + private JustSymbolEnum justSymbol = null; + + /** + * Gets or Sets arrayEnum + */ + public enum ArrayEnumEnum { + FISH("fish"), + + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ArrayEnumEnum fromValue(String text) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("array_enum") + private List arrayEnum = null; + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(value = "") + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { + if (this.arrayEnum == null) { + this.arrayEnum = new ArrayList(); + } + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(value = "") + public List getArrayEnum() { + return arrayEnum; + } + + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumArrays enumArrays = (EnumArrays) o; + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); + } + + @Override + public int hashCode() { + return Objects.hash(justSymbol, arrayEnum); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/EnumClass.java new file mode 100644 index 00000000000..abbd7a56668 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/EnumClass.java @@ -0,0 +1,58 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/EnumTest.java new file mode 100644 index 00000000000..93d0da037b6 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/EnumTest.java @@ -0,0 +1,267 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.OuterEnum; + +/** + * EnumTest + */ + +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"), + + EMPTY(""); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumStringEnum fromValue(String text) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_string") + private EnumStringEnum enumString = null; + + /** + * Gets or Sets enumInteger + */ + public enum EnumIntegerEnum { + NUMBER_1(1), + + NUMBER_MINUS_1(-1); + + private Integer value; + + EnumIntegerEnum(Integer value) { + this.value = value; + } + + @JsonValue + public Integer getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumIntegerEnum fromValue(String text) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_integer") + private EnumIntegerEnum enumInteger = null; + + /** + * Gets or Sets enumNumber + */ + public enum EnumNumberEnum { + NUMBER_1_DOT_1(1.1), + + NUMBER_MINUS_1_DOT_2(-1.2); + + private Double value; + + EnumNumberEnum(Double value) { + this.value = value; + } + + @JsonValue + public Double getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumNumberEnum fromValue(String text) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_number") + private EnumNumberEnum enumNumber = null; + + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(value = "") + public EnumStringEnum getEnumString() { + return enumString; + } + + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + @ApiModelProperty(value = "") + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + @ApiModelProperty(value = "") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/FormatTest.java new file mode 100644 index 00000000000..4118656d29e --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/FormatTest.java @@ -0,0 +1,380 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.UUID; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; + +/** + * FormatTest + */ + +public class FormatTest { + @JsonProperty("integer") + private Integer integer = null; + + @JsonProperty("int32") + private Integer int32 = null; + + @JsonProperty("int64") + private Long int64 = null; + + @JsonProperty("number") + private BigDecimal number = null; + + @JsonProperty("float") + private Float _float = null; + + @JsonProperty("double") + private Double _double = null; + + @JsonProperty("string") + private String string = null; + + @JsonProperty("byte") + private byte[] _byte = null; + + @JsonProperty("binary") + private byte[] binary = null; + + @JsonProperty("date") + private LocalDate date = null; + + @JsonProperty("dateTime") + private OffsetDateTime dateTime = null; + + @JsonProperty("uuid") + private UUID uuid = null; + + @JsonProperty("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10 + * maximum: 100 + * @return integer + **/ + @ApiModelProperty(value = "") + public Integer getInteger() { + return integer; + } + + public void setInteger(Integer integer) { + this.integer = integer; + } + + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int32 + * minimum: 20 + * maximum: 200 + * @return int32 + **/ + @ApiModelProperty(value = "") + public Integer getInt32() { + return int32; + } + + public void setInt32(Integer int32) { + this.int32 = int32; + } + + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + @ApiModelProperty(value = "") + public Long getInt64() { + return int64; + } + + public void setInt64(Long int64) { + this.int64 = int64; + } + + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + @ApiModelProperty(required = true, value = "") + public BigDecimal getNumber() { + return number; + } + + public void setNumber(BigDecimal number) { + this.number = number; + } + + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + @ApiModelProperty(value = "") + public Float getFloat() { + return _float; + } + + public void setFloat(Float _float) { + this._float = _float; + } + + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + @ApiModelProperty(value = "") + public Double getDouble() { + return _double; + } + + public void setDouble(Double _double) { + this._double = _double; + } + + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get string + * @return string + **/ + @ApiModelProperty(value = "") + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } + + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + @ApiModelProperty(required = true, value = "") + public byte[] getByte() { + return _byte; + } + + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + public FormatTest binary(byte[] binary) { + this.binary = binary; + return this; + } + + /** + * Get binary + * @return binary + **/ + @ApiModelProperty(value = "") + public byte[] getBinary() { + return binary; + } + + public void setBinary(byte[] binary) { + this.binary = binary; + } + + public FormatTest date(LocalDate date) { + this.date = date; + return this; + } + + /** + * Get date + * @return date + **/ + @ApiModelProperty(required = true, value = "") + public LocalDate getDate() { + return date; + } + + public void setDate(LocalDate date) { + this.date = date; + } + + public FormatTest dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public OffsetDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public UUID getUuid() { + return uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(required = true, value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..6dc9f12c4b8 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -0,0 +1,95 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * HasOnlyReadOnly + */ + +public class HasOnlyReadOnly { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("foo") + private String foo = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(value = "") + public String getFoo() { + return foo; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/MapTest.java new file mode 100644 index 00000000000..e6344a1df0f --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/MapTest.java @@ -0,0 +1,167 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * MapTest + */ + +public class MapTest { + @JsonProperty("map_map_of_string") + private Map> mapMapOfString = null; + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static InnerEnum fromValue(String text) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("map_of_enum_string") + private Map mapOfEnumString = null; + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + if (this.mapMapOfString == null) { + this.mapMapOfString = new HashMap>(); + } + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(value = "") + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + if (this.mapOfEnumString == null) { + this.mapOfEnumString = new HashMap(); + } + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(value = "") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + 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/google-api-client/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..29bfc7e8c08 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.threeten.bp.OffsetDateTime; + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private UUID uuid = null; + + @JsonProperty("dateTime") + private OffsetDateTime dateTime = null; + + @JsonProperty("map") + private Map map = null; + + public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public UUID getUuid() { + return uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public OffsetDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + if (this.map == null) { + this.map = new HashMap(); + } + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + **/ + @ApiModelProperty(value = "") + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Model200Response.java new file mode 100644 index 00000000000..58624475e43 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Model200Response.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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model name starting with number + */ +@ApiModel(description = "Model for testing model name starting with number") + +public class Model200Response { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("class") + private String propertyClass = null; + + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(this.name, _200Response.name) && + Objects.equals(this.propertyClass, _200Response.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(name, propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ModelApiResponse.java new file mode 100644 index 00000000000..b010e53b48c --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -0,0 +1,136 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * ModelApiResponse + */ + +public class ModelApiResponse { + @JsonProperty("code") + private Integer code = null; + + @JsonProperty("type") + private String type = null; + + @JsonProperty("message") + private String message = null; + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @ApiModelProperty(value = "") + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @ApiModelProperty(value = "") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + **/ + @ApiModelProperty(value = "") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ModelReturn.java new file mode 100644 index 00000000000..27d08557248 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ModelReturn.java @@ -0,0 +1,91 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing reserved words + */ +@ApiModel(description = "Model for testing reserved words") + +public class ModelReturn { + @JsonProperty("return") + private Integer _return = null; + + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + /** + * Get _return + * @return _return + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; + } + + public void setReturn(Integer _return) { + this._return = _return; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(this._return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Name.java new file mode 100644 index 00000000000..f2b9b1703bd --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Name.java @@ -0,0 +1,142 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model name same as property name + */ +@ApiModel(description = "Model for testing model name same as property name") + +public class Name { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("snake_case") + private Integer snakeCase = null; + + @JsonProperty("property") + private String property = null; + + @JsonProperty("123Number") + private Integer _123Number = null; + + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(required = true, value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(value = "") + public Integer getSnakeCase() { + return snakeCase; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(value = "") + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + /** + * Get _123Number + * @return _123Number + **/ + @ApiModelProperty(value = "") + public Integer get123Number() { + return _123Number; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123Number); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/NumberOnly.java new file mode 100644 index 00000000000..ec93aba0531 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/NumberOnly.java @@ -0,0 +1,91 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; + +/** + * NumberOnly + */ + +public class NumberOnly { + @JsonProperty("JustNumber") + private BigDecimal justNumber = null; + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @ApiModelProperty(value = "") + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(this.justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 00000000000..6976ceb8fba --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,243 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.threeten.bp.OffsetDateTime; + +/** + * Order + */ + +public class Order { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("petId") + private Long petId = null; + + @JsonProperty("quantity") + private Integer quantity = null; + + @JsonProperty("shipDate") + private OffsetDateTime shipDate = null; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + @JsonProperty("complete") + private Boolean complete = false; + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + **/ + @ApiModelProperty(value = "") + public Long getPetId() { + return petId; + } + + public void setPetId(Long petId) { + this.petId = petId; + } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + @ApiModelProperty(value = "") + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order shipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @ApiModelProperty(value = "") + public OffsetDateTime getShipDate() { + return shipDate; + } + + public void setShipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @ApiModelProperty(value = "") + public Boolean isComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/OuterComposite.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/OuterComposite.java new file mode 100644 index 00000000000..02c16a99b70 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/OuterComposite.java @@ -0,0 +1,137 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; + +/** + * OuterComposite + */ + +public class OuterComposite { + @JsonProperty("my_number") + private BigDecimal myNumber = null; + + @JsonProperty("my_string") + private String myString = null; + + @JsonProperty("my_boolean") + private Boolean myBoolean = null; + + public OuterComposite myNumber(BigDecimal myNumber) { + this.myNumber = myNumber; + return this; + } + + /** + * Get myNumber + * @return myNumber + **/ + @ApiModelProperty(value = "") + public BigDecimal getMyNumber() { + return myNumber; + } + + public void setMyNumber(BigDecimal myNumber) { + this.myNumber = myNumber; + } + + public OuterComposite myString(String myString) { + this.myString = myString; + return this; + } + + /** + * Get myString + * @return myString + **/ + @ApiModelProperty(value = "") + public String getMyString() { + return myString; + } + + public void setMyString(String myString) { + this.myString = myString; + } + + public OuterComposite myBoolean(Boolean myBoolean) { + this.myBoolean = myBoolean; + return this; + } + + /** + * Get myBoolean + * @return myBoolean + **/ + @ApiModelProperty(value = "") + public Boolean getMyBoolean() { + return myBoolean; + } + + public void setMyBoolean(Boolean myBoolean) { + this.myBoolean = myBoolean; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OuterComposite outerComposite = (OuterComposite) o; + return Objects.equals(this.myNumber, outerComposite.myNumber) && + Objects.equals(this.myString, outerComposite.myString) && + Objects.equals(this.myBoolean, outerComposite.myBoolean); + } + + @Override + public int hashCode() { + return Objects.hash(myNumber, myString, myBoolean); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OuterComposite {\n"); + + sb.append(" myNumber: ").append(toIndentedString(myNumber)).append("\n"); + sb.append(" myString: ").append(toIndentedString(myString)).append("\n"); + sb.append(" myBoolean: ").append(toIndentedString(myBoolean)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/OuterEnum.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/OuterEnum.java new file mode 100644 index 00000000000..948d80c2e6d --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/OuterEnum.java @@ -0,0 +1,58 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Pet.java new file mode 100644 index 00000000000..4c351dec3e4 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,259 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Category; +import io.swagger.client.model.Tag; +import java.util.ArrayList; +import java.util.List; + +/** + * Pet + */ + +public class Pet { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("category") + private Category category = null; + + @JsonProperty("name") + private String name = null; + + @JsonProperty("photoUrls") + private List photoUrls = new ArrayList(); + + @JsonProperty("tags") + private List tags = null; + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @ApiModelProperty(value = "") + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "doggie", required = true, value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @ApiModelProperty(required = true, value = "") + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..76f8a912f36 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,104 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * ReadOnlyFirst + */ + +public class ReadOnlyFirst { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("baz") + private String baz = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(value = "") + public String getBaz() { + return baz; + } + + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/SpecialModelName.java new file mode 100644 index 00000000000..784eb8baca8 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -0,0 +1,90 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * SpecialModelName + */ + +public class SpecialModelName { + @JsonProperty("$special[property.name]") + private Long specialPropertyName = null; + + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ + @ApiModelProperty(value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash(specialPropertyName); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Tag.java new file mode 100644 index 00000000000..1cf2f5bc5e6 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Tag.java @@ -0,0 +1,113 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Tag + */ + +public class Tag { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/User.java new file mode 100644 index 00000000000..de5bc439c5a --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/User.java @@ -0,0 +1,251 @@ +/* + * 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. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * User + */ + +public class User { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("username") + private String username = null; + + @JsonProperty("firstName") + private String firstName = null; + + @JsonProperty("lastName") + private String lastName = null; + + @JsonProperty("email") + private String email = null; + + @JsonProperty("password") + private String password = null; + + @JsonProperty("phone") + private String phone = null; + + @JsonProperty("userStatus") + private Integer userStatus = null; + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get username + * @return username + **/ + @ApiModelProperty(value = "") + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + @ApiModelProperty(value = "") + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + @ApiModelProperty(value = "") + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get email + * @return email + **/ + @ApiModelProperty(value = "") + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + **/ + @ApiModelProperty(value = "") + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + **/ + @ApiModelProperty(value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/AnotherFakeApiTest.java b/samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/AnotherFakeApiTest.java new file mode 100644 index 00000000000..109ff063df5 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/AnotherFakeApiTest.java @@ -0,0 +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. + */ + + +package io.swagger.client.api; + +import io.swagger.client.model.Client; +import org.junit.Test; +import org.junit.Ignore; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for AnotherFakeApi + */ +@Ignore +public class AnotherFakeApiTest { + + private final AnotherFakeApi api = new AnotherFakeApi(); + + + /** + * To test special tags + * + * To test special tags + * + * @throws IOException + * if the Api call fails + */ + @Test + public void testSpecialTagsTest() throws IOException { + Client body = null; + Client response = api.testSpecialTags(body); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/FakeApiTest.java new file mode 100644 index 00000000000..55ae5bb2a13 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -0,0 +1,204 @@ +/* + * 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. + */ + + +package io.swagger.client.api; + +import java.math.BigDecimal; +import io.swagger.client.model.Client; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import io.swagger.client.model.OuterComposite; +import org.junit.Test; +import org.junit.Ignore; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +@Ignore +public class FakeApiTest { + + private final FakeApi api = new FakeApi(); + + + /** + * + * + * Test serialization of outer boolean types + * + * @throws IOException + * if the Api call fails + */ + @Test + public void fakeOuterBooleanSerializeTest() throws IOException { + Boolean body = null; + Boolean response = api.fakeOuterBooleanSerialize(body); + + // TODO: test validations + } + + /** + * + * + * Test serialization of object with outer number type + * + * @throws IOException + * if the Api call fails + */ + @Test + public void fakeOuterCompositeSerializeTest() throws IOException { + OuterComposite body = null; + OuterComposite response = api.fakeOuterCompositeSerialize(body); + + // TODO: test validations + } + + /** + * + * + * Test serialization of outer number types + * + * @throws IOException + * if the Api call fails + */ + @Test + public void fakeOuterNumberSerializeTest() throws IOException { + BigDecimal body = null; + BigDecimal response = api.fakeOuterNumberSerialize(body); + + // TODO: test validations + } + + /** + * + * + * Test serialization of outer string types + * + * @throws IOException + * if the Api call fails + */ + @Test + public void fakeOuterStringSerializeTest() throws IOException { + String body = null; + String response = api.fakeOuterStringSerialize(body); + + // TODO: test validations + } + + /** + * To test \"client\" model + * + * To test \"client\" model + * + * @throws IOException + * if the Api call fails + */ + @Test + public void testClientModelTest() throws IOException { + Client body = null; + Client response = api.testClientModel(body); + + // TODO: test validations + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @throws IOException + * if the Api call fails + */ + @Test + public void testEndpointParametersTest() throws IOException { + BigDecimal number = null; + Double _double = null; + String patternWithoutDelimiter = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + String string = null; + byte[] binary = null; + LocalDate date = null; + OffsetDateTime dateTime = null; + String password = null; + String paramCallback = null; + api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + + // TODO: test validations + } + + /** + * To test enum parameters + * + * To test enum parameters + * + * @throws IOException + * if the Api call fails + */ + @Test + public void testEnumParametersTest() throws IOException { + List enumFormStringArray = null; + String enumFormString = null; + List enumHeaderStringArray = null; + String enumHeaderString = null; + List enumQueryStringArray = null; + String enumQueryString = null; + Integer enumQueryInteger = null; + Double enumQueryDouble = null; + api.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + + // TODO: test validations + } + + /** + * test inline additionalProperties + * + * + * + * @throws IOException + * if the Api call fails + */ + @Test + public void testInlineAdditionalPropertiesTest() throws IOException { + Object param = null; + api.testInlineAdditionalProperties(param); + + // TODO: test validations + } + + /** + * test json serialization of form data + * + * + * + * @throws IOException + * if the Api call fails + */ + @Test + public void testJsonFormDataTest() throws IOException { + String param = null; + String param2 = null; + api.testJsonFormData(param, param2); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/FakeClassnameTags123ApiTest.java b/samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/FakeClassnameTags123ApiTest.java new file mode 100644 index 00000000000..9564580b31b --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/FakeClassnameTags123ApiTest.java @@ -0,0 +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. + */ + + +package io.swagger.client.api; + +import io.swagger.client.model.Client; +import org.junit.Test; +import org.junit.Ignore; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeClassnameTags123Api + */ +@Ignore +public class FakeClassnameTags123ApiTest { + + private final FakeClassnameTags123Api api = new FakeClassnameTags123Api(); + + + /** + * To test class name in snake case + * + * + * + * @throws IOException + * if the Api call fails + */ + @Test + public void testClassnameTest() throws IOException { + Client body = null; + Client response = api.testClassname(body); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/PetApiTest.java new file mode 100644 index 00000000000..4547bcb8576 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/PetApiTest.java @@ -0,0 +1,170 @@ +/* + * 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. + */ + + +package io.swagger.client.api; + +import java.io.File; +import io.swagger.client.model.ModelApiResponse; +import io.swagger.client.model.Pet; +import org.junit.Test; +import org.junit.Ignore; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for PetApi + */ +@Ignore +public class PetApiTest { + + private final PetApi api = new PetApi(); + + + /** + * Add a new pet to the store + * + * + * + * @throws IOException + * if the Api call fails + */ + @Test + public void addPetTest() throws IOException { + Pet body = null; + api.addPet(body); + + // TODO: test validations + } + + /** + * Deletes a pet + * + * + * + * @throws IOException + * if the Api call fails + */ + @Test + public void deletePetTest() throws IOException { + 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 + * + * @throws IOException + * if the Api call fails + */ + @Test + public void findPetsByStatusTest() throws IOException { + 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. + * + * @throws IOException + * if the Api call fails + */ + @Test + public void findPetsByTagsTest() throws IOException { + List tags = null; + List response = api.findPetsByTags(tags); + + // TODO: test validations + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws IOException + * if the Api call fails + */ + @Test + public void getPetByIdTest() throws IOException { + Long petId = null; + Pet response = api.getPetById(petId); + + // TODO: test validations + } + + /** + * Update an existing pet + * + * + * + * @throws IOException + * if the Api call fails + */ + @Test + public void updatePetTest() throws IOException { + Pet body = null; + api.updatePet(body); + + // TODO: test validations + } + + /** + * Updates a pet in the store with form data + * + * + * + * @throws IOException + * if the Api call fails + */ + @Test + public void updatePetWithFormTest() throws IOException { + Long petId = null; + String name = null; + String status = null; + api.updatePetWithForm(petId, name, status); + + // TODO: test validations + } + + /** + * uploads an image + * + * + * + * @throws IOException + * if the Api call fails + */ + @Test + public void uploadFileTest() throws IOException { + 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/google-api-client/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/StoreApiTest.java new file mode 100644 index 00000000000..927e3693a09 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -0,0 +1,98 @@ +/* + * 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. + */ + + +package io.swagger.client.api; + +import io.swagger.client.model.Order; +import org.junit.Test; +import org.junit.Ignore; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for StoreApi + */ +@Ignore +public class StoreApiTest { + + private final StoreApi api = new StoreApi(); + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @throws IOException + * if the Api call fails + */ + @Test + public void deleteOrderTest() throws IOException { + String orderId = null; + api.deleteOrder(orderId); + + // TODO: test validations + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + * @throws IOException + * if the Api call fails + */ + @Test + public void getInventoryTest() throws IOException { + 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 + * + * @throws IOException + * if the Api call fails + */ + @Test + public void getOrderByIdTest() throws IOException { + Long orderId = null; + Order response = api.getOrderById(orderId); + + // TODO: test validations + } + + /** + * Place an order for a pet + * + * + * + * @throws IOException + * if the Api call fails + */ + @Test + public void placeOrderTest() throws IOException { + Order body = null; + Order response = api.placeOrder(body); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/UserApiTest.java new file mode 100644 index 00000000000..6d89cc2a831 --- /dev/null +++ b/samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/UserApiTest.java @@ -0,0 +1,164 @@ +/* + * 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. + */ + + +package io.swagger.client.api; + +import io.swagger.client.model.User; +import org.junit.Test; +import org.junit.Ignore; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for UserApi + */ +@Ignore +public class UserApiTest { + + private final UserApi api = new UserApi(); + + + /** + * Create user + * + * This can only be done by the logged in user. + * + * @throws IOException + * if the Api call fails + */ + @Test + public void createUserTest() throws IOException { + User body = null; + api.createUser(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws IOException + * if the Api call fails + */ + @Test + public void createUsersWithArrayInputTest() throws IOException { + List body = null; + api.createUsersWithArrayInput(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws IOException + * if the Api call fails + */ + @Test + public void createUsersWithListInputTest() throws IOException { + List body = null; + api.createUsersWithListInput(body); + + // TODO: test validations + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + * @throws IOException + * if the Api call fails + */ + @Test + public void deleteUserTest() throws IOException { + String username = null; + api.deleteUser(username); + + // TODO: test validations + } + + /** + * Get user by user name + * + * + * + * @throws IOException + * if the Api call fails + */ + @Test + public void getUserByNameTest() throws IOException { + String username = null; + User response = api.getUserByName(username); + + // TODO: test validations + } + + /** + * Logs user into the system + * + * + * + * @throws IOException + * if the Api call fails + */ + @Test + public void loginUserTest() throws IOException { + String username = null; + String password = null; + String response = api.loginUser(username, password); + + // TODO: test validations + } + + /** + * Logs out current logged in user session + * + * + * + * @throws IOException + * if the Api call fails + */ + @Test + public void logoutUserTest() throws IOException { + api.logoutUser(); + + // TODO: test validations + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + * @throws IOException + * if the Api call fails + */ + @Test + public void updateUserTest() throws IOException { + String username = null; + User body = null; + api.updateUser(username, body); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/jersey1/docs/FakeApi.md b/samples/client/petstore/java/jersey1/docs/FakeApi.md index 0418b476a66..737ccc28293 100644 --- a/samples/client/petstore/java/jersey1/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey1/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data @@ -267,7 +268,7 @@ FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None -byte[] _byte = _byte_example; // byte[] | None +byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None @@ -376,6 +377,50 @@ No authorization required - **Content-Type**: */* - **Accept**: */* + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Object param = null; // Object | request body +try { + apiInstance.testInlineAdditionalProperties(param); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + # **testJsonFormData** > testJsonFormData(param, param2) diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java index f5df2bb813f..267fd5c8bda 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java @@ -395,6 +395,47 @@ if (enumQueryDouble != null) apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); } + /** + * test inline additionalProperties + * + * @param param request body (required) + * @throws ApiException if fails to make API call + */ + public void testInlineAdditionalProperties(Object param) throws ApiException { + Object localVarPostBody = param; + + // verify the required parameter 'param' is set + if (param == null) { + throw new ApiException(400, "Missing the required parameter 'param' when calling testInlineAdditionalProperties"); + } + + // create path and map variables + String localVarPath = "/fake/inline-additionalProperties"; + + // query params + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } /** * test json serialization of form data * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java index 797c9aaf563..edd3fb24885 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java @@ -185,8 +185,9 @@ public class PetApi { * @param tags Tags to filter by (required) * @return List<Pet> * @throws ApiException if fails to make API call - * @Deprecated + * @deprecated */ + @Deprecated public List findPetsByTags(List tags) throws ApiException { Object localVarPostBody = null; diff --git a/samples/client/petstore/java/jersey2-java6/docs/FakeApi.md b/samples/client/petstore/java/jersey2-java6/docs/FakeApi.md index 0418b476a66..737ccc28293 100644 --- a/samples/client/petstore/java/jersey2-java6/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey2-java6/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data @@ -267,7 +268,7 @@ FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None -byte[] _byte = _byte_example; // byte[] | None +byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None @@ -376,6 +377,50 @@ No authorization required - **Content-Type**: */* - **Accept**: */* + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Object param = null; // Object | request body +try { + apiInstance.testInlineAdditionalProperties(param); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + # **testJsonFormData** > testJsonFormData(param, param2) diff --git a/samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/api/FakeApi.java index f810edcd3d1..2980f8bb1fa 100644 --- a/samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/api/FakeApi.java @@ -374,6 +374,46 @@ if (enumQueryDouble != null) apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); } + /** + * test inline additionalProperties + * + * @param param request body (required) + * @throws ApiException if fails to make API call + */ + public void testInlineAdditionalProperties(Object param) throws ApiException { + Object localVarPostBody = param; + + // verify the required parameter 'param' is set + if (param == null) { + throw new ApiException(400, "Missing the required parameter 'param' when calling testInlineAdditionalProperties"); + } + + // create path and map variables + String localVarPath = "/fake/inline-additionalProperties"; + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } /** * test json serialization of form data * diff --git a/samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/api/PetApi.java index abac5af4ad0..6af9763779c 100644 --- a/samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/api/PetApi.java @@ -168,8 +168,9 @@ public class PetApi { * @param tags Tags to filter by (required) * @return List<Pet> * @throws ApiException if fails to make API call - * @Deprecated + * @deprecated */ + @Deprecated public List findPetsByTags(List tags) throws ApiException { Object localVarPostBody = null; diff --git a/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md b/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md index 0418b476a66..737ccc28293 100644 --- a/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data @@ -267,7 +268,7 @@ FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None -byte[] _byte = _byte_example; // byte[] | None +byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None @@ -376,6 +377,50 @@ No authorization required - **Content-Type**: */* - **Accept**: */* + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Object param = null; // Object | request body +try { + apiInstance.testInlineAdditionalProperties(param); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + # **testJsonFormData** > testJsonFormData(param, param2) diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java index 086b22fe49c..250114eb256 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java @@ -374,6 +374,46 @@ if (enumQueryDouble != null) apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); } + /** + * test inline additionalProperties + * + * @param param request body (required) + * @throws ApiException if fails to make API call + */ + public void testInlineAdditionalProperties(Object param) throws ApiException { + Object localVarPostBody = param; + + // verify the required parameter 'param' is set + if (param == null) { + throw new ApiException(400, "Missing the required parameter 'param' when calling testInlineAdditionalProperties"); + } + + // create path and map variables + String localVarPath = "/fake/inline-additionalProperties"; + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } /** * test json serialization of form data * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java index abac5af4ad0..6af9763779c 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java @@ -168,8 +168,9 @@ public class PetApi { * @param tags Tags to filter by (required) * @return List<Pet> * @throws ApiException if fails to make API call - * @Deprecated + * @deprecated */ + @Deprecated public List findPetsByTags(List tags) throws ApiException { Object localVarPostBody = null; diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 7fe69e168fd..0c24badae38 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -41,7 +41,7 @@ public class AdditionalPropertiesClass { public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { if (this.mapProperty == null) { - this.mapProperty = new HashMap(); + this.mapProperty = new HashMap<>(); } this.mapProperty.put(key, mapPropertyItem); return this; @@ -67,7 +67,7 @@ public class AdditionalPropertiesClass { public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { if (this.mapOfMapProperty == null) { - this.mapOfMapProperty = new HashMap>(); + this.mapOfMapProperty = new HashMap<>(); } this.mapOfMapProperty.put(key, mapOfMapPropertyItem); return this; diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index b7e59a030a4..5997b31cbd4 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -38,7 +38,7 @@ public class ArrayOfArrayOfNumberOnly { public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { if (this.arrayArrayNumber == null) { - this.arrayArrayNumber = new ArrayList>(); + this.arrayArrayNumber = new ArrayList<>(); } this.arrayArrayNumber.add(arrayArrayNumberItem); return this; diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index fdfeb6856f3..2bc17f88eb3 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -38,7 +38,7 @@ public class ArrayOfNumberOnly { public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { if (this.arrayNumber == null) { - this.arrayNumber = new ArrayList(); + this.arrayNumber = new ArrayList<>(); } this.arrayNumber.add(arrayNumberItem); return this; diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java index 62665c2536a..6804a14e313 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java @@ -44,7 +44,7 @@ public class ArrayTest { public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { if (this.arrayOfString == null) { - this.arrayOfString = new ArrayList(); + this.arrayOfString = new ArrayList<>(); } this.arrayOfString.add(arrayOfStringItem); return this; @@ -70,7 +70,7 @@ public class ArrayTest { public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { if (this.arrayArrayOfInteger == null) { - this.arrayArrayOfInteger = new ArrayList>(); + this.arrayArrayOfInteger = new ArrayList<>(); } this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); return this; @@ -96,7 +96,7 @@ public class ArrayTest { public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { - this.arrayArrayOfModel = new ArrayList>(); + this.arrayArrayOfModel = new ArrayList<>(); } this.arrayArrayOfModel.add(arrayArrayOfModelItem); return this; diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumArrays.java index 12caa480285..133a31f10b9 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumArrays.java @@ -128,7 +128,7 @@ public class EnumArrays { public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { if (this.arrayEnum == null) { - this.arrayEnum = new ArrayList(); + this.arrayEnum = new ArrayList<>(); } this.arrayEnum.add(arrayEnumItem); return this; diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java index e6344a1df0f..31a7dae7253 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java @@ -76,7 +76,7 @@ public class MapTest { public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { if (this.mapMapOfString == null) { - this.mapMapOfString = new HashMap>(); + this.mapMapOfString = new HashMap<>(); } this.mapMapOfString.put(key, mapMapOfStringItem); return this; @@ -102,7 +102,7 @@ public class MapTest { public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { if (this.mapOfEnumString == null) { - this.mapOfEnumString = new HashMap(); + this.mapOfEnumString = new HashMap<>(); } this.mapOfEnumString.put(key, mapOfEnumStringItem); return this; diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index b0736f316e3..98c2ad2cc78 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -83,7 +83,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { if (this.map == null) { - this.map = new HashMap(); + this.map = new HashMap<>(); } this.map.put(key, mapItem); return this; diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java index 4c351dec3e4..6ece90bbfc3 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java @@ -39,7 +39,7 @@ public class Pet { private String name = null; @JsonProperty("photoUrls") - private List photoUrls = new ArrayList(); + private List photoUrls = new ArrayList<>(); @JsonProperty("tags") private List tags = null; @@ -168,7 +168,7 @@ public class Pet { public Pet addTagsItem(Tag tagsItem) { if (this.tags == null) { - this.tags = new ArrayList(); + this.tags = new ArrayList<>(); } this.tags.add(tagsItem); return this; diff --git a/samples/client/petstore/java/jersey2/docs/FakeApi.md b/samples/client/petstore/java/jersey2/docs/FakeApi.md index 0418b476a66..737ccc28293 100644 --- a/samples/client/petstore/java/jersey2/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey2/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data @@ -267,7 +268,7 @@ FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None -byte[] _byte = _byte_example; // byte[] | None +byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None @@ -376,6 +377,50 @@ No authorization required - **Content-Type**: */* - **Accept**: */* + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Object param = null; // Object | request body +try { + apiInstance.testInlineAdditionalProperties(param); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + # **testJsonFormData** > testJsonFormData(param, param2) 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 f810edcd3d1..2980f8bb1fa 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 @@ -374,6 +374,46 @@ if (enumQueryDouble != null) apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); } + /** + * test inline additionalProperties + * + * @param param request body (required) + * @throws ApiException if fails to make API call + */ + public void testInlineAdditionalProperties(Object param) throws ApiException { + Object localVarPostBody = param; + + // verify the required parameter 'param' is set + if (param == null) { + throw new ApiException(400, "Missing the required parameter 'param' when calling testInlineAdditionalProperties"); + } + + // create path and map variables + String localVarPath = "/fake/inline-additionalProperties"; + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } /** * test json serialization of form data * 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 abac5af4ad0..6af9763779c 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 @@ -168,8 +168,9 @@ public class PetApi { * @param tags Tags to filter by (required) * @return List<Pet> * @throws ApiException if fails to make API call - * @Deprecated + * @deprecated */ + @Deprecated public List findPetsByTags(List tags) throws ApiException { Object localVarPostBody = null; diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FakeApi.md index 0418b476a66..737ccc28293 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FakeApi.md +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data @@ -267,7 +268,7 @@ FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None -byte[] _byte = _byte_example; // byte[] | None +byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None @@ -376,6 +377,50 @@ No authorization required - **Content-Type**: */* - **Accept**: */* + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Object param = null; // Object | request body +try { + apiInstance.testInlineAdditionalProperties(param); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + # **testJsonFormData** > testJsonFormData(param, param2) diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/AnotherFakeApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/AnotherFakeApi.java index e11d4d1a4d0..e8abc4b61d6 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/AnotherFakeApi.java @@ -64,7 +64,7 @@ public class AnotherFakeApi { */ public com.squareup.okhttp.Call testSpecialTagsCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/another-fake/dummy"; @@ -102,7 +102,7 @@ public class AnotherFakeApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call testSpecialTagsValidateBeforeCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -111,14 +111,10 @@ public class AnotherFakeApi { throw new ApiException("Missing the required parameter 'body' when calling testSpecialTags(Async)"); } - + com.squareup.okhttp.Call call = testSpecialTagsCall(body, progressListener, progressRequestListener); return call; - - - - } /** diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/FakeApi.java index 6cf5cae059e..beb9cb1f8ff 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/FakeApi.java @@ -68,7 +68,7 @@ public class FakeApi { */ public com.squareup.okhttp.Call fakeOuterBooleanSerializeCall(Boolean body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/fake/outer/boolean"; @@ -106,18 +106,14 @@ public class FakeApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call fakeOuterBooleanSerializeValidateBeforeCall(Boolean body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - + com.squareup.okhttp.Call call = fakeOuterBooleanSerializeCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -189,7 +185,7 @@ public class FakeApi { */ public com.squareup.okhttp.Call fakeOuterCompositeSerializeCall(OuterComposite body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/fake/outer/composite"; @@ -227,18 +223,14 @@ public class FakeApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call fakeOuterCompositeSerializeValidateBeforeCall(OuterComposite body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - + com.squareup.okhttp.Call call = fakeOuterCompositeSerializeCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -310,7 +302,7 @@ public class FakeApi { */ public com.squareup.okhttp.Call fakeOuterNumberSerializeCall(BigDecimal body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/fake/outer/number"; @@ -348,18 +340,14 @@ public class FakeApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call fakeOuterNumberSerializeValidateBeforeCall(BigDecimal body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - + com.squareup.okhttp.Call call = fakeOuterNumberSerializeCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -431,7 +419,7 @@ public class FakeApi { */ public com.squareup.okhttp.Call fakeOuterStringSerializeCall(String body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/fake/outer/string"; @@ -469,18 +457,14 @@ public class FakeApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call fakeOuterStringSerializeValidateBeforeCall(String body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - + com.squareup.okhttp.Call call = fakeOuterStringSerializeCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -552,7 +536,7 @@ public class FakeApi { */ public com.squareup.okhttp.Call testClientModelCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/fake"; @@ -590,7 +574,7 @@ public class FakeApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call testClientModelValidateBeforeCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -599,14 +583,10 @@ public class FakeApi { throw new ApiException("Missing the required parameter 'body' when calling testClientModel(Async)"); } - + com.squareup.okhttp.Call call = testClientModelCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -691,7 +671,7 @@ public class FakeApi { */ public com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/fake"; @@ -757,7 +737,7 @@ public class FakeApi { String[] localVarAuthNames = new String[] { "http_basic_test" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call testEndpointParametersValidateBeforeCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -781,14 +761,10 @@ public class FakeApi { throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); } - + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, progressListener, progressRequestListener); return call; - - - - } /** @@ -902,7 +878,7 @@ public class FakeApi { */ public com.squareup.okhttp.Call testEnumParametersCall(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/fake"; @@ -956,18 +932,14 @@ public class FakeApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call testEnumParametersValidateBeforeCall(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - + com.squareup.okhttp.Call call = testEnumParametersCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); return call; - - - - } /** @@ -1046,6 +1018,124 @@ public class FakeApi { apiClient.executeAsync(call, callback); return call; } + /** + * Build call for testInlineAdditionalProperties + * @param param request body (required) + * @param progressListener Progress listener + * @param progressRequestListener Progress request listener + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + */ + public com.squareup.okhttp.Call testInlineAdditionalPropertiesCall(Object param, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = param; + + // create path and map variables + String localVarPath = "/fake/inline-additionalProperties"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json" + }; + 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, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call testInlineAdditionalPropertiesValidateBeforeCall(Object param, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'param' is set + if (param == null) { + throw new ApiException("Missing the required parameter 'param' when calling testInlineAdditionalProperties(Async)"); + } + + + com.squareup.okhttp.Call call = testInlineAdditionalPropertiesCall(param, progressListener, progressRequestListener); + return call; + + } + + /** + * test inline additionalProperties + * + * @param param request body (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testInlineAdditionalProperties(Object param) throws ApiException { + testInlineAdditionalPropertiesWithHttpInfo(param); + } + + /** + * test inline additionalProperties + * + * @param param request body (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testInlineAdditionalPropertiesWithHttpInfo(Object param) throws ApiException { + com.squareup.okhttp.Call call = testInlineAdditionalPropertiesValidateBeforeCall(param, null, null); + return apiClient.execute(call); + } + + /** + * test inline additionalProperties (asynchronously) + * + * @param param request body (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 testInlineAdditionalPropertiesAsync(Object param, 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 = testInlineAdditionalPropertiesValidateBeforeCall(param, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } /** * Build call for testJsonFormData * @param param field1 (required) @@ -1057,7 +1147,7 @@ public class FakeApi { */ public com.squareup.okhttp.Call testJsonFormDataCall(String param, String param2, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/fake/jsonFormData"; @@ -1099,7 +1189,7 @@ public class FakeApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call testJsonFormDataValidateBeforeCall(String param, String param2, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -1113,14 +1203,10 @@ public class FakeApi { throw new ApiException("Missing the required parameter 'param2' when calling testJsonFormData(Async)"); } - + com.squareup.okhttp.Call call = testJsonFormDataCall(param, param2, progressListener, progressRequestListener); return call; - - - - } /** diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/FakeClassnameTags123Api.java index da29f1c830c..cd516030e2c 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/FakeClassnameTags123Api.java @@ -64,7 +64,7 @@ public class FakeClassnameTags123Api { */ public com.squareup.okhttp.Call testClassnameCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/fake_classname_test"; @@ -102,7 +102,7 @@ public class FakeClassnameTags123Api { String[] localVarAuthNames = new String[] { "api_key_query" }; return apiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call testClassnameValidateBeforeCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -111,14 +111,10 @@ public class FakeClassnameTags123Api { throw new ApiException("Missing the required parameter 'body' when calling testClassname(Async)"); } - + com.squareup.okhttp.Call call = testClassnameCall(body, progressListener, progressRequestListener); return call; - - - - } /** diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/PetApi.java index e375ad58a34..23b9049e61b 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/PetApi.java @@ -66,7 +66,7 @@ public class PetApi { */ public com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/pet"; @@ -104,7 +104,7 @@ public class PetApi { String[] localVarAuthNames = new String[] { "petstore_auth" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call addPetValidateBeforeCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -113,14 +113,10 @@ public class PetApi { throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); } - + com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -189,7 +185,7 @@ public class PetApi { */ public com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/pet/{petId}" .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); @@ -230,7 +226,7 @@ public class PetApi { String[] localVarAuthNames = new String[] { "petstore_auth" }; return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call deletePetValidateBeforeCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -239,14 +235,10 @@ public class PetApi { throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); } - + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); return call; - - - - } /** @@ -317,7 +309,7 @@ public class PetApi { */ public com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/pet/findByStatus"; @@ -357,7 +349,7 @@ public class PetApi { String[] localVarAuthNames = new String[] { "petstore_auth" }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call findPetsByStatusValidateBeforeCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -366,14 +358,10 @@ public class PetApi { throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); } - + com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); return call; - - - - } /** @@ -442,10 +430,12 @@ public class PetApi { * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @deprecated */ + @Deprecated public com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/pet/findByTags"; @@ -485,7 +475,8 @@ public class PetApi { String[] localVarAuthNames = new String[] { "petstore_auth" }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + + @Deprecated @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call findPetsByTagsValidateBeforeCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -494,14 +485,10 @@ public class PetApi { throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); } - + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); return call; - - - - } /** @@ -510,7 +497,9 @@ public class PetApi { * @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 + * @deprecated */ + @Deprecated public List findPetsByTags(List tags) throws ApiException { ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); return resp.getData(); @@ -522,7 +511,9 @@ public class PetApi { * @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 + * @deprecated */ + @Deprecated public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { com.squareup.okhttp.Call call = findPetsByTagsValidateBeforeCall(tags, null, null); Type localVarReturnType = new TypeToken>(){}.getType(); @@ -536,7 +527,9 @@ public class PetApi { * @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 + * @deprecated */ + @Deprecated public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; @@ -573,7 +566,7 @@ public class PetApi { */ public com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/pet/{petId}" .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); @@ -612,7 +605,7 @@ public class PetApi { String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call getPetByIdValidateBeforeCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -621,14 +614,10 @@ public class PetApi { throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); } - + com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); return call; - - - - } /** @@ -700,7 +689,7 @@ public class PetApi { */ public com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/pet"; @@ -738,7 +727,7 @@ public class PetApi { String[] localVarAuthNames = new String[] { "petstore_auth" }; return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call updatePetValidateBeforeCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -747,14 +736,10 @@ public class PetApi { throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); } - + com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -824,7 +809,7 @@ public class PetApi { */ public com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/pet/{petId}" .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); @@ -867,7 +852,7 @@ public class PetApi { String[] localVarAuthNames = new String[] { "petstore_auth" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call updatePetWithFormValidateBeforeCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -876,14 +861,10 @@ public class PetApi { throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); } - + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); return call; - - - - } /** @@ -959,7 +940,7 @@ public class PetApi { */ public com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/pet/{petId}/uploadImage" .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); @@ -1002,7 +983,7 @@ public class PetApi { String[] localVarAuthNames = new String[] { "petstore_auth" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call uploadFileValidateBeforeCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -1011,14 +992,10 @@ public class PetApi { throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); } - + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); return call; - - - - } /** diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/StoreApi.java index 29d757735aa..a517a459d79 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/StoreApi.java @@ -64,7 +64,7 @@ public class StoreApi { */ public com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/store/order/{order_id}" .replaceAll("\\{" + "order_id" + "\\}", apiClient.escapeString(orderId.toString())); @@ -103,7 +103,7 @@ public class StoreApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call deleteOrderValidateBeforeCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -112,14 +112,10 @@ public class StoreApi { throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); } - + com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); return call; - - - - } /** @@ -186,7 +182,7 @@ public class StoreApi { */ public 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"; @@ -224,18 +220,14 @@ public class StoreApi { String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call getInventoryValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - + com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); return call; - - - - } /** @@ -304,7 +296,7 @@ public class StoreApi { */ public com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/store/order/{order_id}" .replaceAll("\\{" + "order_id" + "\\}", apiClient.escapeString(orderId.toString())); @@ -343,7 +335,7 @@ public class StoreApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call getOrderByIdValidateBeforeCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -352,14 +344,10 @@ public class StoreApi { throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); } - + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); return call; - - - - } /** @@ -431,7 +419,7 @@ public class StoreApi { */ public com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/store/order"; @@ -469,7 +457,7 @@ public class StoreApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call placeOrderValidateBeforeCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -478,14 +466,10 @@ public class StoreApi { throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); } - + com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); return call; - - - - } /** diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/UserApi.java index 1f38895790c..d0f16373bec 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/UserApi.java @@ -64,7 +64,7 @@ public class UserApi { */ public com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/user"; @@ -102,7 +102,7 @@ public class UserApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call createUserValidateBeforeCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -111,14 +111,10 @@ public class UserApi { throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); } - + com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -186,7 +182,7 @@ public class UserApi { */ public com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/user/createWithArray"; @@ -224,7 +220,7 @@ public class UserApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call createUsersWithArrayInputValidateBeforeCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -233,14 +229,10 @@ public class UserApi { throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); } - + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -308,7 +300,7 @@ public class UserApi { */ public com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/user/createWithList"; @@ -346,7 +338,7 @@ public class UserApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call createUsersWithListInputValidateBeforeCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -355,14 +347,10 @@ public class UserApi { throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); } - + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -430,7 +418,7 @@ public class UserApi { */ public com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/user/{username}" .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); @@ -469,7 +457,7 @@ public class UserApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call deleteUserValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -478,14 +466,10 @@ public class UserApi { throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); } - + com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); return call; - - - - } /** @@ -553,7 +537,7 @@ public class UserApi { */ public com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/user/{username}" .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); @@ -592,7 +576,7 @@ public class UserApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call getUserByNameValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -601,14 +585,10 @@ public class UserApi { throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); } - + com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); return call; - - - - } /** @@ -681,7 +661,7 @@ public class UserApi { */ public com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/user/login"; @@ -723,7 +703,7 @@ public class UserApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call loginUserValidateBeforeCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -737,14 +717,10 @@ public class UserApi { throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); } - + com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); return call; - - - - } /** @@ -818,7 +794,7 @@ public class UserApi { */ public 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"; @@ -856,18 +832,14 @@ public class UserApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call logoutUserValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - + com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); return call; - - - - } /** @@ -933,7 +905,7 @@ public class UserApi { */ public com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/user/{username}" .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); @@ -972,7 +944,7 @@ public class UserApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call updateUserValidateBeforeCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -986,14 +958,10 @@ public class UserApi { throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); } - + com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); return call; - - - - } /** diff --git a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md index 0418b476a66..737ccc28293 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data @@ -267,7 +268,7 @@ FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None -byte[] _byte = _byte_example; // byte[] | None +byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None @@ -376,6 +377,50 @@ No authorization required - **Content-Type**: */* - **Accept**: */* + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Object param = null; // Object | request body +try { + apiInstance.testInlineAdditionalProperties(param); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + # **testJsonFormData** > testJsonFormData(param, param2) 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 7b9c79c79eb..a82ca551679 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 @@ -408,7 +408,7 @@ public class ApiClient { } /** - * Set the tempoaray folder path (for downloading files) + * Set the temporary folder path (for downloading files) * * @param tempFolderPath Temporary folder path * @return ApiClient @@ -430,6 +430,7 @@ public class ApiClient { /** * Sets the connect timeout (in milliseconds). * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. * * @param connectionTimeout connection timeout in milliseconds * @return Api client @@ -439,6 +440,50 @@ public class ApiClient { return this; } + /** + * Get read timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getReadTimeout() { + return httpClient.getReadTimeout(); + } + + /** + * Sets the read timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + * + * @param readTimeout read timeout in milliseconds + * @return Api client + */ + public ApiClient setReadTimeout(int readTimeout) { + httpClient.setReadTimeout(readTimeout, TimeUnit.MILLISECONDS); + return this; + } + + /** + * Get write timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getWriteTimeout() { + return httpClient.getWriteTimeout(); + } + + /** + * Sets the write timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + * + * @param writeTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setWriteTimeout(int writeTimeout) { + httpClient.setWriteTimeout(writeTimeout, TimeUnit.MILLISECONDS); + return this; + } + /** * Format the given parameter object into string. * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/AnotherFakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/AnotherFakeApi.java index e11d4d1a4d0..e8abc4b61d6 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/AnotherFakeApi.java @@ -64,7 +64,7 @@ public class AnotherFakeApi { */ public com.squareup.okhttp.Call testSpecialTagsCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/another-fake/dummy"; @@ -102,7 +102,7 @@ public class AnotherFakeApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call testSpecialTagsValidateBeforeCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -111,14 +111,10 @@ public class AnotherFakeApi { throw new ApiException("Missing the required parameter 'body' when calling testSpecialTags(Async)"); } - + com.squareup.okhttp.Call call = testSpecialTagsCall(body, progressListener, progressRequestListener); return call; - - - - } /** 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 6cf5cae059e..beb9cb1f8ff 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 @@ -68,7 +68,7 @@ public class FakeApi { */ public com.squareup.okhttp.Call fakeOuterBooleanSerializeCall(Boolean body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/fake/outer/boolean"; @@ -106,18 +106,14 @@ public class FakeApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call fakeOuterBooleanSerializeValidateBeforeCall(Boolean body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - + com.squareup.okhttp.Call call = fakeOuterBooleanSerializeCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -189,7 +185,7 @@ public class FakeApi { */ public com.squareup.okhttp.Call fakeOuterCompositeSerializeCall(OuterComposite body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/fake/outer/composite"; @@ -227,18 +223,14 @@ public class FakeApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call fakeOuterCompositeSerializeValidateBeforeCall(OuterComposite body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - + com.squareup.okhttp.Call call = fakeOuterCompositeSerializeCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -310,7 +302,7 @@ public class FakeApi { */ public com.squareup.okhttp.Call fakeOuterNumberSerializeCall(BigDecimal body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/fake/outer/number"; @@ -348,18 +340,14 @@ public class FakeApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call fakeOuterNumberSerializeValidateBeforeCall(BigDecimal body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - + com.squareup.okhttp.Call call = fakeOuterNumberSerializeCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -431,7 +419,7 @@ public class FakeApi { */ public com.squareup.okhttp.Call fakeOuterStringSerializeCall(String body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/fake/outer/string"; @@ -469,18 +457,14 @@ public class FakeApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call fakeOuterStringSerializeValidateBeforeCall(String body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - + com.squareup.okhttp.Call call = fakeOuterStringSerializeCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -552,7 +536,7 @@ public class FakeApi { */ public com.squareup.okhttp.Call testClientModelCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/fake"; @@ -590,7 +574,7 @@ public class FakeApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call testClientModelValidateBeforeCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -599,14 +583,10 @@ public class FakeApi { throw new ApiException("Missing the required parameter 'body' when calling testClientModel(Async)"); } - + com.squareup.okhttp.Call call = testClientModelCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -691,7 +671,7 @@ public class FakeApi { */ public com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/fake"; @@ -757,7 +737,7 @@ public class FakeApi { String[] localVarAuthNames = new String[] { "http_basic_test" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call testEndpointParametersValidateBeforeCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -781,14 +761,10 @@ public class FakeApi { throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); } - + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, progressListener, progressRequestListener); return call; - - - - } /** @@ -902,7 +878,7 @@ public class FakeApi { */ public com.squareup.okhttp.Call testEnumParametersCall(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/fake"; @@ -956,18 +932,14 @@ public class FakeApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call testEnumParametersValidateBeforeCall(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - + com.squareup.okhttp.Call call = testEnumParametersCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); return call; - - - - } /** @@ -1046,6 +1018,124 @@ public class FakeApi { apiClient.executeAsync(call, callback); return call; } + /** + * Build call for testInlineAdditionalProperties + * @param param request body (required) + * @param progressListener Progress listener + * @param progressRequestListener Progress request listener + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + */ + public com.squareup.okhttp.Call testInlineAdditionalPropertiesCall(Object param, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = param; + + // create path and map variables + String localVarPath = "/fake/inline-additionalProperties"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json" + }; + 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, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call testInlineAdditionalPropertiesValidateBeforeCall(Object param, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'param' is set + if (param == null) { + throw new ApiException("Missing the required parameter 'param' when calling testInlineAdditionalProperties(Async)"); + } + + + com.squareup.okhttp.Call call = testInlineAdditionalPropertiesCall(param, progressListener, progressRequestListener); + return call; + + } + + /** + * test inline additionalProperties + * + * @param param request body (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testInlineAdditionalProperties(Object param) throws ApiException { + testInlineAdditionalPropertiesWithHttpInfo(param); + } + + /** + * test inline additionalProperties + * + * @param param request body (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testInlineAdditionalPropertiesWithHttpInfo(Object param) throws ApiException { + com.squareup.okhttp.Call call = testInlineAdditionalPropertiesValidateBeforeCall(param, null, null); + return apiClient.execute(call); + } + + /** + * test inline additionalProperties (asynchronously) + * + * @param param request body (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 testInlineAdditionalPropertiesAsync(Object param, 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 = testInlineAdditionalPropertiesValidateBeforeCall(param, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } /** * Build call for testJsonFormData * @param param field1 (required) @@ -1057,7 +1147,7 @@ public class FakeApi { */ public com.squareup.okhttp.Call testJsonFormDataCall(String param, String param2, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/fake/jsonFormData"; @@ -1099,7 +1189,7 @@ public class FakeApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call testJsonFormDataValidateBeforeCall(String param, String param2, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -1113,14 +1203,10 @@ public class FakeApi { throw new ApiException("Missing the required parameter 'param2' when calling testJsonFormData(Async)"); } - + com.squareup.okhttp.Call call = testJsonFormDataCall(param, param2, progressListener, progressRequestListener); return call; - - - - } /** diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeClassnameTags123Api.java index da29f1c830c..cd516030e2c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeClassnameTags123Api.java @@ -64,7 +64,7 @@ public class FakeClassnameTags123Api { */ public com.squareup.okhttp.Call testClassnameCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/fake_classname_test"; @@ -102,7 +102,7 @@ public class FakeClassnameTags123Api { String[] localVarAuthNames = new String[] { "api_key_query" }; return apiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call testClassnameValidateBeforeCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -111,14 +111,10 @@ public class FakeClassnameTags123Api { throw new ApiException("Missing the required parameter 'body' when calling testClassname(Async)"); } - + com.squareup.okhttp.Call call = testClassnameCall(body, progressListener, progressRequestListener); 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 e375ad58a34..23b9049e61b 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 @@ -66,7 +66,7 @@ public class PetApi { */ public com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/pet"; @@ -104,7 +104,7 @@ public class PetApi { String[] localVarAuthNames = new String[] { "petstore_auth" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call addPetValidateBeforeCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -113,14 +113,10 @@ public class PetApi { throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); } - + com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -189,7 +185,7 @@ public class PetApi { */ public com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/pet/{petId}" .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); @@ -230,7 +226,7 @@ public class PetApi { String[] localVarAuthNames = new String[] { "petstore_auth" }; return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call deletePetValidateBeforeCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -239,14 +235,10 @@ public class PetApi { throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); } - + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); return call; - - - - } /** @@ -317,7 +309,7 @@ public class PetApi { */ public com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/pet/findByStatus"; @@ -357,7 +349,7 @@ public class PetApi { String[] localVarAuthNames = new String[] { "petstore_auth" }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call findPetsByStatusValidateBeforeCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -366,14 +358,10 @@ public class PetApi { throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); } - + com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); return call; - - - - } /** @@ -442,10 +430,12 @@ public class PetApi { * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @deprecated */ + @Deprecated public com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/pet/findByTags"; @@ -485,7 +475,8 @@ public class PetApi { String[] localVarAuthNames = new String[] { "petstore_auth" }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + + @Deprecated @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call findPetsByTagsValidateBeforeCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -494,14 +485,10 @@ public class PetApi { throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); } - + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); return call; - - - - } /** @@ -510,7 +497,9 @@ public class PetApi { * @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 + * @deprecated */ + @Deprecated public List findPetsByTags(List tags) throws ApiException { ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); return resp.getData(); @@ -522,7 +511,9 @@ public class PetApi { * @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 + * @deprecated */ + @Deprecated public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { com.squareup.okhttp.Call call = findPetsByTagsValidateBeforeCall(tags, null, null); Type localVarReturnType = new TypeToken>(){}.getType(); @@ -536,7 +527,9 @@ public class PetApi { * @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 + * @deprecated */ + @Deprecated public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; @@ -573,7 +566,7 @@ public class PetApi { */ public com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/pet/{petId}" .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); @@ -612,7 +605,7 @@ public class PetApi { String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call getPetByIdValidateBeforeCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -621,14 +614,10 @@ public class PetApi { throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); } - + com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); return call; - - - - } /** @@ -700,7 +689,7 @@ public class PetApi { */ public com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/pet"; @@ -738,7 +727,7 @@ public class PetApi { String[] localVarAuthNames = new String[] { "petstore_auth" }; return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call updatePetValidateBeforeCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -747,14 +736,10 @@ public class PetApi { throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); } - + com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -824,7 +809,7 @@ public class PetApi { */ public com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/pet/{petId}" .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); @@ -867,7 +852,7 @@ public class PetApi { String[] localVarAuthNames = new String[] { "petstore_auth" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call updatePetWithFormValidateBeforeCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -876,14 +861,10 @@ public class PetApi { throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); } - + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); return call; - - - - } /** @@ -959,7 +940,7 @@ public class PetApi { */ public com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/pet/{petId}/uploadImage" .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); @@ -1002,7 +983,7 @@ public class PetApi { String[] localVarAuthNames = new String[] { "petstore_auth" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call uploadFileValidateBeforeCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -1011,14 +992,10 @@ public class PetApi { throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); } - + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); 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 29d757735aa..a517a459d79 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 @@ -64,7 +64,7 @@ public class StoreApi { */ public com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/store/order/{order_id}" .replaceAll("\\{" + "order_id" + "\\}", apiClient.escapeString(orderId.toString())); @@ -103,7 +103,7 @@ public class StoreApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call deleteOrderValidateBeforeCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -112,14 +112,10 @@ public class StoreApi { throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); } - + com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); return call; - - - - } /** @@ -186,7 +182,7 @@ public class StoreApi { */ public 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"; @@ -224,18 +220,14 @@ public class StoreApi { String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call getInventoryValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - + com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); return call; - - - - } /** @@ -304,7 +296,7 @@ public class StoreApi { */ public com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/store/order/{order_id}" .replaceAll("\\{" + "order_id" + "\\}", apiClient.escapeString(orderId.toString())); @@ -343,7 +335,7 @@ public class StoreApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call getOrderByIdValidateBeforeCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -352,14 +344,10 @@ public class StoreApi { throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); } - + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); return call; - - - - } /** @@ -431,7 +419,7 @@ public class StoreApi { */ public com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/store/order"; @@ -469,7 +457,7 @@ public class StoreApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call placeOrderValidateBeforeCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -478,14 +466,10 @@ public class StoreApi { throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); } - + com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); 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 1f38895790c..d0f16373bec 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 @@ -64,7 +64,7 @@ public class UserApi { */ public com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/user"; @@ -102,7 +102,7 @@ public class UserApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call createUserValidateBeforeCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -111,14 +111,10 @@ public class UserApi { throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); } - + com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -186,7 +182,7 @@ public class UserApi { */ public com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/user/createWithArray"; @@ -224,7 +220,7 @@ public class UserApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call createUsersWithArrayInputValidateBeforeCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -233,14 +229,10 @@ public class UserApi { throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); } - + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -308,7 +300,7 @@ public class UserApi { */ public com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/user/createWithList"; @@ -346,7 +338,7 @@ public class UserApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call createUsersWithListInputValidateBeforeCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -355,14 +347,10 @@ public class UserApi { throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); } - + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); return call; - - - - } /** @@ -430,7 +418,7 @@ public class UserApi { */ public com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/user/{username}" .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); @@ -469,7 +457,7 @@ public class UserApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call deleteUserValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -478,14 +466,10 @@ public class UserApi { throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); } - + com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); return call; - - - - } /** @@ -553,7 +537,7 @@ public class UserApi { */ public com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/user/{username}" .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); @@ -592,7 +576,7 @@ public class UserApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call getUserByNameValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -601,14 +585,10 @@ public class UserApi { throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); } - + com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); return call; - - - - } /** @@ -681,7 +661,7 @@ public class UserApi { */ public com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; - + // create path and map variables String localVarPath = "/user/login"; @@ -723,7 +703,7 @@ public class UserApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call loginUserValidateBeforeCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -737,14 +717,10 @@ public class UserApi { throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); } - + com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); return call; - - - - } /** @@ -818,7 +794,7 @@ public class UserApi { */ public 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"; @@ -856,18 +832,14 @@ public class UserApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call logoutUserValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - + com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); return call; - - - - } /** @@ -933,7 +905,7 @@ public class UserApi { */ public com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; - + // create path and map variables String localVarPath = "/user/{username}" .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); @@ -972,7 +944,7 @@ public class UserApi { String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - + @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call updateUserValidateBeforeCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { @@ -986,14 +958,10 @@ public class UserApi { throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); } - + com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); return call; - - - - } /** diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java index c103edf2f1e..e793075224b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java @@ -165,7 +165,33 @@ public class ApiClientTest { apiClient.setConnectTimeout(10000); } + + @Test + public void testGetAndSetReadTimeout() { + // read timeout defaults to 10 seconds + assertEquals(10000, apiClient.getReadTimeout()); + assertEquals(10000, apiClient.getHttpClient().getReadTimeout()); + apiClient.setReadTimeout(0); + assertEquals(0, apiClient.getReadTimeout()); + assertEquals(0, apiClient.getHttpClient().getReadTimeout()); + + apiClient.setReadTimeout(10000); + } + + @Test + public void testGetAndSetWriteTimeout() { + // write timeout defaults to 10 seconds + assertEquals(10000, apiClient.getWriteTimeout()); + assertEquals(10000, apiClient.getHttpClient().getWriteTimeout()); + + apiClient.setWriteTimeout(0); + assertEquals(0, apiClient.getWriteTimeout()); + assertEquals(0, apiClient.getHttpClient().getWriteTimeout()); + + apiClient.setWriteTimeout(10000); + } + @Test public void testParameterToPairWhenNameIsInvalid() throws Exception { List pairs_a = apiClient.parameterToPair(null, new Integer(1)); diff --git a/samples/client/petstore/java/resteasy/docs/FakeApi.md b/samples/client/petstore/java/resteasy/docs/FakeApi.md index 0418b476a66..737ccc28293 100644 --- a/samples/client/petstore/java/resteasy/docs/FakeApi.md +++ b/samples/client/petstore/java/resteasy/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data @@ -267,7 +268,7 @@ FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None -byte[] _byte = _byte_example; // byte[] | None +byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None @@ -376,6 +377,50 @@ No authorization required - **Content-Type**: */* - **Accept**: */* + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Object param = null; // Object | request body +try { + apiInstance.testInlineAdditionalProperties(param); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + # **testJsonFormData** > testJsonFormData(param, param2) diff --git a/samples/client/petstore/java/resteasy/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/resteasy/src/main/java/io/swagger/client/api/FakeApi.java index 8110632ad66..9a9757e898b 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/resteasy/src/main/java/io/swagger/client/api/FakeApi.java @@ -374,6 +374,46 @@ if (enumQueryDouble != null) apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); } + /** + * test inline additionalProperties + * + * @param param request body (required) + * @throws ApiException if fails to make API call + */ + public void testInlineAdditionalProperties(Object param) throws ApiException { + Object localVarPostBody = param; + + // verify the required parameter 'param' is set + if (param == null) { + throw new ApiException(400, "Missing the required parameter 'param' when calling testInlineAdditionalProperties"); + } + + // create path and map variables + String localVarPath = "/fake/inline-additionalProperties".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } /** * test json serialization of form data * diff --git a/samples/client/petstore/java/resteasy/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/resteasy/src/main/java/io/swagger/client/api/PetApi.java index 61eddf5eff9..d95172a9741 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/resteasy/src/main/java/io/swagger/client/api/PetApi.java @@ -168,8 +168,9 @@ public class PetApi { * @param tags Tags to filter by (required) * @return List * @throws ApiException if fails to make API call - * @Deprecated + * @deprecated */ + @Deprecated public List findPetsByTags(List tags) throws ApiException { Object localVarPostBody = null; diff --git a/samples/client/petstore/java/resttemplate-withXml/docs/FakeApi.md b/samples/client/petstore/java/resttemplate-withXml/docs/FakeApi.md index 0418b476a66..737ccc28293 100644 --- a/samples/client/petstore/java/resttemplate-withXml/docs/FakeApi.md +++ b/samples/client/petstore/java/resttemplate-withXml/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data @@ -267,7 +268,7 @@ FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None -byte[] _byte = _byte_example; // byte[] | None +byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None @@ -376,6 +377,50 @@ No authorization required - **Content-Type**: */* - **Accept**: */* + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Object param = null; // Object | request body +try { + apiInstance.testInlineAdditionalProperties(param); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + # **testJsonFormData** > testJsonFormData(param, param2) diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/io/swagger/client/api/FakeApi.java index 8393e7097f1..768e7e8fc09 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/io/swagger/client/api/FakeApi.java @@ -340,6 +340,39 @@ public class FakeApi { ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } + /** + * test inline additionalProperties + * + *

200 - successful operation + * @param param request body + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void testInlineAdditionalProperties(Object param) throws RestClientException { + Object postBody = param; + + // verify the required parameter 'param' is set + if (param == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'param' when calling testInlineAdditionalProperties"); + } + + String path = UriComponentsBuilder.fromPath("/fake/inline-additionalProperties").build().toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** * test json serialization of form data * diff --git a/samples/client/petstore/java/resttemplate/docs/FakeApi.md b/samples/client/petstore/java/resttemplate/docs/FakeApi.md index 0418b476a66..737ccc28293 100644 --- a/samples/client/petstore/java/resttemplate/docs/FakeApi.md +++ b/samples/client/petstore/java/resttemplate/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data @@ -267,7 +268,7 @@ FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None -byte[] _byte = _byte_example; // byte[] | None +byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None @@ -376,6 +377,50 @@ No authorization required - **Content-Type**: */* - **Accept**: */* + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Object param = null; // Object | request body +try { + apiInstance.testInlineAdditionalProperties(param); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + # **testJsonFormData** > testJsonFormData(param, param2) diff --git a/samples/client/petstore/java/resttemplate/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/resttemplate/src/main/java/io/swagger/client/api/FakeApi.java index 8393e7097f1..768e7e8fc09 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/io/swagger/client/api/FakeApi.java @@ -340,6 +340,39 @@ public class FakeApi { ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } + /** + * test inline additionalProperties + * + *

200 - successful operation + * @param param request body + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void testInlineAdditionalProperties(Object param) throws RestClientException { + Object postBody = param; + + // verify the required parameter 'param' is set + if (param == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'param' when calling testInlineAdditionalProperties"); + } + + String path = UriComponentsBuilder.fromPath("/fake/inline-additionalProperties").build().toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** * test json serialization of form data * 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 c0ca330ddba..07681e62c98 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 @@ -230,6 +230,30 @@ public interface FakeApi { void testEnumParameters( @retrofit.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit.http.Field("enum_form_string") String enumFormString, @retrofit.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit.http.Header("enum_header_string") String enumHeaderString, @retrofit.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit.http.Query("enum_query_string") String enumQueryString, @retrofit.http.Query("enum_query_integer") Integer enumQueryInteger, @retrofit.http.Field("enum_query_double") Double enumQueryDouble, Callback cb ); + /** + * test inline additionalProperties + * Sync method + * + * @param param request body (required) + * @return Void + */ + + @POST("/fake/inline-additionalProperties") + Void testInlineAdditionalProperties( + @retrofit.http.Body Object param + ); + + /** + * test inline additionalProperties + * Async method + * @param param request body (required) + * @param cb callback method + */ + + @POST("/fake/inline-additionalProperties") + void testInlineAdditionalProperties( + @retrofit.http.Body Object param, Callback cb + ); /** * test json serialization of form data * Sync method diff --git a/samples/client/petstore/java/retrofit2-play24/build.gradle b/samples/client/petstore/java/retrofit2-play24/build.gradle index dab54a7dba8..5ba5dc34efc 100644 --- a/samples/client/petstore/java/retrofit2-play24/build.gradle +++ b/samples/client/petstore/java/retrofit2-play24/build.gradle @@ -100,6 +100,7 @@ ext { play_version = "2.4.11" swagger_annotations_version = "1.5.15" junit_version = "4.12" + json_fire_version = "1.8.0" } dependencies { @@ -108,6 +109,7 @@ dependencies { 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 "io.gsonfire:gson-fire:$json_fire_version" compile "com.typesafe.play:play-java-ws_2.11:$play_version" compile "com.squareup.retrofit2:converter-jackson:$retrofit_version" compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" diff --git a/samples/client/petstore/java/retrofit2-play24/build.sbt b/samples/client/petstore/java/retrofit2-play24/build.sbt index e3323ddd04b..9320633cf84 100644 --- a/samples/client/petstore/java/retrofit2-play24/build.sbt +++ b/samples/client/petstore/java/retrofit2-play24/build.sbt @@ -18,6 +18,7 @@ lazy val root = (project in file(".")). "com.squareup.retrofit2" % "converter-jackson" % "2.3.0" % "compile", "io.swagger" % "swagger-annotations" % "1.5.15" % "compile", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "io.gsonfire" % "gson-fire" % "1.8.0" % "compile", "junit" % "junit" % "4.12" % "test", "com.novocode" % "junit-interface" % "0.11" % "test" ) diff --git a/samples/client/petstore/java/retrofit2-play24/docs/FakeApi.md b/samples/client/petstore/java/retrofit2-play24/docs/FakeApi.md index 1467a2943d6..3e052dea273 100644 --- a/samples/client/petstore/java/retrofit2-play24/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2-play24/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** fake/jsonFormData | test json serialization of form data @@ -267,7 +268,7 @@ FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None -byte[] _byte = _byte_example; // byte[] | None +byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None @@ -378,6 +379,51 @@ No authorization required - **Content-Type**: */* - **Accept**: */* + +# **testInlineAdditionalProperties** +> Void testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Object param = null; // Object | request body +try { + Void result = apiInstance.testInlineAdditionalProperties(param); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + # **testJsonFormData** > Void testJsonFormData(param, param2) diff --git a/samples/client/petstore/java/retrofit2-play24/pom.xml b/samples/client/petstore/java/retrofit2-play24/pom.xml index 9a72e7356fb..0156fa1d293 100644 --- a/samples/client/petstore/java/retrofit2-play24/pom.xml +++ b/samples/client/petstore/java/retrofit2-play24/pom.xml @@ -194,6 +194,11 @@ org.apache.oltu.oauth2.client ${oltu-version} + + io.gsonfire + gson-fire + ${gson-fire-version} + @@ -241,6 +246,7 @@ 1.8 ${java.version} ${java.version} + 1.8.0 1.5.15 2.6.6 2.4.11 diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/FakeApi.java index eb9240dfaef..64649d8607a 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/FakeApi.java @@ -126,6 +126,20 @@ public interface FakeApi { @retrofit2.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit2.http.Field("enum_form_string") String enumFormString, @retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit2.http.Header("enum_header_string") String enumHeaderString, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit2.http.Query("enum_query_string") String enumQueryString, @retrofit2.http.Query("enum_query_integer") Integer enumQueryInteger, @retrofit2.http.Field("enum_query_double") Double enumQueryDouble ); + /** + * test inline additionalProperties + * + * @param param request body (required) + * @return Call<Void> + */ + @Headers({ + "Content-Type:application/json" + }) + @POST("fake/inline-additionalProperties") + F.Promise> testInlineAdditionalProperties( + @retrofit2.http.Body Object param + ); + /** * test json serialization of form data * diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index e2bb686e935..f03052a0c41 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -43,7 +43,7 @@ public class AdditionalPropertiesClass { public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { if (this.mapProperty == null) { - this.mapProperty = new HashMap(); + this.mapProperty = new HashMap<>(); } this.mapProperty.put(key, mapPropertyItem); return this; @@ -69,7 +69,7 @@ public class AdditionalPropertiesClass { public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { if (this.mapOfMapProperty == null) { - this.mapOfMapProperty = new HashMap>(); + this.mapOfMapProperty = new HashMap<>(); } this.mapOfMapProperty.put(key, mapOfMapPropertyItem); return this; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 87d66e0750d..a5f6292b7b4 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -40,7 +40,7 @@ public class ArrayOfArrayOfNumberOnly { public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { if (this.arrayArrayNumber == null) { - this.arrayArrayNumber = new ArrayList>(); + this.arrayArrayNumber = new ArrayList<>(); } this.arrayArrayNumber.add(arrayArrayNumberItem); return this; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index 50e09468219..443501f0598 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -40,7 +40,7 @@ public class ArrayOfNumberOnly { public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { if (this.arrayNumber == null) { - this.arrayNumber = new ArrayList(); + this.arrayNumber = new ArrayList<>(); } this.arrayNumber.add(arrayNumberItem); return this; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayTest.java index b944839bc47..4934689e7dc 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayTest.java @@ -46,7 +46,7 @@ public class ArrayTest { public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { if (this.arrayOfString == null) { - this.arrayOfString = new ArrayList(); + this.arrayOfString = new ArrayList<>(); } this.arrayOfString.add(arrayOfStringItem); return this; @@ -72,7 +72,7 @@ public class ArrayTest { public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { if (this.arrayArrayOfInteger == null) { - this.arrayArrayOfInteger = new ArrayList>(); + this.arrayArrayOfInteger = new ArrayList<>(); } this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); return this; @@ -99,7 +99,7 @@ public class ArrayTest { public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { - this.arrayArrayOfModel = new ArrayList>(); + this.arrayArrayOfModel = new ArrayList<>(); } this.arrayArrayOfModel.add(arrayArrayOfModelItem); return this; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumArrays.java index 2019cbae634..f3cff0ea172 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumArrays.java @@ -130,7 +130,7 @@ public class EnumArrays { public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { if (this.arrayEnum == null) { - this.arrayEnum = new ArrayList(); + this.arrayEnum = new ArrayList<>(); } this.arrayEnum.add(arrayEnumItem); return this; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MapTest.java index 7c013ad8e69..1a15255161d 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MapTest.java @@ -78,7 +78,7 @@ public class MapTest { public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { if (this.mapMapOfString == null) { - this.mapMapOfString = new HashMap>(); + this.mapMapOfString = new HashMap<>(); } this.mapMapOfString.put(key, mapMapOfStringItem); return this; @@ -105,7 +105,7 @@ public class MapTest { public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { if (this.mapOfEnumString == null) { - this.mapOfEnumString = new HashMap(); + this.mapOfEnumString = new HashMap<>(); } this.mapOfEnumString.put(key, mapOfEnumStringItem); return this; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 44dba37c6aa..01184029234 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -87,7 +87,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { if (this.map == null) { - this.map = new HashMap(); + this.map = new HashMap<>(); } this.map.put(key, mapItem); return this; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Pet.java index 145360c48a9..653a9765a66 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Pet.java @@ -41,7 +41,7 @@ public class Pet { private String name = null; @JsonProperty("photoUrls") - private List photoUrls = new ArrayList(); + private List photoUrls = new ArrayList<>(); @JsonProperty("tags") private List tags = null; @@ -173,7 +173,7 @@ public class Pet { public Pet addTagsItem(Tag tagsItem) { if (this.tags == null) { - this.tags = new ArrayList(); + this.tags = new ArrayList<>(); } this.tags.add(tagsItem); return this; diff --git a/samples/client/petstore/java/retrofit2/docs/FakeApi.md b/samples/client/petstore/java/retrofit2/docs/FakeApi.md index 1467a2943d6..3e052dea273 100644 --- a/samples/client/petstore/java/retrofit2/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** fake/jsonFormData | test json serialization of form data @@ -267,7 +268,7 @@ FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None -byte[] _byte = _byte_example; // byte[] | None +byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None @@ -378,6 +379,51 @@ No authorization required - **Content-Type**: */* - **Accept**: */* + +# **testInlineAdditionalProperties** +> Void testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Object param = null; // Object | request body +try { + Void result = apiInstance.testInlineAdditionalProperties(param); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + # **testJsonFormData** > Void testJsonFormData(param, param2) 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 d169b8111b7..8842354c81f 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 @@ -122,6 +122,20 @@ public interface FakeApi { @retrofit2.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit2.http.Field("enum_form_string") String enumFormString, @retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit2.http.Header("enum_header_string") String enumHeaderString, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit2.http.Query("enum_query_string") String enumQueryString, @retrofit2.http.Query("enum_query_integer") Integer enumQueryInteger, @retrofit2.http.Field("enum_query_double") Double enumQueryDouble ); + /** + * test inline additionalProperties + * + * @param param request body (required) + * @return Call<Void> + */ + @Headers({ + "Content-Type:application/json" + }) + @POST("fake/inline-additionalProperties") + Call testInlineAdditionalProperties( + @retrofit2.http.Body Object param + ); + /** * test json serialization of form data * diff --git a/samples/client/petstore/java/retrofit2rx/build.gradle b/samples/client/petstore/java/retrofit2rx/build.gradle index fe0538acddc..efbc57f9f81 100644 --- a/samples/client/petstore/java/retrofit2rx/build.gradle +++ b/samples/client/petstore/java/retrofit2rx/build.gradle @@ -100,6 +100,7 @@ ext { junit_version = "4.12" rx_java_version = "1.3.0" threetenbp_version = "1.3.5" + json_fire_version = "1.8.0" } dependencies { @@ -110,6 +111,7 @@ dependencies { 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 "io.gsonfire:gson-fire:$json_fire_version" compile "org.threeten:threetenbp:$threetenbp_version" testCompile "junit:junit:$junit_version" diff --git a/samples/client/petstore/java/retrofit2rx/build.sbt b/samples/client/petstore/java/retrofit2rx/build.sbt index 992dd1963dc..e8748e9d2f7 100644 --- a/samples/client/petstore/java/retrofit2rx/build.sbt +++ b/samples/client/petstore/java/retrofit2rx/build.sbt @@ -17,6 +17,7 @@ lazy val root = (project in file(".")). "io.swagger" % "swagger-annotations" % "1.5.15" % "compile", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", "org.threeten" % "threetenbp" % "1.3.5" % "compile", + "io.gsonfire" % "gson-fire" % "1.8.0" % "compile", "junit" % "junit" % "4.12" % "test", "com.novocode" % "junit-interface" % "0.11" % "test" ) diff --git a/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md index 1467a2943d6..3e052dea273 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** fake/jsonFormData | test json serialization of form data @@ -267,7 +268,7 @@ FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None -byte[] _byte = _byte_example; // byte[] | None +byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None @@ -378,6 +379,51 @@ No authorization required - **Content-Type**: */* - **Accept**: */* + +# **testInlineAdditionalProperties** +> Void testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Object param = null; // Object | request body +try { + Void result = apiInstance.testInlineAdditionalProperties(param); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + # **testJsonFormData** > Void testJsonFormData(param, param2) diff --git a/samples/client/petstore/java/retrofit2rx/pom.xml b/samples/client/petstore/java/retrofit2rx/pom.xml index f78f35da747..d825abfe3ed 100644 --- a/samples/client/petstore/java/retrofit2rx/pom.xml +++ b/samples/client/petstore/java/retrofit2rx/pom.xml @@ -194,6 +194,11 @@ org.apache.oltu.oauth2.client ${oltu-version} + + io.gsonfire + gson-fire + ${gson-fire-version} + org.threeten threetenbp @@ -225,6 +230,7 @@ 1.7 ${java.version} ${java.version} + 1.8.0 1.5.15 2.3.0 1.3.0 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 dfdf92060ad..03c74e2ac20 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 @@ -2,6 +2,7 @@ package io.swagger.client; import com.google.gson.Gson; import com.google.gson.JsonParseException; +import com.google.gson.JsonElement; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.RequestBody; @@ -26,6 +27,7 @@ import java.lang.reflect.Type; import java.text.DateFormat; import java.util.LinkedHashMap; import java.util.Map; +import java.util.HashMap; public class ApiClient { diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/JSON.java index 590495331b6..aa07fc781cc 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/JSON.java @@ -20,10 +20,15 @@ import com.google.gson.TypeAdapter; import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonElement; +import io.gsonfire.GsonFireBuilder; +import io.gsonfire.TypeSelector; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import org.threeten.bp.format.DateTimeFormatter; +import io.swagger.client.model.*; + import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Type; @@ -31,6 +36,8 @@ import java.text.DateFormat; import java.text.ParseException; import java.text.ParsePosition; import java.util.Date; +import java.util.Map; +import java.util.HashMap; public class JSON { private Gson gson; @@ -39,8 +46,42 @@ public class JSON { private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); + public static GsonBuilder createGson() { + GsonFireBuilder fireBuilder = new GsonFireBuilder() + .registerTypeSelector(Animal.class, new TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new HashMap(); + classByDiscriminatorValue.put("Cat".toUpperCase(), Cat.class); + classByDiscriminatorValue.put("Dog".toUpperCase(), Dog.class); + classByDiscriminatorValue.put("Animal".toUpperCase(), Animal.class); + return getClassByDiscriminator( + classByDiscriminatorValue, + getDiscriminatorValue(readElement, "className")); + } + }) + ; + return fireBuilder.createGsonBuilder(); + } + + private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { + JsonElement element = readElement.getAsJsonObject().get(discriminatorField); + if(null == element) { + throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); + } + return element.getAsString(); + } + + private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { + Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue.toUpperCase()); + if(null == clazz) { + throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); + } + return clazz; + } + public JSON() { - gson = new GsonBuilder() + gson = createGson() .registerTypeAdapter(Date.class, dateTypeAdapter) .registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter) .registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter) 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 1104aaeced5..475de10d940 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 @@ -122,6 +122,20 @@ public interface FakeApi { @retrofit2.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit2.http.Field("enum_form_string") String enumFormString, @retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit2.http.Header("enum_header_string") String enumHeaderString, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit2.http.Query("enum_query_string") String enumQueryString, @retrofit2.http.Query("enum_query_integer") Integer enumQueryInteger, @retrofit2.http.Field("enum_query_double") Double enumQueryDouble ); + /** + * test inline additionalProperties + * + * @param param request body (required) + * @return Call<Void> + */ + @Headers({ + "Content-Type:application/json" + }) + @POST("fake/inline-additionalProperties") + Observable testInlineAdditionalProperties( + @retrofit2.http.Body Object param + ); + /** * test json serialization of form data * diff --git a/samples/client/petstore/java/retrofit2rx2/build.gradle b/samples/client/petstore/java/retrofit2rx2/build.gradle index 9c5787a93e8..22dff04b7d1 100644 --- a/samples/client/petstore/java/retrofit2rx2/build.gradle +++ b/samples/client/petstore/java/retrofit2rx2/build.gradle @@ -100,6 +100,7 @@ ext { junit_version = "4.12" rx_java_version = "2.1.1" threetenbp_version = "1.3.5" + json_fire_version = "1.8.0" } dependencies { @@ -110,6 +111,7 @@ dependencies { compile "io.reactivex.rxjava2: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 "io.gsonfire:gson-fire:$json_fire_version" compile "org.threeten:threetenbp:$threetenbp_version" testCompile "junit:junit:$junit_version" diff --git a/samples/client/petstore/java/retrofit2rx2/build.sbt b/samples/client/petstore/java/retrofit2rx2/build.sbt index 46ef2833c05..89f22bca2a0 100644 --- a/samples/client/petstore/java/retrofit2rx2/build.sbt +++ b/samples/client/petstore/java/retrofit2rx2/build.sbt @@ -17,6 +17,7 @@ lazy val root = (project in file(".")). "io.swagger" % "swagger-annotations" % "1.5.15" % "compile", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", "org.threeten" % "threetenbp" % "1.3.5" % "compile", + "io.gsonfire" % "gson-fire" % "1.8.0" % "compile", "junit" % "junit" % "4.12" % "test", "com.novocode" % "junit-interface" % "0.11" % "test" ) diff --git a/samples/client/petstore/java/retrofit2rx2/docs/FakeApi.md b/samples/client/petstore/java/retrofit2rx2/docs/FakeApi.md index 1467a2943d6..3e052dea273 100644 --- a/samples/client/petstore/java/retrofit2rx2/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2rx2/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** fake/jsonFormData | test json serialization of form data @@ -267,7 +268,7 @@ FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None -byte[] _byte = _byte_example; // byte[] | None +byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None @@ -378,6 +379,51 @@ No authorization required - **Content-Type**: */* - **Accept**: */* + +# **testInlineAdditionalProperties** +> Void testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Object param = null; // Object | request body +try { + Void result = apiInstance.testInlineAdditionalProperties(param); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + # **testJsonFormData** > Void testJsonFormData(param, param2) diff --git a/samples/client/petstore/java/retrofit2rx2/pom.xml b/samples/client/petstore/java/retrofit2rx2/pom.xml index c3750d0b9b5..b670d70167d 100644 --- a/samples/client/petstore/java/retrofit2rx2/pom.xml +++ b/samples/client/petstore/java/retrofit2rx2/pom.xml @@ -194,6 +194,11 @@ org.apache.oltu.oauth2.client ${oltu-version} + + io.gsonfire + gson-fire + ${gson-fire-version} + org.threeten threetenbp @@ -225,6 +230,7 @@ 1.7 ${java.version} ${java.version} + 1.8.0 1.5.15 2.3.0 2.1.1 diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/io/swagger/client/ApiClient.java index 9310c72d1a1..a2bddc86934 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/io/swagger/client/ApiClient.java @@ -2,6 +2,7 @@ package io.swagger.client; import com.google.gson.Gson; import com.google.gson.JsonParseException; +import com.google.gson.JsonElement; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.RequestBody; @@ -26,6 +27,7 @@ import java.lang.reflect.Type; import java.text.DateFormat; import java.util.LinkedHashMap; import java.util.Map; +import java.util.HashMap; public class ApiClient { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/io/swagger/client/JSON.java index 590495331b6..aa07fc781cc 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/io/swagger/client/JSON.java @@ -20,10 +20,15 @@ import com.google.gson.TypeAdapter; import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonElement; +import io.gsonfire.GsonFireBuilder; +import io.gsonfire.TypeSelector; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import org.threeten.bp.format.DateTimeFormatter; +import io.swagger.client.model.*; + import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Type; @@ -31,6 +36,8 @@ import java.text.DateFormat; import java.text.ParseException; import java.text.ParsePosition; import java.util.Date; +import java.util.Map; +import java.util.HashMap; public class JSON { private Gson gson; @@ -39,8 +46,42 @@ public class JSON { private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); + public static GsonBuilder createGson() { + GsonFireBuilder fireBuilder = new GsonFireBuilder() + .registerTypeSelector(Animal.class, new TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new HashMap(); + classByDiscriminatorValue.put("Cat".toUpperCase(), Cat.class); + classByDiscriminatorValue.put("Dog".toUpperCase(), Dog.class); + classByDiscriminatorValue.put("Animal".toUpperCase(), Animal.class); + return getClassByDiscriminator( + classByDiscriminatorValue, + getDiscriminatorValue(readElement, "className")); + } + }) + ; + return fireBuilder.createGsonBuilder(); + } + + private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { + JsonElement element = readElement.getAsJsonObject().get(discriminatorField); + if(null == element) { + throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); + } + return element.getAsString(); + } + + private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { + Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue.toUpperCase()); + if(null == clazz) { + throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); + } + return clazz; + } + public JSON() { - gson = new GsonBuilder() + gson = createGson() .registerTypeAdapter(Date.class, dateTypeAdapter) .registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter) .registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter) diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/io/swagger/client/api/FakeApi.java index 933e33cb88b..37673eac589 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/io/swagger/client/api/FakeApi.java @@ -122,6 +122,20 @@ public interface FakeApi { @retrofit2.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit2.http.Field("enum_form_string") String enumFormString, @retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit2.http.Header("enum_header_string") String enumHeaderString, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit2.http.Query("enum_query_string") String enumQueryString, @retrofit2.http.Query("enum_query_integer") Integer enumQueryInteger, @retrofit2.http.Field("enum_query_double") Double enumQueryDouble ); + /** + * test inline additionalProperties + * + * @param param request body (required) + * @return Call<Void> + */ + @Headers({ + "Content-Type:application/json" + }) + @POST("fake/inline-additionalProperties") + Observable testInlineAdditionalProperties( + @retrofit2.http.Body Object param + ); + /** * test json serialization of form data * diff --git a/samples/client/petstore/javascript-es6/.babelrc b/samples/client/petstore/javascript-es6/.babelrc index bcb6ee8de93..67b369ed370 100644 --- a/samples/client/petstore/javascript-es6/.babelrc +++ b/samples/client/petstore/javascript-es6/.babelrc @@ -1,3 +1,3 @@ { - "presets": ["es2015", "stage-0"] -} \ No newline at end of file + "presets": ["env", "stage-0"] +} diff --git a/samples/client/petstore/javascript-es6/README.md b/samples/client/petstore/javascript-es6/README.md index 7d74305e7ce..bbf7a369ff4 100644 --- a/samples/client/petstore/javascript-es6/README.md +++ b/samples/client/petstore/javascript-es6/README.md @@ -100,6 +100,7 @@ Class | Method | HTTP request | Description *SwaggerPetstore.FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model *SwaggerPetstore.FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *SwaggerPetstore.FakeApi* | [**testEnumParameters**](docs/FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +*SwaggerPetstore.FakeApi* | [**testInlineAdditionalProperties**](docs/FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties *SwaggerPetstore.FakeApi* | [**testJsonFormData**](docs/FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data *SwaggerPetstore.FakeClassnameTags123Api* | [**testClassname**](docs/FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case *SwaggerPetstore.PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store diff --git a/samples/client/petstore/javascript-es6/docs/FakeApi.md b/samples/client/petstore/javascript-es6/docs/FakeApi.md index 037f5a2a9b0..cafe836d687 100644 --- a/samples/client/petstore/javascript-es6/docs/FakeApi.md +++ b/samples/client/petstore/javascript-es6/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data @@ -385,6 +386,51 @@ No authorization required - **Content-Type**: */* - **Accept**: */* + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```javascript +import SwaggerPetstore from 'swagger_petstore'; + +let apiInstance = new SwaggerPetstore.FakeApi(); + +let param = null; // Object | request body + + +apiInstance.testInlineAdditionalProperties(param, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + # **testJsonFormData** > testJsonFormData(param, param2) diff --git a/samples/client/petstore/javascript-es6/package.json b/samples/client/petstore/javascript-es6/package.json index 427e6b3a506..afb99e8a97a 100644 --- a/samples/client/petstore/javascript-es6/package.json +++ b/samples/client/petstore/javascript-es6/package.json @@ -12,12 +12,12 @@ }, "dependencies": { "babel": "^6.23.0", - "babel-cli": "^6.24.1", + "babel-cli": "^6.26.0", "superagent": "3.5.2" }, "devDependencies": { - "babel-core": "6.18.0", - "babel-preset-es2015": "^6.24.1", + "babel-core": "6.26.0", + "babel-preset-env": "^1.6.1", "babel-preset-stage-0": "^6.24.1", "expect.js": "~0.3.1", "mocha": "~2.3.4", diff --git a/samples/client/petstore/javascript-es6/src/ApiClient.js b/samples/client/petstore/javascript-es6/src/ApiClient.js index a2556b62caa..11497febbe9 100644 --- a/samples/client/petstore/javascript-es6/src/ApiClient.js +++ b/samples/client/petstore/javascript-es6/src/ApiClient.js @@ -83,6 +83,12 @@ export default class ApiClient { if (typeof window === 'undefined') { this.agent = new superagent.agent(); } + + /* + * Allow user to override superagent agent + */ + this.requestAgent = null; + } /** @@ -398,6 +404,11 @@ export default class ApiClient { // set header parameters request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); + // set requestAgent if it is set by user + if (this.requestAgent) { + request.agent(this.requestAgent); + } + // set request timeout request.timeout(this.timeout); diff --git a/samples/client/petstore/javascript-es6/src/api/FakeApi.js b/samples/client/petstore/javascript-es6/src/api/FakeApi.js index 99741813c03..1a5f16e94bc 100644 --- a/samples/client/petstore/javascript-es6/src/api/FakeApi.js +++ b/samples/client/petstore/javascript-es6/src/api/FakeApi.js @@ -391,6 +391,50 @@ export default class FakeApi { ); } + /** + * Callback function to receive the result of the testInlineAdditionalProperties operation. + * @callback module:api/FakeApi~testInlineAdditionalPropertiesCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. + */ + + /** + * test inline additionalProperties + * + * @param {Object} param request body + * @param {module:api/FakeApi~testInlineAdditionalPropertiesCallback} callback The callback function, accepting three arguments: error, data, response + */ + testInlineAdditionalProperties(param, callback) { + let postBody = param; + + // verify the required parameter 'param' is set + if (param === undefined || param === null) { + throw new Error("Missing the required parameter 'param' when calling testInlineAdditionalProperties"); + } + + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['application/json']; + let accepts = []; + let returnType = null; + + return this.apiClient.callApi( + '/fake/inline-additionalProperties', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + /** * Callback function to receive the result of the testJsonFormData operation. * @callback module:api/FakeApi~testJsonFormDataCallback diff --git a/samples/client/petstore/javascript-promise-es6/.babelrc b/samples/client/petstore/javascript-promise-es6/.babelrc index bcb6ee8de93..67b369ed370 100644 --- a/samples/client/petstore/javascript-promise-es6/.babelrc +++ b/samples/client/petstore/javascript-promise-es6/.babelrc @@ -1,3 +1,3 @@ { - "presets": ["es2015", "stage-0"] -} \ No newline at end of file + "presets": ["env", "stage-0"] +} diff --git a/samples/client/petstore/javascript-promise-es6/README.md b/samples/client/petstore/javascript-promise-es6/README.md index c668dfd721f..67af003b88d 100644 --- a/samples/client/petstore/javascript-promise-es6/README.md +++ b/samples/client/petstore/javascript-promise-es6/README.md @@ -97,6 +97,7 @@ Class | Method | HTTP request | Description *SwaggerPetstore.FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model *SwaggerPetstore.FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *SwaggerPetstore.FakeApi* | [**testEnumParameters**](docs/FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +*SwaggerPetstore.FakeApi* | [**testInlineAdditionalProperties**](docs/FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties *SwaggerPetstore.FakeApi* | [**testJsonFormData**](docs/FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data *SwaggerPetstore.FakeClassnameTags123Api* | [**testClassname**](docs/FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case *SwaggerPetstore.PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store diff --git a/samples/client/petstore/javascript-promise-es6/docs/FakeApi.md b/samples/client/petstore/javascript-promise-es6/docs/FakeApi.md index 41d3591a9bb..366f5ff7bed 100644 --- a/samples/client/petstore/javascript-promise-es6/docs/FakeApi.md +++ b/samples/client/petstore/javascript-promise-es6/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data @@ -371,6 +372,49 @@ No authorization required - **Content-Type**: */* - **Accept**: */* + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```javascript +import SwaggerPetstore from 'swagger_petstore'; + +let apiInstance = new SwaggerPetstore.FakeApi(); + +let param = null; // Object | request body + +apiInstance.testInlineAdditionalProperties(param).then(() => { + console.log('API called successfully.'); +}, (error) => { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + # **testJsonFormData** > testJsonFormData(param, param2) diff --git a/samples/client/petstore/javascript-promise-es6/package.json b/samples/client/petstore/javascript-promise-es6/package.json index 427e6b3a506..afb99e8a97a 100644 --- a/samples/client/petstore/javascript-promise-es6/package.json +++ b/samples/client/petstore/javascript-promise-es6/package.json @@ -12,12 +12,12 @@ }, "dependencies": { "babel": "^6.23.0", - "babel-cli": "^6.24.1", + "babel-cli": "^6.26.0", "superagent": "3.5.2" }, "devDependencies": { - "babel-core": "6.18.0", - "babel-preset-es2015": "^6.24.1", + "babel-core": "6.26.0", + "babel-preset-env": "^1.6.1", "babel-preset-stage-0": "^6.24.1", "expect.js": "~0.3.1", "mocha": "~2.3.4", diff --git a/samples/client/petstore/javascript-promise-es6/src/ApiClient.js b/samples/client/petstore/javascript-promise-es6/src/ApiClient.js index b68c9055546..a6a1dddd8ef 100644 --- a/samples/client/petstore/javascript-promise-es6/src/ApiClient.js +++ b/samples/client/petstore/javascript-promise-es6/src/ApiClient.js @@ -83,6 +83,12 @@ export default class ApiClient { if (typeof window === 'undefined') { this.agent = new superagent.agent(); } + + /* + * Allow user to override superagent agent + */ + this.requestAgent = null; + } /** @@ -391,6 +397,11 @@ export default class ApiClient { // set header parameters request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); + // set requestAgent if it is set by user + if (this.requestAgent) { + request.agent(this.requestAgent); + } + // set request timeout request.timeout(this.timeout); diff --git a/samples/client/petstore/javascript-promise-es6/src/api/FakeApi.js b/samples/client/petstore/javascript-promise-es6/src/api/FakeApi.js index 9bcf6796fa3..0b0b8a1a816 100644 --- a/samples/client/petstore/javascript-promise-es6/src/api/FakeApi.js +++ b/samples/client/petstore/javascript-promise-es6/src/api/FakeApi.js @@ -451,6 +451,56 @@ export default class FakeApi { } + /** + * test inline additionalProperties + * + * @param {Object} param request body + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing HTTP response + */ + testInlineAdditionalPropertiesWithHttpInfo(param) { + let postBody = param; + + // verify the required parameter 'param' is set + if (param === undefined || param === null) { + throw new Error("Missing the required parameter 'param' when calling testInlineAdditionalProperties"); + } + + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['application/json']; + let accepts = []; + let returnType = null; + + return this.apiClient.callApi( + '/fake/inline-additionalProperties', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType + ); + } + + /** + * test inline additionalProperties + * + * @param {Object} param request body + * @return {Promise} a {@link https://www.promisejs.org/|Promise} + */ + testInlineAdditionalProperties(param) { + return this.testInlineAdditionalPropertiesWithHttpInfo(param) + .then(function(response_and_data) { + return response_and_data.data; + }); + } + + /** * test json serialization of form data * diff --git a/samples/client/petstore/javascript-promise/README.md b/samples/client/petstore/javascript-promise/README.md index 35942f17ef6..3dbc2e674d8 100644 --- a/samples/client/petstore/javascript-promise/README.md +++ b/samples/client/petstore/javascript-promise/README.md @@ -122,6 +122,7 @@ Class | Method | HTTP request | Description *SwaggerPetstore.FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model *SwaggerPetstore.FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *SwaggerPetstore.FakeApi* | [**testEnumParameters**](docs/FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +*SwaggerPetstore.FakeApi* | [**testInlineAdditionalProperties**](docs/FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties *SwaggerPetstore.FakeApi* | [**testJsonFormData**](docs/FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data *SwaggerPetstore.FakeClassnameTags123Api* | [**testClassname**](docs/FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case *SwaggerPetstore.PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store diff --git a/samples/client/petstore/javascript-promise/docs/FakeApi.md b/samples/client/petstore/javascript-promise/docs/FakeApi.md index 52969139d4b..8fd0dc0a6d9 100644 --- a/samples/client/petstore/javascript-promise/docs/FakeApi.md +++ b/samples/client/petstore/javascript-promise/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data @@ -371,6 +372,49 @@ No authorization required - **Content-Type**: */* - **Accept**: */* + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```javascript +var SwaggerPetstore = require('swagger_petstore'); + +var apiInstance = new SwaggerPetstore.FakeApi(); + +var param = null; // Object | request body + +apiInstance.testInlineAdditionalProperties(param).then(function() { + console.log('API called successfully.'); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + # **testJsonFormData** > testJsonFormData(param, param2) diff --git a/samples/client/petstore/javascript-promise/src/ApiClient.js b/samples/client/petstore/javascript-promise/src/ApiClient.js index 0d8ec3e5007..691f409db9e 100644 --- a/samples/client/petstore/javascript-promise/src/ApiClient.js +++ b/samples/client/petstore/javascript-promise/src/ApiClient.js @@ -98,6 +98,10 @@ this.agent = new superagent.agent(); } + /* + * Allow user to override superagent agent + */ + this.requestAgent = null; }; /** @@ -406,6 +410,12 @@ // set header parameters request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); + + // set requestAgent if it is set by user + if (this.requestAgent) { + request.agent(this.requestAgent); + } + // set request timeout request.timeout(this.timeout); diff --git a/samples/client/petstore/javascript-promise/src/api/FakeApi.js b/samples/client/petstore/javascript-promise/src/api/FakeApi.js index 0b3b9c24e2f..0f06c046e0e 100644 --- a/samples/client/petstore/javascript-promise/src/api/FakeApi.js +++ b/samples/client/petstore/javascript-promise/src/api/FakeApi.js @@ -478,6 +478,58 @@ } + /** + * test inline additionalProperties + * + * @param {Object} param request body + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing HTTP response + */ + this.testInlineAdditionalPropertiesWithHttpInfo = function(param) { + var postBody = param; + + // verify the required parameter 'param' is set + if (param === undefined || param === null) { + throw new Error("Missing the required parameter 'param' when calling testInlineAdditionalProperties"); + } + + + var pathParams = { + }; + var queryParams = { + }; + var collectionQueryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = []; + var contentTypes = ['application/json']; + var accepts = []; + var returnType = null; + + return this.apiClient.callApi( + '/fake/inline-additionalProperties', 'POST', + pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType + ); + } + + /** + * test inline additionalProperties + * + * @param {Object} param request body + * @return {Promise} a {@link https://www.promisejs.org/|Promise} + */ + this.testInlineAdditionalProperties = function(param) { + return this.testInlineAdditionalPropertiesWithHttpInfo(param) + .then(function(response_and_data) { + return response_and_data.data; + }); + } + + /** * test json serialization of form data * diff --git a/samples/client/petstore/javascript/README.md b/samples/client/petstore/javascript/README.md index 402689f894a..556caa6e87b 100644 --- a/samples/client/petstore/javascript/README.md +++ b/samples/client/petstore/javascript/README.md @@ -125,6 +125,7 @@ Class | Method | HTTP request | Description *SwaggerPetstore.FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model *SwaggerPetstore.FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *SwaggerPetstore.FakeApi* | [**testEnumParameters**](docs/FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +*SwaggerPetstore.FakeApi* | [**testInlineAdditionalProperties**](docs/FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties *SwaggerPetstore.FakeApi* | [**testJsonFormData**](docs/FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data *SwaggerPetstore.FakeClassnameTags123Api* | [**testClassname**](docs/FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case *SwaggerPetstore.PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store diff --git a/samples/client/petstore/javascript/docs/FakeApi.md b/samples/client/petstore/javascript/docs/FakeApi.md index a4e995f4333..f9b086c52d5 100644 --- a/samples/client/petstore/javascript/docs/FakeApi.md +++ b/samples/client/petstore/javascript/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data @@ -392,6 +393,52 @@ No authorization required - **Content-Type**: */* - **Accept**: */* + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties(param) + +test inline additionalProperties + + + +### Example +```javascript +var SwaggerPetstore = require('swagger_petstore'); + +var apiInstance = new SwaggerPetstore.FakeApi(); + +var param = null; // Object | request body + + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}; +apiInstance.testInlineAdditionalProperties(param, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + # **testJsonFormData** > testJsonFormData(param, param2) diff --git a/samples/client/petstore/javascript/src/ApiClient.js b/samples/client/petstore/javascript/src/ApiClient.js index 5ea52184385..246500eb3e4 100644 --- a/samples/client/petstore/javascript/src/ApiClient.js +++ b/samples/client/petstore/javascript/src/ApiClient.js @@ -98,6 +98,10 @@ this.agent = new superagent.agent(); } + /* + * Allow user to override superagent agent + */ + this.requestAgent = null; }; /** @@ -415,6 +419,12 @@ // set header parameters request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); + + // set requestAgent if it is set by user + if (this.requestAgent) { + request.agent(this.requestAgent); + } + // set request timeout request.timeout(this.timeout); diff --git a/samples/client/petstore/javascript/src/api/FakeApi.js b/samples/client/petstore/javascript/src/api/FakeApi.js index f7621dc00c9..81ac51959d8 100644 --- a/samples/client/petstore/javascript/src/api/FakeApi.js +++ b/samples/client/petstore/javascript/src/api/FakeApi.js @@ -418,6 +418,52 @@ ); } + /** + * Callback function to receive the result of the testInlineAdditionalProperties operation. + * @callback module:api/FakeApi~testInlineAdditionalPropertiesCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. + */ + + /** + * test inline additionalProperties + * + * @param {Object} param request body + * @param {module:api/FakeApi~testInlineAdditionalPropertiesCallback} callback The callback function, accepting three arguments: error, data, response + */ + this.testInlineAdditionalProperties = function(param, callback) { + var postBody = param; + + // verify the required parameter 'param' is set + if (param === undefined || param === null) { + throw new Error("Missing the required parameter 'param' when calling testInlineAdditionalProperties"); + } + + + var pathParams = { + }; + var queryParams = { + }; + var collectionQueryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = []; + var contentTypes = ['application/json']; + var accepts = []; + var returnType = null; + + return this.apiClient.callApi( + '/fake/inline-additionalProperties', 'POST', + pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + /** * Callback function to receive the result of the testJsonFormData operation. * @callback module:api/FakeApi~testJsonFormDataCallback diff --git a/samples/client/petstore/jaxrs-cxf-client/pom.xml b/samples/client/petstore/jaxrs-cxf-client/pom.xml index 0c5cec23101..e2be3c4f26b 100644 --- a/samples/client/petstore/jaxrs-cxf-client/pom.xml +++ b/samples/client/petstore/jaxrs-cxf-client/pom.xml @@ -4,6 +4,7 @@ jaxrs-cxf-petstore-client war jaxrs-cxf-petstore-client + This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. 1.0.0 src/main/java diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/PetApi.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/PetApi.java index 93a82ed4f6c..f8b8a10d288 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/PetApi.java @@ -21,10 +21,22 @@ import io.swagger.jaxrs.PATCH; import javax.validation.constraints.*; import javax.validation.Valid; +/** + * 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. + * + */ @Path("/") @Api(value = "/", description = "") public interface PetApi { + /** + * Add a new pet to the store + * + * + * + */ @POST @Path("/pet") @Consumes({ "application/json", "application/xml" }) @@ -34,6 +46,12 @@ public interface PetApi { @ApiResponse(code = 405, message = "Invalid input") }) public void addPet(@Valid Pet body); + /** + * Deletes a pet + * + * + * + */ @DELETE @Path("/pet/{petId}") @Produces({ "application/xml", "application/json" }) @@ -42,6 +60,12 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid pet value") }) public void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey); + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + */ @GET @Path("/pet/findByStatus") @Produces({ "application/xml", "application/json" }) @@ -51,6 +75,12 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid status value") }) public List findPetsByStatus(@QueryParam("status") @NotNull List status); + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + */ @GET @Path("/pet/findByTags") @Produces({ "application/xml", "application/json" }) @@ -60,6 +90,12 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid tag value") }) public List findPetsByTags(@QueryParam("tags") @NotNull List tags); + /** + * Find pet by ID + * + * Returns a single pet + * + */ @GET @Path("/pet/{petId}") @Produces({ "application/xml", "application/json" }) @@ -70,6 +106,12 @@ public interface PetApi { @ApiResponse(code = 404, message = "Pet not found") }) public Pet getPetById(@PathParam("petId") Long petId); + /** + * Update an existing pet + * + * + * + */ @PUT @Path("/pet") @Consumes({ "application/json", "application/xml" }) @@ -81,6 +123,12 @@ public interface PetApi { @ApiResponse(code = 405, message = "Validation exception") }) public void updatePet(@Valid Pet body); + /** + * Updates a pet in the store with form data + * + * + * + */ @POST @Path("/pet/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) @@ -90,6 +138,12 @@ public interface PetApi { @ApiResponse(code = 405, message = "Invalid input") }) public void updatePetWithForm(@PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status); + /** + * uploads an image + * + * + * + */ @POST @Path("/pet/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/StoreApi.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/StoreApi.java index 8ddeb8f3dea..72508ea286a 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/StoreApi.java @@ -20,10 +20,22 @@ import io.swagger.jaxrs.PATCH; import javax.validation.constraints.*; import javax.validation.Valid; +/** + * 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. + * + */ @Path("/") @Api(value = "/", description = "") public interface StoreApi { + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + */ @DELETE @Path("/store/order/{orderId}") @Produces({ "application/xml", "application/json" }) @@ -33,6 +45,12 @@ public interface StoreApi { @ApiResponse(code = 404, message = "Order not found") }) public void deleteOrder(@PathParam("orderId") String orderId); + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + */ @GET @Path("/store/inventory") @Produces({ "application/json" }) @@ -41,6 +59,12 @@ public interface StoreApi { @ApiResponse(code = 200, message = "successful operation", response = Map.class, responseContainer = "Map") }) public Map getInventory(); + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + */ @GET @Path("/store/order/{orderId}") @Produces({ "application/xml", "application/json" }) @@ -51,6 +75,12 @@ public interface StoreApi { @ApiResponse(code = 404, message = "Order not found") }) public Order getOrderById(@PathParam("orderId") @Min(1) @Max(5) Long orderId); + /** + * Place an order for a pet + * + * + * + */ @POST @Path("/store/order") @Produces({ "application/xml", "application/json" }) diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/UserApi.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/UserApi.java index 5588dddf74f..7aba6911b46 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/api/UserApi.java @@ -20,10 +20,22 @@ import io.swagger.jaxrs.PATCH; import javax.validation.constraints.*; import javax.validation.Valid; +/** + * 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. + * + */ @Path("/") @Api(value = "/", description = "") public interface UserApi { + /** + * Create user + * + * This can only be done by the logged in user. + * + */ @POST @Path("/user") @Produces({ "application/xml", "application/json" }) @@ -32,6 +44,12 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation") }) public void createUser(@Valid User body); + /** + * Creates list of users with given input array + * + * + * + */ @POST @Path("/user/createWithArray") @Produces({ "application/xml", "application/json" }) @@ -40,6 +58,12 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation") }) public void createUsersWithArrayInput(@Valid List body); + /** + * Creates list of users with given input array + * + * + * + */ @POST @Path("/user/createWithList") @Produces({ "application/xml", "application/json" }) @@ -48,6 +72,12 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation") }) public void createUsersWithListInput(@Valid List body); + /** + * Delete user + * + * This can only be done by the logged in user. + * + */ @DELETE @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) @@ -57,6 +87,12 @@ public interface UserApi { @ApiResponse(code = 404, message = "User not found") }) public void deleteUser(@PathParam("username") String username); + /** + * Get user by user name + * + * + * + */ @GET @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) @@ -67,6 +103,12 @@ public interface UserApi { @ApiResponse(code = 404, message = "User not found") }) public User getUserByName(@PathParam("username") String username); + /** + * Logs user into the system + * + * + * + */ @GET @Path("/user/login") @Produces({ "application/xml", "application/json" }) @@ -76,6 +118,12 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid username/password supplied") }) public String loginUser(@QueryParam("username") @NotNull String username, @QueryParam("password") @NotNull String password); + /** + * Logs out current logged in user session + * + * + * + */ @GET @Path("/user/logout") @Produces({ "application/xml", "application/json" }) @@ -84,6 +132,12 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation") }) public void logoutUser(); + /** + * Updated user + * + * This can only be done by the logged in user. + * + */ @PUT @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Category.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Category.java index c6076fb8df8..9a1956aae8c 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Category.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Category.java @@ -11,7 +11,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * A category for a pet + **/ @ApiModel(description="A category for a pet") public class Category { @@ -24,6 +28,7 @@ public class Category { * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -41,6 +46,7 @@ public class Category { * Get name * @return name **/ + @JsonProperty("name") public String getName() { return name; } diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/ModelApiResponse.java index 4877f3ace31..51ffbeff6da 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -11,7 +11,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * Describes the result of uploading an image resource + **/ @ApiModel(description="Describes the result of uploading an image resource") public class ModelApiResponse { @@ -26,6 +30,7 @@ public class ModelApiResponse { * Get code * @return code **/ + @JsonProperty("code") public Integer getCode() { return code; } @@ -43,6 +48,7 @@ public class ModelApiResponse { * Get type * @return type **/ + @JsonProperty("type") public String getType() { return type; } @@ -60,6 +66,7 @@ public class ModelApiResponse { * Get message * @return message **/ + @JsonProperty("message") public String getMessage() { return message; } diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Order.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Order.java index 5b4a67f50c1..dac33686761 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Order.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Order.java @@ -12,7 +12,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * An order for a pets from the pet store + **/ @ApiModel(description="An order for a pets from the pet store") public class Order { @@ -58,6 +62,9 @@ public enum StatusEnum { } @ApiModelProperty(value = "Order Status") + /** + * Order Status + **/ private StatusEnum status = null; @ApiModelProperty(value = "") private Boolean complete = false; @@ -66,6 +73,7 @@ public enum StatusEnum { * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -83,6 +91,7 @@ public enum StatusEnum { * Get petId * @return petId **/ + @JsonProperty("petId") public Long getPetId() { return petId; } @@ -100,6 +109,7 @@ public enum StatusEnum { * Get quantity * @return quantity **/ + @JsonProperty("quantity") public Integer getQuantity() { return quantity; } @@ -117,6 +127,7 @@ public enum StatusEnum { * Get shipDate * @return shipDate **/ + @JsonProperty("shipDate") public Date getShipDate() { return shipDate; } @@ -134,8 +145,12 @@ public enum StatusEnum { * Order Status * @return status **/ - public StatusEnum getStatus() { - return status; + @JsonProperty("status") + public String getStatus() { + if (status == null) { + return null; + } + return status.value(); } public void setStatus(StatusEnum status) { @@ -151,6 +166,7 @@ public enum StatusEnum { * Get complete * @return complete **/ + @JsonProperty("complete") public Boolean isComplete() { return complete; } diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Pet.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Pet.java index 15f9322a95a..3c8ab5da478 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Pet.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Pet.java @@ -15,7 +15,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * A pet for sale in the pet store + **/ @ApiModel(description="A pet for sale in the pet store") public class Pet { @@ -63,12 +67,16 @@ public enum StatusEnum { } @ApiModelProperty(value = "pet status in the store") + /** + * pet status in the store + **/ private StatusEnum status = null; /** * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -86,6 +94,7 @@ public enum StatusEnum { * Get category * @return category **/ + @JsonProperty("category") public Category getCategory() { return category; } @@ -103,6 +112,7 @@ public enum StatusEnum { * Get name * @return name **/ + @JsonProperty("name") @NotNull public String getName() { return name; @@ -121,6 +131,7 @@ public enum StatusEnum { * Get photoUrls * @return photoUrls **/ + @JsonProperty("photoUrls") @NotNull public List getPhotoUrls() { return photoUrls; @@ -144,6 +155,7 @@ public enum StatusEnum { * Get tags * @return tags **/ + @JsonProperty("tags") public List getTags() { return tags; } @@ -166,8 +178,12 @@ public enum StatusEnum { * pet status in the store * @return status **/ - public StatusEnum getStatus() { - return status; + @JsonProperty("status") + public String getStatus() { + if (status == null) { + return null; + } + return status.value(); } public void setStatus(StatusEnum status) { diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Tag.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Tag.java index a0bfd24470f..24fd1d55d2a 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Tag.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/Tag.java @@ -11,7 +11,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * A tag for a pet + **/ @ApiModel(description="A tag for a pet") public class Tag { @@ -24,6 +28,7 @@ public class Tag { * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -41,6 +46,7 @@ public class Tag { * Get name * @return name **/ + @JsonProperty("name") public String getName() { return name; } diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/User.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/User.java index 74b908a3aa3..858e8e14268 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/User.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/io/swagger/model/User.java @@ -11,7 +11,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * A User who is purchasing from the pet store + **/ @ApiModel(description="A User who is purchasing from the pet store") public class User { @@ -30,12 +34,16 @@ public class User { @ApiModelProperty(value = "") private String phone = null; @ApiModelProperty(value = "User Status") + /** + * User Status + **/ private Integer userStatus = null; /** * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -53,6 +61,7 @@ public class User { * Get username * @return username **/ + @JsonProperty("username") public String getUsername() { return username; } @@ -70,6 +79,7 @@ public class User { * Get firstName * @return firstName **/ + @JsonProperty("firstName") public String getFirstName() { return firstName; } @@ -87,6 +97,7 @@ public class User { * Get lastName * @return lastName **/ + @JsonProperty("lastName") public String getLastName() { return lastName; } @@ -104,6 +115,7 @@ public class User { * Get email * @return email **/ + @JsonProperty("email") public String getEmail() { return email; } @@ -121,6 +133,7 @@ public class User { * Get password * @return password **/ + @JsonProperty("password") public String getPassword() { return password; } @@ -138,6 +151,7 @@ public class User { * Get phone * @return phone **/ + @JsonProperty("phone") public String getPhone() { return phone; } @@ -155,6 +169,7 @@ public class User { * User Status * @return userStatus **/ + @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/ApiResponse.kt b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/ApiResponse.kt index 8b2325ac4d0..c79864c2515 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/ApiResponse.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/ApiResponse.kt @@ -25,3 +25,4 @@ data class ApiResponse ( ) { } + diff --git a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Category.kt b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Category.kt index 60c0b058dd1..f14b8010fcc 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Category.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Category.kt @@ -23,3 +23,4 @@ data class Category ( ) { } + diff --git a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Order.kt b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Order.kt index 383d5e155ea..6f96c317e95 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Order.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Order.kt @@ -31,11 +31,19 @@ data class Order ( val complete: kotlin.Boolean? = null ) { - enum class Status(val value: kotlin.String) { + /** + * Order Status + * Values: placed,approved,delivered + */ + enum class Status(val value: kotlin.Any){ + placed("placed"), + approved("approved"), + delivered("delivered"); + } - } + diff --git a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Pet.kt b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Pet.kt index 68ee9be1b4b..c507522da92 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Pet.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Pet.kt @@ -33,11 +33,19 @@ data class Pet ( val status: Pet.Status? = null ) { - enum class Status(val value: kotlin.String) { + /** + * pet status in the store + * Values: available,pending,sold + */ + enum class Status(val value: kotlin.Any){ + available("available"), + pending("pending"), + sold("sold"); + } - } + diff --git a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Tag.kt b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Tag.kt index a584da9bdf9..6686186b1a2 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Tag.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/Tag.kt @@ -23,3 +23,4 @@ data class Tag ( ) { } + diff --git a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/User.kt b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/User.kt index bf3dff18f94..527a75bad4b 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/User.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/io/swagger/client/models/User.kt @@ -36,3 +36,4 @@ data class User ( ) { } + diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index 087c3105f8d..112c5b8ab08 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -56,11 +56,15 @@ Please follow the [installation procedure](#installation--usage) and then run th testSpecialTags($body); + $result = $apiInstance->testSpecialTags($body); print_r($result); } catch (Exception $e) { echo 'Exception when calling AnotherFakeApi->testSpecialTags: ', $e->getMessage(), PHP_EOL; diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Api/AnotherFakeApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/AnotherFakeApi.md index 5b443618999..9eaff87384b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/AnotherFakeApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/AnotherFakeApi.md @@ -19,11 +19,15 @@ To test special tags testSpecialTags($body); + $result = $apiInstance->testSpecialTags($body); print_r($result); } catch (Exception $e) { echo 'Exception when calling AnotherFakeApi->testSpecialTags: ', $e->getMessage(), PHP_EOL; diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md index 845ab2f8a02..da5558c386f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md @@ -27,11 +27,15 @@ Test serialization of outer boolean types fakeOuterBooleanSerialize($body); + $result = $apiInstance->fakeOuterBooleanSerialize($body); print_r($result); } catch (Exception $e) { echo 'Exception when calling FakeApi->fakeOuterBooleanSerialize: ', $e->getMessage(), PHP_EOL; @@ -72,11 +76,15 @@ Test serialization of object with outer number type fakeOuterCompositeSerialize($body); + $result = $apiInstance->fakeOuterCompositeSerialize($body); print_r($result); } catch (Exception $e) { echo 'Exception when calling FakeApi->fakeOuterCompositeSerialize: ', $e->getMessage(), PHP_EOL; @@ -117,11 +125,15 @@ Test serialization of outer number types fakeOuterNumberSerialize($body); + $result = $apiInstance->fakeOuterNumberSerialize($body); print_r($result); } catch (Exception $e) { echo 'Exception when calling FakeApi->fakeOuterNumberSerialize: ', $e->getMessage(), PHP_EOL; @@ -162,11 +174,15 @@ Test serialization of outer string types fakeOuterStringSerialize($body); + $result = $apiInstance->fakeOuterStringSerialize($body); print_r($result); } catch (Exception $e) { echo 'Exception when calling FakeApi->fakeOuterStringSerialize: ', $e->getMessage(), PHP_EOL; @@ -207,11 +223,15 @@ To test \"client\" model testClientModel($body); + $result = $apiInstance->testClientModel($body); print_r($result); } catch (Exception $e) { echo 'Exception when calling FakeApi->testClientModel: ', $e->getMessage(), PHP_EOL; @@ -253,14 +273,21 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン require_once(__DIR__ . '/vendor/autoload.php'); // Configure HTTP basic authorization: http_basic_test -Swagger\Client\Configuration::getDefaultConfiguration()->setUsername('YOUR_USERNAME'); -Swagger\Client\Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD'); +$config = Swagger\Client\Configuration::getDefaultConfiguration() + ->setUsername('YOUR_USERNAME') + ->setPassword('YOUR_PASSWORD'); -$api_instance = new Swagger\Client\Api\FakeApi(new \Http\Adapter\Guzzle6\Client()); -$number = 3.4; // float | None + +$apiInstance = new Swagger\Client\Api\FakeApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$number = 8.14; // float | None $double = 1.2; // double | None $pattern_without_delimiter = "pattern_without_delimiter_example"; // string | None -$byte = "byte_example"; // string | None +$byte = "B"; // string | None $integer = 56; // int | None $int32 = 56; // int | None $int64 = 789; // int | None @@ -273,7 +300,7 @@ $password = "password_example"; // string | None $callback = "callback_example"; // string | None try { - $api_instance->testEndpointParameters($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback); + $apiInstance->testEndpointParameters($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback); } catch (Exception $e) { echo 'Exception when calling FakeApi->testEndpointParameters: ', $e->getMessage(), PHP_EOL; } @@ -326,7 +353,11 @@ To test enum parameters testEnumParameters($enum_form_string_array, $enum_form_string, $enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double); + $apiInstance->testEnumParameters($enum_form_string_array, $enum_form_string, $enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double); } catch (Exception $e) { echo 'Exception when calling FakeApi->testEnumParameters: ', $e->getMessage(), PHP_EOL; } @@ -384,11 +415,15 @@ test inline additionalProperties testInlineAdditionalProperties($param); + $apiInstance->testInlineAdditionalProperties($param); } catch (Exception $e) { echo 'Exception when calling FakeApi->testInlineAdditionalProperties: ', $e->getMessage(), PHP_EOL; } @@ -428,12 +463,16 @@ test json serialization of form data testJsonFormData($param, $param2); + $apiInstance->testJsonFormData($param, $param2); } catch (Exception $e) { echo 'Exception when calling FakeApi->testJsonFormData: ', $e->getMessage(), PHP_EOL; } diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeClassnameTags123Api.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeClassnameTags123Api.md index 8f826708f0c..af8699f0961 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeClassnameTags123Api.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeClassnameTags123Api.md @@ -18,15 +18,20 @@ To test class name in snake case require_once(__DIR__ . '/vendor/autoload.php'); // Configure API key authorization: api_key_query -Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('api_key_query', 'YOUR_API_KEY'); +$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('api_key_query', 'YOUR_API_KEY'); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key_query', 'Bearer'); +// $config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key_query', 'Bearer'); -$api_instance = new Swagger\Client\Api\FakeClassnameTags123Api(new \Http\Adapter\Guzzle6\Client()); +$apiInstance = new Swagger\Client\Api\FakeClassnameTags123Api( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); $body = new \Swagger\Client\Model\Client(); // \Swagger\Client\Model\Client | client model try { - $result = $api_instance->testClassname($body); + $result = $apiInstance->testClassname($body); print_r($result); } catch (Exception $e) { echo 'Exception when calling FakeClassnameTags123Api->testClassname: ', $e->getMessage(), PHP_EOL; 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 2c5edb0414e..46e42007fac 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md @@ -27,13 +27,18 @@ Add a new pet to the store require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: petstore_auth -Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); +$config = Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); -$api_instance = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client()); +$apiInstance = new Swagger\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); $body = new \Swagger\Client\Model\Pet(); // \Swagger\Client\Model\Pet | Pet object that needs to be added to the store try { - $api_instance->addPet($body); + $apiInstance->addPet($body); } catch (Exception $e) { echo 'Exception when calling PetApi->addPet: ', $e->getMessage(), PHP_EOL; } @@ -74,14 +79,19 @@ Deletes a pet require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: petstore_auth -Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); +$config = Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); -$api_instance = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client()); +$apiInstance = new Swagger\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); $pet_id = 789; // int | Pet id to delete $api_key = "api_key_example"; // string | try { - $api_instance->deletePet($pet_id, $api_key); + $apiInstance->deletePet($pet_id, $api_key); } catch (Exception $e) { echo 'Exception when calling PetApi->deletePet: ', $e->getMessage(), PHP_EOL; } @@ -123,13 +133,18 @@ Multiple status values can be provided with comma separated strings require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: petstore_auth -Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); +$config = Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); -$api_instance = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client()); +$apiInstance = new Swagger\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); $status = array("status_example"); // string[] | Status values that need to be considered for filter try { - $result = $api_instance->findPetsByStatus($status); + $result = $apiInstance->findPetsByStatus($status); print_r($result); } catch (Exception $e) { echo 'Exception when calling PetApi->findPetsByStatus: ', $e->getMessage(), PHP_EOL; @@ -171,13 +186,18 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: petstore_auth -Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); +$config = Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); -$api_instance = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client()); +$apiInstance = new Swagger\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); $tags = array("tags_example"); // string[] | Tags to filter by try { - $result = $api_instance->findPetsByTags($tags); + $result = $apiInstance->findPetsByTags($tags); print_r($result); } catch (Exception $e) { echo 'Exception when calling PetApi->findPetsByTags: ', $e->getMessage(), PHP_EOL; @@ -219,15 +239,20 @@ Returns a single pet require_once(__DIR__ . '/vendor/autoload.php'); // Configure API key authorization: api_key -Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('api_key', 'YOUR_API_KEY'); +$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('api_key', 'YOUR_API_KEY'); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); +// $config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); -$api_instance = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client()); +$apiInstance = new Swagger\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); $pet_id = 789; // int | ID of pet to return try { - $result = $api_instance->getPetById($pet_id); + $result = $apiInstance->getPetById($pet_id); print_r($result); } catch (Exception $e) { echo 'Exception when calling PetApi->getPetById: ', $e->getMessage(), PHP_EOL; @@ -269,13 +294,18 @@ Update an existing pet require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: petstore_auth -Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); +$config = Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); -$api_instance = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client()); +$apiInstance = new Swagger\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); $body = new \Swagger\Client\Model\Pet(); // \Swagger\Client\Model\Pet | Pet object that needs to be added to the store try { - $api_instance->updatePet($body); + $apiInstance->updatePet($body); } catch (Exception $e) { echo 'Exception when calling PetApi->updatePet: ', $e->getMessage(), PHP_EOL; } @@ -316,15 +346,20 @@ Updates a pet in the store with form data require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: petstore_auth -Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); +$config = Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); -$api_instance = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client()); +$apiInstance = new Swagger\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); $pet_id = 789; // int | ID of pet that needs to be updated $name = "name_example"; // string | Updated name of the pet $status = "status_example"; // string | Updated status of the pet try { - $api_instance->updatePetWithForm($pet_id, $name, $status); + $apiInstance->updatePetWithForm($pet_id, $name, $status); } catch (Exception $e) { echo 'Exception when calling PetApi->updatePetWithForm: ', $e->getMessage(), PHP_EOL; } @@ -367,15 +402,20 @@ uploads an image require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: petstore_auth -Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); +$config = Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); -$api_instance = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client()); +$apiInstance = new Swagger\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); $pet_id = 789; // int | ID of pet to update $additional_metadata = "additional_metadata_example"; // string | Additional data to pass to server $file = "/path/to/file.txt"; // \SplFileObject | file to upload try { - $result = $api_instance->uploadFile($pet_id, $additional_metadata, $file); + $result = $apiInstance->uploadFile($pet_id, $additional_metadata, $file); print_r($result); } catch (Exception $e) { echo 'Exception when calling PetApi->uploadFile: ', $e->getMessage(), PHP_EOL; 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 9daa65eba7b..87cec61aa7b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md @@ -22,11 +22,15 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non deleteOrder($order_id); + $apiInstance->deleteOrder($order_id); } catch (Exception $e) { echo 'Exception when calling StoreApi->deleteOrder: ', $e->getMessage(), PHP_EOL; } @@ -67,14 +71,19 @@ Returns a map of status codes to quantities require_once(__DIR__ . '/vendor/autoload.php'); // Configure API key authorization: api_key -Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('api_key', 'YOUR_API_KEY'); +$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('api_key', 'YOUR_API_KEY'); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); +// $config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); -$api_instance = new Swagger\Client\Api\StoreApi(new \Http\Adapter\Guzzle6\Client()); +$apiInstance = new Swagger\Client\Api\StoreApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); try { - $result = $api_instance->getInventory(); + $result = $apiInstance->getInventory(); print_r($result); } catch (Exception $e) { echo 'Exception when calling StoreApi->getInventory: ', $e->getMessage(), PHP_EOL; @@ -112,11 +121,15 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge getOrderById($order_id); + $result = $apiInstance->getOrderById($order_id); print_r($result); } catch (Exception $e) { echo 'Exception when calling StoreApi->getOrderById: ', $e->getMessage(), PHP_EOL; @@ -157,11 +170,15 @@ Place an order for a pet placeOrder($body); + $result = $apiInstance->placeOrder($body); print_r($result); } catch (Exception $e) { echo 'Exception when calling StoreApi->placeOrder: ', $e->getMessage(), PHP_EOL; 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 a1b3fdf3089..52b0a351904 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/UserApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/UserApi.md @@ -26,11 +26,15 @@ This can only be done by the logged in user. createUser($body); + $apiInstance->createUser($body); } catch (Exception $e) { echo 'Exception when calling UserApi->createUser: ', $e->getMessage(), PHP_EOL; } @@ -70,11 +74,15 @@ Creates list of users with given input array createUsersWithArrayInput($body); + $apiInstance->createUsersWithArrayInput($body); } catch (Exception $e) { echo 'Exception when calling UserApi->createUsersWithArrayInput: ', $e->getMessage(), PHP_EOL; } @@ -114,11 +122,15 @@ Creates list of users with given input array createUsersWithListInput($body); + $apiInstance->createUsersWithListInput($body); } catch (Exception $e) { echo 'Exception when calling UserApi->createUsersWithListInput: ', $e->getMessage(), PHP_EOL; } @@ -158,11 +170,15 @@ This can only be done by the logged in user. deleteUser($username); + $apiInstance->deleteUser($username); } catch (Exception $e) { echo 'Exception when calling UserApi->deleteUser: ', $e->getMessage(), PHP_EOL; } @@ -202,11 +218,15 @@ Get user by user name getUserByName($username); + $result = $apiInstance->getUserByName($username); print_r($result); } catch (Exception $e) { echo 'Exception when calling UserApi->getUserByName: ', $e->getMessage(), PHP_EOL; @@ -247,12 +267,16 @@ Logs user into the system loginUser($username, $password); + $result = $apiInstance->loginUser($username, $password); print_r($result); } catch (Exception $e) { echo 'Exception when calling UserApi->loginUser: ', $e->getMessage(), PHP_EOL; @@ -294,10 +318,14 @@ Logs out current logged in user session logoutUser(); + $apiInstance->logoutUser(); } catch (Exception $e) { echo 'Exception when calling UserApi->logoutUser: ', $e->getMessage(), PHP_EOL; } @@ -334,12 +362,16 @@ This can only be done by the logged in user. updateUser($username, $body); + $apiInstance->updateUser($username, $body); } catch (Exception $e) { echo 'Exception when calling UserApi->updateUser: ', $e->getMessage(), PHP_EOL; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/AnotherFakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/AnotherFakeApi.php index a5980f76cc2..0e50667dc0c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/AnotherFakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/AnotherFakeApi.php @@ -32,6 +32,7 @@ use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; +use GuzzleHttp\RequestOptions; use Swagger\Client\ApiException; use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; @@ -114,14 +115,15 @@ class AnotherFakeApi $request = $this->testSpecialTagsRequest($body); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -207,7 +209,7 @@ class AnotherFakeApi $request = $this->testSpecialTagsRequest($body); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); @@ -336,4 +338,22 @@ class AnotherFakeApi ); } + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 61d4e4a3095..b712667cbf3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -32,6 +32,7 @@ use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; +use GuzzleHttp\RequestOptions; use Swagger\Client\ApiException; use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; @@ -110,14 +111,15 @@ class FakeApi $request = $this->fakeOuterBooleanSerializeRequest($body); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -203,7 +205,7 @@ class FakeApi $request = $this->fakeOuterBooleanSerializeRequest($body); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); @@ -356,14 +358,15 @@ class FakeApi $request = $this->fakeOuterCompositeSerializeRequest($body); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -449,7 +452,7 @@ class FakeApi $request = $this->fakeOuterCompositeSerializeRequest($body); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); @@ -602,14 +605,15 @@ class FakeApi $request = $this->fakeOuterNumberSerializeRequest($body); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -695,7 +699,7 @@ class FakeApi $request = $this->fakeOuterNumberSerializeRequest($body); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); @@ -848,14 +852,15 @@ class FakeApi $request = $this->fakeOuterStringSerializeRequest($body); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -941,7 +946,7 @@ class FakeApi $request = $this->fakeOuterStringSerializeRequest($body); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); @@ -1098,14 +1103,15 @@ class FakeApi $request = $this->testClientModelRequest($body); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -1191,7 +1197,7 @@ class FakeApi $request = $this->testClientModelRequest($body); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); @@ -1379,14 +1385,15 @@ class FakeApi $request = $this->testEndpointParametersRequest($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -1476,7 +1483,7 @@ class FakeApi $request = $this->testEndpointParametersRequest($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; @@ -1773,14 +1780,15 @@ class FakeApi $request = $this->testEnumParametersRequest($enum_form_string_array, $enum_form_string, $enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -1858,7 +1866,7 @@ class FakeApi $request = $this->testEnumParametersRequest($enum_form_string_array, $enum_form_string, $enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; @@ -2042,14 +2050,15 @@ class FakeApi $request = $this->testInlineAdditionalPropertiesRequest($param); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -2113,7 +2122,7 @@ class FakeApi $request = $this->testInlineAdditionalPropertiesRequest($param); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; @@ -2263,14 +2272,15 @@ class FakeApi $request = $this->testJsonFormDataRequest($param, $param2); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -2336,7 +2346,7 @@ class FakeApi $request = $this->testJsonFormDataRequest($param, $param2); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; @@ -2463,4 +2473,22 @@ class FakeApi ); } + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeClassnameTags123Api.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeClassnameTags123Api.php index 3e306d423a3..2ef04d3951f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeClassnameTags123Api.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeClassnameTags123Api.php @@ -32,6 +32,7 @@ use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; +use GuzzleHttp\RequestOptions; use Swagger\Client\ApiException; use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; @@ -114,14 +115,15 @@ class FakeClassnameTags123Api $request = $this->testClassnameRequest($body); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -207,7 +209,7 @@ class FakeClassnameTags123Api $request = $this->testClassnameRequest($body); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); @@ -341,4 +343,22 @@ class FakeClassnameTags123Api ); } + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 313e0f2882d..4c7f7845d04 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -32,6 +32,7 @@ use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; +use GuzzleHttp\RequestOptions; use Swagger\Client\ApiException; use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; @@ -113,14 +114,15 @@ class PetApi $request = $this->addPetRequest($body); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -184,7 +186,7 @@ class PetApi $request = $this->addPetRequest($body); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; @@ -338,14 +340,15 @@ class PetApi $request = $this->deletePetRequest($pet_id, $api_key); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -411,7 +414,7 @@ class PetApi $request = $this->deletePetRequest($pet_id, $api_key); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; @@ -574,14 +577,15 @@ class PetApi $request = $this->findPetsByStatusRequest($status); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -667,7 +671,7 @@ class PetApi $request = $this->findPetsByStatusRequest($status); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); @@ -838,14 +842,15 @@ class PetApi $request = $this->findPetsByTagsRequest($tags); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -931,7 +936,7 @@ class PetApi $request = $this->findPetsByTagsRequest($tags); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); @@ -1102,14 +1107,15 @@ class PetApi $request = $this->getPetByIdRequest($pet_id); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -1195,7 +1201,7 @@ class PetApi $request = $this->getPetByIdRequest($pet_id); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); @@ -1367,14 +1373,15 @@ class PetApi $request = $this->updatePetRequest($body); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -1438,7 +1445,7 @@ class PetApi $request = $this->updatePetRequest($body); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; @@ -1594,14 +1601,15 @@ class PetApi $request = $this->updatePetWithFormRequest($pet_id, $name, $status); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -1669,7 +1677,7 @@ class PetApi $request = $this->updatePetWithFormRequest($pet_id, $name, $status); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; @@ -1841,14 +1849,15 @@ class PetApi $request = $this->uploadFileRequest($pet_id, $additional_metadata, $file); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -1938,7 +1947,7 @@ class PetApi $request = $this->uploadFileRequest($pet_id, $additional_metadata, $file); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); @@ -2087,4 +2096,22 @@ class PetApi ); } + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 9424f62693e..5026eecfd74 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -32,6 +32,7 @@ use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; +use GuzzleHttp\RequestOptions; use Swagger\Client\ApiException; use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; @@ -113,14 +114,15 @@ class StoreApi $request = $this->deleteOrderRequest($order_id); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -184,7 +186,7 @@ class StoreApi $request = $this->deleteOrderRequest($order_id); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; @@ -336,14 +338,15 @@ class StoreApi $request = $this->getInventoryRequest(); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -427,7 +430,7 @@ class StoreApi $request = $this->getInventoryRequest(); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); @@ -585,14 +588,15 @@ class StoreApi $request = $this->getOrderByIdRequest($order_id); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -678,7 +682,7 @@ class StoreApi $request = $this->getOrderByIdRequest($order_id); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); @@ -853,14 +857,15 @@ class StoreApi $request = $this->placeOrderRequest($body); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -946,7 +951,7 @@ class StoreApi $request = $this->placeOrderRequest($body); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); @@ -1075,4 +1080,22 @@ class StoreApi ); } + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index ce31171cef1..b9d0a3e3f28 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -32,6 +32,7 @@ use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; +use GuzzleHttp\RequestOptions; use Swagger\Client\ApiException; use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; @@ -113,14 +114,15 @@ class UserApi $request = $this->createUserRequest($body); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -184,7 +186,7 @@ class UserApi $request = $this->createUserRequest($body); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; @@ -332,14 +334,15 @@ class UserApi $request = $this->createUsersWithArrayInputRequest($body); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -403,7 +406,7 @@ class UserApi $request = $this->createUsersWithArrayInputRequest($body); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; @@ -551,14 +554,15 @@ class UserApi $request = $this->createUsersWithListInputRequest($body); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -622,7 +626,7 @@ class UserApi $request = $this->createUsersWithListInputRequest($body); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; @@ -770,14 +774,15 @@ class UserApi $request = $this->deleteUserRequest($username); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -841,7 +846,7 @@ class UserApi $request = $this->deleteUserRequest($username); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; @@ -995,14 +1000,15 @@ class UserApi $request = $this->getUserByNameRequest($username); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -1088,7 +1094,7 @@ class UserApi $request = $this->getUserByNameRequest($username); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); @@ -1258,14 +1264,15 @@ class UserApi $request = $this->loginUserRequest($username, $password); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -1353,7 +1360,7 @@ class UserApi $request = $this->loginUserRequest($username, $password); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { $responseBody = $response->getBody(); @@ -1525,14 +1532,15 @@ class UserApi $request = $this->logoutUserRequest(); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -1594,7 +1602,7 @@ class UserApi $request = $this->logoutUserRequest(); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; @@ -1734,14 +1742,15 @@ class UserApi $request = $this->updateUserRequest($username, $body); try { - + $options = $this->createHttpClientOption(); try { - $response = $this->client->send($request); + $response = $this->client->send($request, $options); } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse()->getBody()->getContents() ); } @@ -1807,7 +1816,7 @@ class UserApi $request = $this->updateUserRequest($username, $body); return $this->client - ->sendAsync($request) + ->sendAsync($request, $this->createHttpClientOption()) ->then( function ($response) use ($returnType) { return [null, $response->getStatusCode(), $response->getHeaders()]; @@ -1937,4 +1946,22 @@ class UserApi ); } + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } } diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/DebugTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/DebugTest.php new file mode 100644 index 00000000000..6eb9dacaffe --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/tests/DebugTest.php @@ -0,0 +1,26 @@ +expectOutputRegex('#GET /v2/pet/1 HTTP/1.1#'); + + $config = new Configuration(); + $config->setDebug(true); + $api = new Api\PetApi(null, $config); + $api->getPetById(1); + } + + public function testEnableDebugOutputAsync() + { + $this->expectOutputRegex('#GET /v2/pet/1 HTTP/1.1#'); + + $config = new Configuration(); + $config->setDebug(true); + $api = new Api\PetApi(null, $config); + $promise = $api->getPetByIdAsync(1); + $promise->wait(); + } +} diff --git a/samples/client/petstore/python-asyncio/README.md b/samples/client/petstore/python-asyncio/README.md index 87f80990fc5..a49d99c556c 100644 --- a/samples/client/petstore/python-asyncio/README.md +++ b/samples/client/petstore/python-asyncio/README.md @@ -77,6 +77,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model *FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**test_inline_additional_properties**](docs/FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties *FakeApi* | [**test_json_form_data**](docs/FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data *FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store diff --git a/samples/client/petstore/python-asyncio/docs/AdditionalPropertiesClass.md b/samples/client/petstore/python-asyncio/docs/AdditionalPropertiesClass.md index ea12f270f02..796a789d4c4 100644 --- a/samples/client/petstore/python-asyncio/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/python-asyncio/docs/AdditionalPropertiesClass.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **map_property** | **dict(str, str)** | | [optional] -**map_of_map_property** | [**dict(str, dict(str, str))**](dict.md) | | [optional] +**map_of_map_property** | **dict(str, dict(str, 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-asyncio/docs/AnotherFakeApi.md b/samples/client/petstore/python-asyncio/docs/AnotherFakeApi.md index b78fcf86f43..3d70f7a2875 100644 --- a/samples/client/petstore/python-asyncio/docs/AnotherFakeApi.md +++ b/samples/client/petstore/python-asyncio/docs/AnotherFakeApi.md @@ -14,7 +14,7 @@ To test special tags To test special tags -### Example +### Example ```python from __future__ import print_function import time @@ -26,7 +26,7 @@ from pprint import pprint api_instance = petstore_api.AnotherFakeApi() body = petstore_api.Client() # Client | client model -try: +try: # To test special tags api_response = api_instance.test_special_tags(body) pprint(api_response) diff --git a/samples/client/petstore/python-asyncio/docs/FakeApi.md b/samples/client/petstore/python-asyncio/docs/FakeApi.md index eb669540e53..1da84500bfe 100644 --- a/samples/client/petstore/python-asyncio/docs/FakeApi.md +++ b/samples/client/petstore/python-asyncio/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model [**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +[**test_inline_additional_properties**](FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**test_json_form_data**](FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data @@ -21,7 +22,7 @@ Method | HTTP request | Description Test serialization of outer boolean types -### Example +### Example ```python from __future__ import print_function import time @@ -33,7 +34,7 @@ from pprint import pprint api_instance = petstore_api.FakeApi() body = petstore_api.OuterBoolean() # OuterBoolean | Input boolean as post body (optional) -try: +try: api_response = api_instance.fake_outer_boolean_serialize(body=body) pprint(api_response) except ApiException as e: @@ -68,7 +69,7 @@ No authorization required Test serialization of object with outer number type -### Example +### Example ```python from __future__ import print_function import time @@ -80,7 +81,7 @@ from pprint import pprint api_instance = petstore_api.FakeApi() body = petstore_api.OuterComposite() # OuterComposite | Input composite as post body (optional) -try: +try: api_response = api_instance.fake_outer_composite_serialize(body=body) pprint(api_response) except ApiException as e: @@ -115,7 +116,7 @@ No authorization required Test serialization of outer number types -### Example +### Example ```python from __future__ import print_function import time @@ -127,7 +128,7 @@ from pprint import pprint api_instance = petstore_api.FakeApi() body = petstore_api.OuterNumber() # OuterNumber | Input number as post body (optional) -try: +try: api_response = api_instance.fake_outer_number_serialize(body=body) pprint(api_response) except ApiException as e: @@ -162,7 +163,7 @@ No authorization required Test serialization of outer string types -### Example +### Example ```python from __future__ import print_function import time @@ -174,7 +175,7 @@ from pprint import pprint api_instance = petstore_api.FakeApi() body = petstore_api.OuterString() # OuterString | Input string as post body (optional) -try: +try: api_response = api_instance.fake_outer_string_serialize(body=body) pprint(api_response) except ApiException as e: @@ -209,7 +210,7 @@ To test \"client\" model To test \"client\" model -### Example +### Example ```python from __future__ import print_function import time @@ -221,7 +222,7 @@ from pprint import pprint api_instance = petstore_api.FakeApi() body = petstore_api.Client() # Client | client model -try: +try: # To test \"client\" model api_response = api_instance.test_client_model(body) pprint(api_response) @@ -257,7 +258,7 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -### Example +### Example ```python from __future__ import print_function import time @@ -272,10 +273,10 @@ configuration.password = 'YOUR_PASSWORD' # create an instance of the API class api_instance = petstore_api.FakeApi(petstore_api.ApiClient(configuration)) -number = 3.4 # float | None +number = 8.14 # float | None double = 1.2 # float | None pattern_without_delimiter = 'pattern_without_delimiter_example' # str | None -byte = 'byte_example' # str | None +byte = 'B' # str | None integer = 56 # int | None (optional) int32 = 56 # int | None (optional) int64 = 789 # int | None (optional) @@ -287,7 +288,7 @@ date_time = '2013-10-20T19:20:30+01:00' # datetime | None (optional) password = 'password_example' # str | None (optional) param_callback = 'param_callback_example' # str | None (optional) -try: +try: # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password, param_callback=param_callback) except ApiException as e: @@ -335,7 +336,7 @@ To test enum parameters To test enum parameters -### Example +### Example ```python from __future__ import print_function import time @@ -354,7 +355,7 @@ enum_query_string = '-efg' # str | Query parameter enum test (string) (optional) enum_query_integer = 56 # int | Query parameter enum test (double) (optional) enum_query_double = 1.2 # float | Query parameter enum test (double) (optional) -try: +try: # To test enum parameters api_instance.test_enum_parameters(enum_form_string_array=enum_form_string_array, enum_form_string=enum_form_string, enum_header_string_array=enum_header_string_array, enum_header_string=enum_header_string, enum_query_string_array=enum_query_string_array, enum_query_string=enum_query_string, enum_query_integer=enum_query_integer, enum_query_double=enum_query_double) except ApiException as e: @@ -389,6 +390,53 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_inline_additional_properties** +> test_inline_additional_properties(param) + +test inline additionalProperties + + + +### Example +```python +from __future__ import print_function +import time +import petstore_api +from petstore_api.rest import ApiException +from pprint import pprint + +# create an instance of the API class +api_instance = petstore_api.FakeApi() +param = NULL # object | request body + +try: + # test inline additionalProperties + api_instance.test_inline_additional_properties(param) +except ApiException as e: + print("Exception when calling FakeApi->test_inline_additional_properties: %s\n" % e) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **object**| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_json_form_data** > test_json_form_data(param, param2) @@ -396,7 +444,7 @@ test json serialization of form data -### Example +### Example ```python from __future__ import print_function import time @@ -409,7 +457,7 @@ api_instance = petstore_api.FakeApi() param = 'param_example' # str | field1 param2 = 'param2_example' # str | field2 -try: +try: # test json serialization of form data api_instance.test_json_form_data(param, param2) except ApiException as e: diff --git a/samples/client/petstore/python-asyncio/docs/FakeClassnameTags123Api.md b/samples/client/petstore/python-asyncio/docs/FakeClassnameTags123Api.md index a103a4ee327..2546c09ca4a 100644 --- a/samples/client/petstore/python-asyncio/docs/FakeClassnameTags123Api.md +++ b/samples/client/petstore/python-asyncio/docs/FakeClassnameTags123Api.md @@ -12,7 +12,7 @@ Method | HTTP request | Description To test class name in snake case -### Example +### Example ```python from __future__ import print_function import time @@ -30,7 +30,7 @@ configuration.api_key['api_key_query'] = 'YOUR_API_KEY' api_instance = petstore_api.FakeClassnameTags123Api(petstore_api.ApiClient(configuration)) body = petstore_api.Client() # Client | client model -try: +try: # To test class name in snake case api_response = api_instance.test_classname(body) pprint(api_response) diff --git a/samples/client/petstore/python-asyncio/docs/MapTest.md b/samples/client/petstore/python-asyncio/docs/MapTest.md index 63cdab0374a..68844755d42 100644 --- a/samples/client/petstore/python-asyncio/docs/MapTest.md +++ b/samples/client/petstore/python-asyncio/docs/MapTest.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**map_map_of_string** | [**dict(str, dict(str, str))**](dict.md) | | [optional] +**map_map_of_string** | **dict(str, dict(str, str))** | | [optional] **map_of_enum_string** | **dict(str, 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-asyncio/docs/PetApi.md b/samples/client/petstore/python-asyncio/docs/PetApi.md index 74c6a5196fd..53b9158e699 100644 --- a/samples/client/petstore/python-asyncio/docs/PetApi.md +++ b/samples/client/petstore/python-asyncio/docs/PetApi.md @@ -21,7 +21,7 @@ Add a new pet to the store -### Example +### Example ```python from __future__ import print_function import time @@ -37,7 +37,7 @@ configuration.access_token = 'YOUR_ACCESS_TOKEN' api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) body = petstore_api.Pet() # Pet | Pet object that needs to be added to the store -try: +try: # Add a new pet to the store api_instance.add_pet(body) except ApiException as e: @@ -72,7 +72,7 @@ Deletes a pet -### Example +### Example ```python from __future__ import print_function import time @@ -89,7 +89,7 @@ api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) pet_id = 789 # int | Pet id to delete api_key = 'api_key_example' # str | (optional) -try: +try: # Deletes a pet api_instance.delete_pet(pet_id, api_key=api_key) except ApiException as e: @@ -125,7 +125,7 @@ Finds Pets by status Multiple status values can be provided with comma separated strings -### Example +### Example ```python from __future__ import print_function import time @@ -141,7 +141,7 @@ configuration.access_token = 'YOUR_ACCESS_TOKEN' api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) status = ['status_example'] # list[str] | Status values that need to be considered for filter -try: +try: # Finds Pets by status api_response = api_instance.find_pets_by_status(status) pprint(api_response) @@ -177,7 +177,7 @@ Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. -### Example +### Example ```python from __future__ import print_function import time @@ -193,7 +193,7 @@ configuration.access_token = 'YOUR_ACCESS_TOKEN' api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) tags = ['tags_example'] # list[str] | Tags to filter by -try: +try: # Finds Pets by tags api_response = api_instance.find_pets_by_tags(tags) pprint(api_response) @@ -229,7 +229,7 @@ Find pet by ID Returns a single pet -### Example +### Example ```python from __future__ import print_function import time @@ -247,7 +247,7 @@ configuration.api_key['api_key'] = 'YOUR_API_KEY' api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) pet_id = 789 # int | ID of pet to return -try: +try: # Find pet by ID api_response = api_instance.get_pet_by_id(pet_id) pprint(api_response) @@ -283,7 +283,7 @@ Update an existing pet -### Example +### Example ```python from __future__ import print_function import time @@ -299,7 +299,7 @@ configuration.access_token = 'YOUR_ACCESS_TOKEN' api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) body = petstore_api.Pet() # Pet | Pet object that needs to be added to the store -try: +try: # Update an existing pet api_instance.update_pet(body) except ApiException as e: @@ -334,7 +334,7 @@ Updates a pet in the store with form data -### Example +### Example ```python from __future__ import print_function import time @@ -352,7 +352,7 @@ 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) -try: +try: # Updates a pet in the store with form data api_instance.update_pet_with_form(pet_id, name=name, status=status) except ApiException as e: @@ -389,7 +389,7 @@ uploads an image -### Example +### Example ```python from __future__ import print_function import time @@ -407,7 +407,7 @@ 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) -try: +try: # uploads an image api_response = api_instance.upload_file(pet_id, additional_metadata=additional_metadata, file=file) pprint(api_response) diff --git a/samples/client/petstore/python-asyncio/docs/StoreApi.md b/samples/client/petstore/python-asyncio/docs/StoreApi.md index a75113975ef..6cbb6b45145 100644 --- a/samples/client/petstore/python-asyncio/docs/StoreApi.md +++ b/samples/client/petstore/python-asyncio/docs/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 ```python from __future__ import print_function import time @@ -29,7 +29,7 @@ from pprint import pprint api_instance = petstore_api.StoreApi() order_id = 'order_id_example' # str | ID of the order that needs to be deleted -try: +try: # Delete purchase order by ID api_instance.delete_order(order_id) except ApiException as e: @@ -64,7 +64,7 @@ Returns pet inventories by status Returns a map of status codes to quantities -### Example +### Example ```python from __future__ import print_function import time @@ -81,7 +81,7 @@ configuration.api_key['api_key'] = 'YOUR_API_KEY' # create an instance of the API class api_instance = petstore_api.StoreApi(petstore_api.ApiClient(configuration)) -try: +try: # Returns pet inventories by status api_response = api_instance.get_inventory() pprint(api_response) @@ -114,7 +114,7 @@ Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions -### Example +### Example ```python from __future__ import print_function import time @@ -126,7 +126,7 @@ from pprint import pprint api_instance = petstore_api.StoreApi() order_id = 789 # int | ID of pet that needs to be fetched -try: +try: # Find purchase order by ID api_response = api_instance.get_order_by_id(order_id) pprint(api_response) @@ -162,7 +162,7 @@ Place an order for a pet -### Example +### Example ```python from __future__ import print_function import time @@ -174,7 +174,7 @@ from pprint import pprint api_instance = petstore_api.StoreApi() body = petstore_api.Order() # Order | order placed for purchasing the pet -try: +try: # Place an order for a pet api_response = api_instance.place_order(body) pprint(api_response) diff --git a/samples/client/petstore/python-asyncio/docs/UserApi.md b/samples/client/petstore/python-asyncio/docs/UserApi.md index 5b73179dce3..969485595ae 100644 --- a/samples/client/petstore/python-asyncio/docs/UserApi.md +++ b/samples/client/petstore/python-asyncio/docs/UserApi.md @@ -21,7 +21,7 @@ Create user This can only be done by the logged in user. -### Example +### Example ```python from __future__ import print_function import time @@ -33,7 +33,7 @@ from pprint import pprint api_instance = petstore_api.UserApi() body = petstore_api.User() # User | Created user object -try: +try: # Create user api_instance.create_user(body) except ApiException as e: @@ -68,7 +68,7 @@ Creates list of users with given input array -### Example +### Example ```python from __future__ import print_function import time @@ -80,7 +80,7 @@ from pprint import pprint api_instance = petstore_api.UserApi() body = [petstore_api.User()] # list[User] | List of user object -try: +try: # Creates list of users with given input array api_instance.create_users_with_array_input(body) except ApiException as e: @@ -115,7 +115,7 @@ Creates list of users with given input array -### Example +### Example ```python from __future__ import print_function import time @@ -127,7 +127,7 @@ from pprint import pprint api_instance = petstore_api.UserApi() body = [petstore_api.User()] # list[User] | List of user object -try: +try: # Creates list of users with given input array api_instance.create_users_with_list_input(body) except ApiException as e: @@ -162,7 +162,7 @@ Delete user This can only be done by the logged in user. -### Example +### Example ```python from __future__ import print_function import time @@ -174,7 +174,7 @@ from pprint import pprint api_instance = petstore_api.UserApi() username = 'username_example' # str | The name that needs to be deleted -try: +try: # Delete user api_instance.delete_user(username) except ApiException as e: @@ -209,7 +209,7 @@ Get user by user name -### Example +### Example ```python from __future__ import print_function import time @@ -221,7 +221,7 @@ from pprint import pprint api_instance = petstore_api.UserApi() username = 'username_example' # str | The name that needs to be fetched. Use user1 for testing. -try: +try: # Get user by user name api_response = api_instance.get_user_by_name(username) pprint(api_response) @@ -257,7 +257,7 @@ Logs user into the system -### Example +### Example ```python from __future__ import print_function import time @@ -270,7 +270,7 @@ 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 -try: +try: # Logs user into the system api_response = api_instance.login_user(username, password) pprint(api_response) @@ -307,7 +307,7 @@ Logs out current logged in user session -### Example +### Example ```python from __future__ import print_function import time @@ -318,7 +318,7 @@ from pprint import pprint # create an instance of the API class api_instance = petstore_api.UserApi() -try: +try: # Logs out current logged in user session api_instance.logout_user() except ApiException as e: @@ -350,7 +350,7 @@ Updated user This can only be done by the logged in user. -### Example +### Example ```python from __future__ import print_function import time @@ -363,7 +363,7 @@ api_instance = petstore_api.UserApi() username = 'username_example' # str | name that need to be deleted body = petstore_api.User() # User | Updated user object -try: +try: # Updated user api_instance.update_user(username, body) except ApiException as e: diff --git a/samples/client/petstore/python-asyncio/petstore_api/__init__.py b/samples/client/petstore/python-asyncio/petstore_api/__init__.py index cad09e2691c..c368867dd11 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/__init__.py +++ b/samples/client/petstore/python-asyncio/petstore_api/__init__.py @@ -1,9 +1,11 @@ # coding: utf-8 +# flake8: noqa + """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,53 +15,51 @@ 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_of_array_of_number_only import ArrayOfArrayOfNumberOnly -from .models.array_of_number_only import ArrayOfNumberOnly -from .models.array_test import ArrayTest -from .models.capitalization import Capitalization -from .models.category import Category -from .models.class_model import ClassModel -from .models.client import Client -from .models.enum_arrays import EnumArrays -from .models.enum_class import EnumClass -from .models.enum_test import EnumTest -from .models.format_test import FormatTest -from .models.has_only_read_only import HasOnlyReadOnly -from .models.list import List -from .models.map_test import MapTest -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.number_only import NumberOnly -from .models.order import Order -from .models.outer_boolean import OuterBoolean -from .models.outer_composite import OuterComposite -from .models.outer_enum import OuterEnum -from .models.outer_number import OuterNumber -from .models.outer_string import OuterString -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 -from .models.cat import Cat -from .models.dog import Dog - # import apis into sdk package -from .apis.another_fake_api import AnotherFakeApi -from .apis.fake_api import FakeApi -from .apis.fake_classname_tags_123_api import FakeClassnameTags123Api -from .apis.pet_api import PetApi -from .apis.store_api import StoreApi -from .apis.user_api import UserApi +from petstore_api.api.another_fake_api import AnotherFakeApi +from petstore_api.api.fake_api import FakeApi +from petstore_api.api.fake_classname_tags_123_api import FakeClassnameTags123Api +from petstore_api.api.pet_api import PetApi +from petstore_api.api.store_api import StoreApi +from petstore_api.api.user_api import UserApi # import ApiClient -from .api_client import ApiClient - -from .configuration import Configuration +from petstore_api.api_client import ApiClient +from petstore_api.configuration import Configuration +# import models into sdk package +from petstore_api.models.additional_properties_class import AdditionalPropertiesClass +from petstore_api.models.animal import Animal +from petstore_api.models.animal_farm import AnimalFarm +from petstore_api.models.api_response import ApiResponse +from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly +from petstore_api.models.array_of_number_only import ArrayOfNumberOnly +from petstore_api.models.array_test import ArrayTest +from petstore_api.models.capitalization import Capitalization +from petstore_api.models.category import Category +from petstore_api.models.class_model import ClassModel +from petstore_api.models.client import Client +from petstore_api.models.enum_arrays import EnumArrays +from petstore_api.models.enum_class import EnumClass +from petstore_api.models.enum_test import EnumTest +from petstore_api.models.format_test import FormatTest +from petstore_api.models.has_only_read_only import HasOnlyReadOnly +from petstore_api.models.list import List +from petstore_api.models.map_test import MapTest +from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass +from petstore_api.models.model_200_response import Model200Response +from petstore_api.models.model_return import ModelReturn +from petstore_api.models.name import Name +from petstore_api.models.number_only import NumberOnly +from petstore_api.models.order import Order +from petstore_api.models.outer_boolean import OuterBoolean +from petstore_api.models.outer_composite import OuterComposite +from petstore_api.models.outer_enum import OuterEnum +from petstore_api.models.outer_number import OuterNumber +from petstore_api.models.outer_string import OuterString +from petstore_api.models.pet import Pet +from petstore_api.models.read_only_first import ReadOnlyFirst +from petstore_api.models.special_model_name import SpecialModelName +from petstore_api.models.tag import Tag +from petstore_api.models.user import User +from petstore_api.models.cat import Cat +from petstore_api.models.dog import Dog diff --git a/samples/client/petstore/python-asyncio/petstore_api/api/__init__.py b/samples/client/petstore/python-asyncio/petstore_api/api/__init__.py new file mode 100644 index 00000000000..74496adb5a2 --- /dev/null +++ b/samples/client/petstore/python-asyncio/petstore_api/api/__init__.py @@ -0,0 +1,11 @@ +from __future__ import absolute_import + +# flake8: noqa + +# import apis into api package +from petstore_api.api.another_fake_api import AnotherFakeApi +from petstore_api.api.fake_api import FakeApi +from petstore_api.api.fake_classname_tags_123_api import FakeClassnameTags123Api +from petstore_api.api.pet_api import PetApi +from petstore_api.api.store_api import StoreApi +from petstore_api.api.user_api import UserApi diff --git a/samples/client/petstore/python-tornado/petstore_api/apis/another_fake_api.py b/samples/client/petstore/python-asyncio/petstore_api/api/another_fake_api.py similarity index 59% rename from samples/client/petstore/python-tornado/petstore_api/apis/another_fake_api.py rename to samples/client/petstore/python-asyncio/petstore_api/api/another_fake_api.py index 8fb991ff3df..0096dad1a37 100644 --- a/samples/client/petstore/python-tornado/petstore_api/apis/another_fake_api.py +++ b/samples/client/petstore/python-asyncio/petstore_api/api/another_fake_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class AnotherFakeApi(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,10 +33,10 @@ class AnotherFakeApi(object): api_client = ApiClient() self.api_client = api_client - def test_special_tags(self, body, **kwargs): - """ - To test special tags - To test special tags + def test_special_tags(self, body, **kwargs): # noqa: E501 + """To test special tags # noqa: E501 + + To test special tags # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_special_tags(body, async=True) @@ -52,15 +50,15 @@ class AnotherFakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_special_tags_with_http_info(body, **kwargs) + return self.test_special_tags_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.test_special_tags_with_http_info(body, **kwargs) + (data) = self.test_special_tags_with_http_info(body, **kwargs) # noqa: E501 return data - def test_special_tags_with_http_info(self, body, **kwargs): - """ - To test special tags - To test special tags + def test_special_tags_with_http_info(self, body, **kwargs): # noqa: E501 + """To test special tags # noqa: E501 + + To test special tags # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_special_tags_with_http_info(body, async=True) @@ -73,14 +71,14 @@ class AnotherFakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -89,9 +87,9 @@ class AnotherFakeApi(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 `test_special_tags`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `test_special_tags`") # noqa: E501 collection_formats = {} @@ -108,27 +106,28 @@ class AnotherFakeApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/another-fake/dummy', 'PATCH', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Client', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/another-fake/dummy', 'PATCH', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Client', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python-asyncio/petstore_api/apis/fake_api.py b/samples/client/petstore/python-asyncio/petstore_api/api/fake_api.py similarity index 57% rename from samples/client/petstore/python-asyncio/petstore_api/apis/fake_api.py rename to samples/client/petstore/python-asyncio/petstore_api/api/fake_api.py index 46fb22f7290..4c52ee51647 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/apis/fake_api.py +++ b/samples/client/petstore/python-asyncio/petstore_api/api/fake_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class FakeApi(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,9 +33,10 @@ class FakeApi(object): api_client = ApiClient() self.api_client = api_client - def fake_outer_boolean_serialize(self, **kwargs): - """ - Test serialization of outer boolean types + def fake_outer_boolean_serialize(self, **kwargs): # noqa: E501 + """fake_outer_boolean_serialize # noqa: E501 + + Test serialization of outer boolean types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_boolean_serialize(async=True) @@ -51,14 +50,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.fake_outer_boolean_serialize_with_http_info(**kwargs) + return self.fake_outer_boolean_serialize_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.fake_outer_boolean_serialize_with_http_info(**kwargs) + (data) = self.fake_outer_boolean_serialize_with_http_info(**kwargs) # noqa: E501 return data - def fake_outer_boolean_serialize_with_http_info(self, **kwargs): - """ - Test serialization of outer boolean types + def fake_outer_boolean_serialize_with_http_info(self, **kwargs): # noqa: E501 + """fake_outer_boolean_serialize # noqa: E501 + + Test serialization of outer boolean types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_boolean_serialize_with_http_info(async=True) @@ -71,14 +71,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -87,7 +87,6 @@ class FakeApi(object): params[key] = val del params['kwargs'] - collection_formats = {} path_params = {} @@ -103,26 +102,28 @@ class FakeApi(object): if 'body' in params: body_params = params['body'] # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake/outer/boolean', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='OuterBoolean', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake/outer/boolean', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='OuterBoolean', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def fake_outer_composite_serialize(self, **kwargs): - """ - Test serialization of object with outer number type + def fake_outer_composite_serialize(self, **kwargs): # noqa: E501 + """fake_outer_composite_serialize # noqa: E501 + + Test serialization of object with outer number type # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_composite_serialize(async=True) @@ -136,14 +137,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.fake_outer_composite_serialize_with_http_info(**kwargs) + return self.fake_outer_composite_serialize_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.fake_outer_composite_serialize_with_http_info(**kwargs) + (data) = self.fake_outer_composite_serialize_with_http_info(**kwargs) # noqa: E501 return data - def fake_outer_composite_serialize_with_http_info(self, **kwargs): - """ - Test serialization of object with outer number type + def fake_outer_composite_serialize_with_http_info(self, **kwargs): # noqa: E501 + """fake_outer_composite_serialize # noqa: E501 + + Test serialization of object with outer number type # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_composite_serialize_with_http_info(async=True) @@ -156,14 +158,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -172,7 +174,6 @@ class FakeApi(object): params[key] = val del params['kwargs'] - collection_formats = {} path_params = {} @@ -188,26 +189,28 @@ class FakeApi(object): if 'body' in params: body_params = params['body'] # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake/outer/composite', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='OuterComposite', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake/outer/composite', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='OuterComposite', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def fake_outer_number_serialize(self, **kwargs): - """ - Test serialization of outer number types + def fake_outer_number_serialize(self, **kwargs): # noqa: E501 + """fake_outer_number_serialize # noqa: E501 + + Test serialization of outer number types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_number_serialize(async=True) @@ -221,14 +224,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.fake_outer_number_serialize_with_http_info(**kwargs) + return self.fake_outer_number_serialize_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.fake_outer_number_serialize_with_http_info(**kwargs) + (data) = self.fake_outer_number_serialize_with_http_info(**kwargs) # noqa: E501 return data - def fake_outer_number_serialize_with_http_info(self, **kwargs): - """ - Test serialization of outer number types + def fake_outer_number_serialize_with_http_info(self, **kwargs): # noqa: E501 + """fake_outer_number_serialize # noqa: E501 + + Test serialization of outer number types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_number_serialize_with_http_info(async=True) @@ -241,14 +245,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -257,7 +261,6 @@ class FakeApi(object): params[key] = val del params['kwargs'] - collection_formats = {} path_params = {} @@ -273,26 +276,28 @@ class FakeApi(object): if 'body' in params: body_params = params['body'] # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake/outer/number', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='OuterNumber', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake/outer/number', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='OuterNumber', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def fake_outer_string_serialize(self, **kwargs): - """ - Test serialization of outer string types + def fake_outer_string_serialize(self, **kwargs): # noqa: E501 + """fake_outer_string_serialize # noqa: E501 + + Test serialization of outer string types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_string_serialize(async=True) @@ -306,14 +311,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.fake_outer_string_serialize_with_http_info(**kwargs) + return self.fake_outer_string_serialize_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.fake_outer_string_serialize_with_http_info(**kwargs) + (data) = self.fake_outer_string_serialize_with_http_info(**kwargs) # noqa: E501 return data - def fake_outer_string_serialize_with_http_info(self, **kwargs): - """ - Test serialization of outer string types + def fake_outer_string_serialize_with_http_info(self, **kwargs): # noqa: E501 + """fake_outer_string_serialize # noqa: E501 + + Test serialization of outer string types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_string_serialize_with_http_info(async=True) @@ -326,14 +332,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -342,7 +348,6 @@ class FakeApi(object): params[key] = val del params['kwargs'] - collection_formats = {} path_params = {} @@ -358,27 +363,28 @@ class FakeApi(object): if 'body' in params: body_params = params['body'] # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake/outer/string', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='OuterString', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake/outer/string', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='OuterString', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def test_client_model(self, body, **kwargs): - """ - To test \"client\" model - To test \"client\" model + def test_client_model(self, body, **kwargs): # noqa: E501 + """To test \"client\" model # noqa: E501 + + To test \"client\" model # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_client_model(body, async=True) @@ -392,15 +398,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_client_model_with_http_info(body, **kwargs) + return self.test_client_model_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.test_client_model_with_http_info(body, **kwargs) + (data) = self.test_client_model_with_http_info(body, **kwargs) # noqa: E501 return data - def test_client_model_with_http_info(self, body, **kwargs): - """ - To test \"client\" model - To test \"client\" model + def test_client_model_with_http_info(self, body, **kwargs): # noqa: E501 + """To test \"client\" model # noqa: E501 + + To test \"client\" model # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_client_model_with_http_info(body, async=True) @@ -413,14 +419,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -429,9 +435,9 @@ class FakeApi(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 `test_client_model`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `test_client_model`") # noqa: E501 collection_formats = {} @@ -448,35 +454,36 @@ class FakeApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake', 'PATCH', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Client', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake', 'PATCH', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Client', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def test_endpoint_parameters(self, number, double, pattern_without_delimiter, byte, **kwargs): - """ - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + def test_endpoint_parameters(self, number, double, pattern_without_delimiter, byte, **kwargs): # noqa: E501 + """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 + + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, async=True) @@ -503,15 +510,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, **kwargs) + return self.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, **kwargs) # noqa: E501 else: - (data) = self.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, **kwargs) + (data) = self.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, **kwargs) # noqa: E501 return data - def test_endpoint_parameters_with_http_info(self, number, double, pattern_without_delimiter, byte, **kwargs): - """ - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + def test_endpoint_parameters_with_http_info(self, number, double, pattern_without_delimiter, byte, **kwargs): # noqa: E501 + """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 + + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, async=True) @@ -537,14 +544,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['number', 'double', 'pattern_without_delimiter', 'byte', 'integer', 'int32', 'int64', 'float', 'string', 'binary', 'date', 'date_time', 'password', 'param_callback'] + all_params = ['number', 'double', 'pattern_without_delimiter', 'byte', 'integer', 'int32', 'int64', 'float', 'string', 'binary', 'date', 'date_time', 'password', 'param_callback'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -553,45 +560,50 @@ 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`") + if ('number' not in params or + params['number'] is None): + raise ValueError("Missing the required parameter `number` when calling `test_endpoint_parameters`") # noqa: E501 # verify the required parameter 'double' is set - if ('double' not in params) or (params['double'] is None): - raise ValueError("Missing the required parameter `double` when calling `test_endpoint_parameters`") + if ('double' not in params or + params['double'] is None): + raise ValueError("Missing the required parameter `double` when calling `test_endpoint_parameters`") # noqa: E501 # verify the required parameter 'pattern_without_delimiter' is set - if ('pattern_without_delimiter' not in params) or (params['pattern_without_delimiter'] is None): - raise ValueError("Missing the required parameter `pattern_without_delimiter` when calling `test_endpoint_parameters`") + if ('pattern_without_delimiter' not in params or + params['pattern_without_delimiter'] is None): + raise ValueError("Missing the required parameter `pattern_without_delimiter` when calling `test_endpoint_parameters`") # noqa: E501 # verify the required parameter 'byte' is set - 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: - 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: - 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: - 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: - raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value greater than or equal to `67.8`") - if 'pattern_without_delimiter' in params and not re.search('^[A-Z].*', params['pattern_without_delimiter']): - raise ValueError("Invalid value for parameter `pattern_without_delimiter` when calling `test_endpoint_parameters`, must conform to the pattern `/^[A-Z].*/`") - if 'integer' in params and params['integer'] > 100: - raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100`") - if 'integer' in params and params['integer'] < 10: - raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value greater than or equal to `10`") - if 'int32' in params and params['int32'] > 200: - raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value less than or equal to `200`") - if 'int32' in params and params['int32'] < 20: - raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value greater than or equal to `20`") - 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 '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 '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: - raise ValueError("Invalid value for parameter `password` when calling `test_endpoint_parameters`, length must be greater than or equal to `10`") + if ('byte' not in params or + params['byte'] is None): + raise ValueError("Missing the required parameter `byte` when calling `test_endpoint_parameters`") # noqa: E501 + if 'number' in params and params['number'] > 543.2: # noqa: E501 + raise ValueError("Invalid value for parameter `number` when calling `test_endpoint_parameters`, must be a value less than or equal to `543.2`") # noqa: E501 + if 'number' in params and params['number'] < 32.1: # noqa: E501 + raise ValueError("Invalid value for parameter `number` when calling `test_endpoint_parameters`, must be a value greater than or equal to `32.1`") # noqa: E501 + if 'double' in params and params['double'] > 123.4: # noqa: E501 + raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value less than or equal to `123.4`") # noqa: E501 + if 'double' in params and params['double'] < 67.8: # noqa: E501 + raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value greater than or equal to `67.8`") # noqa: E501 + if 'pattern_without_delimiter' in params and not re.search('^[A-Z].*', params['pattern_without_delimiter']): # noqa: E501 + raise ValueError("Invalid value for parameter `pattern_without_delimiter` when calling `test_endpoint_parameters`, must conform to the pattern `/^[A-Z].*/`") # noqa: E501 + if 'integer' in params and params['integer'] > 100: # noqa: E501 + raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100`") # noqa: E501 + if 'integer' in params and params['integer'] < 10: # noqa: E501 + raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value greater than or equal to `10`") # noqa: E501 + if 'int32' in params and params['int32'] > 200: # noqa: E501 + raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value less than or equal to `200`") # noqa: E501 + if 'int32' in params and params['int32'] < 20: # noqa: E501 + raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value greater than or equal to `20`") # noqa: E501 + if 'float' in params and params['float'] > 987.6: # noqa: E501 + raise ValueError("Invalid value for parameter `float` when calling `test_endpoint_parameters`, must be a value less than or equal to `987.6`") # noqa: E501 + if 'string' in params and not re.search('[a-z]', params['string'], flags=re.IGNORECASE): # noqa: E501 + raise ValueError("Invalid value for parameter `string` when calling `test_endpoint_parameters`, must conform to the pattern `/[a-z]/i`") # noqa: E501 + 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`") # noqa: E501 + 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`") # noqa: E501 collection_formats = {} path_params = {} @@ -603,65 +615,66 @@ class FakeApi(object): form_params = [] local_var_files = {} if 'integer' in params: - form_params.append(('integer', params['integer'])) + form_params.append(('integer', params['integer'])) # noqa: E501 if 'int32' in params: - form_params.append(('int32', params['int32'])) + form_params.append(('int32', params['int32'])) # noqa: E501 if 'int64' in params: - form_params.append(('int64', params['int64'])) + form_params.append(('int64', params['int64'])) # noqa: E501 if 'number' in params: - form_params.append(('number', params['number'])) + form_params.append(('number', params['number'])) # noqa: E501 if 'float' in params: - form_params.append(('float', params['float'])) + form_params.append(('float', params['float'])) # noqa: E501 if 'double' in params: - form_params.append(('double', params['double'])) + form_params.append(('double', params['double'])) # noqa: E501 if 'string' in params: - form_params.append(('string', params['string'])) + form_params.append(('string', params['string'])) # noqa: E501 if 'pattern_without_delimiter' in params: - form_params.append(('pattern_without_delimiter', params['pattern_without_delimiter'])) + form_params.append(('pattern_without_delimiter', params['pattern_without_delimiter'])) # noqa: E501 if 'byte' in params: - form_params.append(('byte', params['byte'])) + form_params.append(('byte', params['byte'])) # noqa: E501 if 'binary' in params: - form_params.append(('binary', params['binary'])) + form_params.append(('binary', params['binary'])) # noqa: E501 if 'date' in params: - form_params.append(('date', params['date'])) + form_params.append(('date', params['date'])) # noqa: E501 if 'date_time' in params: - form_params.append(('dateTime', params['date_time'])) + form_params.append(('dateTime', params['date_time'])) # noqa: E501 if 'password' in params: - form_params.append(('password', params['password'])) + form_params.append(('password', params['password'])) # noqa: E501 if 'param_callback' in params: - form_params.append(('callback', params['param_callback'])) + form_params.append(('callback', params['param_callback'])) # noqa: E501 body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml; charset=utf-8', 'application/json; charset=utf-8']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml; charset=utf-8', 'application/json; charset=utf-8']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/xml; charset=utf-8', 'application/json; charset=utf-8']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/xml; charset=utf-8', 'application/json; charset=utf-8']) # noqa: E501 # Authentication setting - auth_settings = ['http_basic_test'] + auth_settings = ['http_basic_test'] # noqa: E501 - return self.api_client.call_api('/fake', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def test_enum_parameters(self, **kwargs): - """ - To test enum parameters - To test enum parameters + def test_enum_parameters(self, **kwargs): # noqa: E501 + """To test enum parameters # noqa: E501 + + To test enum parameters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_enum_parameters(async=True) @@ -682,15 +695,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_enum_parameters_with_http_info(**kwargs) + return self.test_enum_parameters_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.test_enum_parameters_with_http_info(**kwargs) + (data) = self.test_enum_parameters_with_http_info(**kwargs) # noqa: E501 return data - def test_enum_parameters_with_http_info(self, **kwargs): - """ - To test enum parameters - To test enum parameters + def test_enum_parameters_with_http_info(self, **kwargs): # noqa: E501 + """To test enum parameters # noqa: E501 + + To test enum parameters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_enum_parameters_with_http_info(async=True) @@ -710,14 +723,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['enum_form_string_array', 'enum_form_string', 'enum_header_string_array', 'enum_header_string', 'enum_query_string_array', 'enum_query_string', 'enum_query_integer', 'enum_query_double'] + all_params = ['enum_form_string_array', 'enum_form_string', 'enum_header_string_array', 'enum_header_string', 'enum_query_string_array', 'enum_query_string', 'enum_query_integer', 'enum_query_double'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -726,68 +739,163 @@ class FakeApi(object): params[key] = val del params['kwargs'] - collection_formats = {} path_params = {} query_params = [] if 'enum_query_string_array' in params: - query_params.append(('enum_query_string_array', params['enum_query_string_array'])) - collection_formats['enum_query_string_array'] = 'csv' + query_params.append(('enum_query_string_array', params['enum_query_string_array'])) # noqa: E501 + collection_formats['enum_query_string_array'] = 'csv' # noqa: E501 if 'enum_query_string' in params: - query_params.append(('enum_query_string', params['enum_query_string'])) + query_params.append(('enum_query_string', params['enum_query_string'])) # noqa: E501 if 'enum_query_integer' in params: - query_params.append(('enum_query_integer', params['enum_query_integer'])) + query_params.append(('enum_query_integer', params['enum_query_integer'])) # noqa: E501 header_params = {} if 'enum_header_string_array' in params: - header_params['enum_header_string_array'] = params['enum_header_string_array'] - collection_formats['enum_header_string_array'] = 'csv' + header_params['enum_header_string_array'] = params['enum_header_string_array'] # noqa: E501 + collection_formats['enum_header_string_array'] = 'csv' # noqa: E501 if 'enum_header_string' in params: - header_params['enum_header_string'] = params['enum_header_string'] + header_params['enum_header_string'] = params['enum_header_string'] # noqa: E501 form_params = [] local_var_files = {} if 'enum_form_string_array' in params: - form_params.append(('enum_form_string_array', params['enum_form_string_array'])) - collection_formats['enum_form_string_array'] = 'csv' + form_params.append(('enum_form_string_array', params['enum_form_string_array'])) # noqa: E501 + collection_formats['enum_form_string_array'] = 'csv' # noqa: E501 if 'enum_form_string' in params: - form_params.append(('enum_form_string', params['enum_form_string'])) + form_params.append(('enum_form_string', params['enum_form_string'])) # noqa: E501 if 'enum_query_double' in params: - form_params.append(('enum_query_double', params['enum_query_double'])) + form_params.append(('enum_query_double', params['enum_query_double'])) # noqa: E501 body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['*/*']) + header_params['Accept'] = self.api_client.select_header_accept( + ['*/*']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['*/*']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['*/*']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def test_json_form_data(self, param, param2, **kwargs): + def test_inline_additional_properties(self, param, **kwargs): # noqa: E501 + """test inline additionalProperties # noqa: E501 + + # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async=True + >>> thread = api.test_inline_additional_properties(param, async=True) + >>> result = thread.get() + + :param async bool + :param object param: request body (required) + :return: None + If the method is called asynchronously, + returns the request thread. """ - test json serialization of form data - + kwargs['_return_http_data_only'] = True + if kwargs.get('async'): + return self.test_inline_additional_properties_with_http_info(param, **kwargs) # noqa: E501 + else: + (data) = self.test_inline_additional_properties_with_http_info(param, **kwargs) # noqa: E501 + return data + + def test_inline_additional_properties_with_http_info(self, param, **kwargs): # noqa: E501 + """test inline additionalProperties # noqa: E501 + + # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async=True + >>> thread = api.test_inline_additional_properties_with_http_info(param, async=True) + >>> result = thread.get() + + :param async bool + :param object param: request body (required) + :return: None + If the method is called asynchronously, + returns the request thread. + """ + + all_params = ['param'] # noqa: E501 + all_params.append('async') + all_params.append('_return_http_data_only') + all_params.append('_preload_content') + all_params.append('_request_timeout') + + params = locals() + for key, val in six.iteritems(params['kwargs']): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method test_inline_additional_properties" % key + ) + params[key] = val + del params['kwargs'] + # verify the required parameter 'param' is set + if ('param' not in params or + params['param'] is None): + raise ValueError("Missing the required parameter `param` when calling `test_inline_additional_properties`") # noqa: E501 + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if 'param' in params: + body_params = params['param'] + # HTTP header `Content-Type` + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json']) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + '/fake/inline-additionalProperties', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) + + def test_json_form_data(self, param, param2, **kwargs): # noqa: E501 + """test json serialization of form data # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_json_form_data(param, param2, async=True) @@ -802,15 +910,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_json_form_data_with_http_info(param, param2, **kwargs) + return self.test_json_form_data_with_http_info(param, param2, **kwargs) # noqa: E501 else: - (data) = self.test_json_form_data_with_http_info(param, param2, **kwargs) + (data) = self.test_json_form_data_with_http_info(param, param2, **kwargs) # noqa: E501 return data - def test_json_form_data_with_http_info(self, param, param2, **kwargs): - """ - test json serialization of form data - + def test_json_form_data_with_http_info(self, param, param2, **kwargs): # noqa: E501 + """test json serialization of form data # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_json_form_data_with_http_info(param, param2, async=True) @@ -824,14 +932,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['param', 'param2'] + all_params = ['param', 'param2'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -840,12 +948,13 @@ class FakeApi(object): params[key] = val del params['kwargs'] # verify the required parameter 'param' is set - if ('param' not in params) or (params['param'] is None): - raise ValueError("Missing the required parameter `param` when calling `test_json_form_data`") + if ('param' not in params or + params['param'] is None): + raise ValueError("Missing the required parameter `param` when calling `test_json_form_data`") # noqa: E501 # verify the required parameter 'param2' is set - if ('param2' not in params) or (params['param2'] is None): - raise ValueError("Missing the required parameter `param2` when calling `test_json_form_data`") - + if ('param2' not in params or + params['param2'] is None): + raise ValueError("Missing the required parameter `param2` when calling `test_json_form_data`") # noqa: E501 collection_formats = {} @@ -858,29 +967,30 @@ class FakeApi(object): form_params = [] local_var_files = {} if 'param' in params: - form_params.append(('param', params['param'])) + form_params.append(('param', params['param'])) # noqa: E501 if 'param2' in params: - form_params.append(('param2', params['param2'])) + form_params.append(('param2', params['param2'])) # noqa: E501 body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake/jsonFormData', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake/jsonFormData', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/fake_classname_tags_123_api.py b/samples/client/petstore/python-asyncio/petstore_api/api/fake_classname_tags_123_api.py similarity index 60% rename from samples/client/petstore/python/petstore_api/apis/fake_classname_tags_123_api.py rename to samples/client/petstore/python-asyncio/petstore_api/api/fake_classname_tags_123_api.py index da75ad3cccd..6b6606dc096 100644 --- a/samples/client/petstore/python/petstore_api/apis/fake_classname_tags_123_api.py +++ b/samples/client/petstore/python-asyncio/petstore_api/api/fake_classname_tags_123_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class FakeClassnameTags123Api(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,9 +33,9 @@ class FakeClassnameTags123Api(object): api_client = ApiClient() self.api_client = api_client - def test_classname(self, body, **kwargs): - """ - To test class name in snake case + def test_classname(self, body, **kwargs): # noqa: E501 + """To test class name in snake case # noqa: E501 + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_classname(body, async=True) @@ -51,14 +49,14 @@ class FakeClassnameTags123Api(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_classname_with_http_info(body, **kwargs) + return self.test_classname_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.test_classname_with_http_info(body, **kwargs) + (data) = self.test_classname_with_http_info(body, **kwargs) # noqa: E501 return data - def test_classname_with_http_info(self, body, **kwargs): - """ - To test class name in snake case + def test_classname_with_http_info(self, body, **kwargs): # noqa: E501 + """To test class name in snake case # noqa: E501 + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_classname_with_http_info(body, async=True) @@ -71,14 +69,14 @@ class FakeClassnameTags123Api(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -87,9 +85,9 @@ class FakeClassnameTags123Api(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 `test_classname`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `test_classname`") # noqa: E501 collection_formats = {} @@ -106,27 +104,28 @@ class FakeClassnameTags123Api(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json']) # noqa: E501 # Authentication setting - auth_settings = ['api_key_query'] + auth_settings = ['api_key_query'] # noqa: E501 - return self.api_client.call_api('/fake_classname_test', 'PATCH', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Client', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake_classname_test', 'PATCH', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Client', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python-tornado/petstore_api/apis/pet_api.py b/samples/client/petstore/python-asyncio/petstore_api/api/pet_api.py similarity index 57% rename from samples/client/petstore/python-tornado/petstore_api/apis/pet_api.py rename to samples/client/petstore/python-asyncio/petstore_api/api/pet_api.py index 51b6ce82540..ff1026f3fae 100644 --- a/samples/client/petstore/python-tornado/petstore_api/apis/pet_api.py +++ b/samples/client/petstore/python-asyncio/petstore_api/api/pet_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class PetApi(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,10 +33,10 @@ class PetApi(object): api_client = ApiClient() self.api_client = api_client - def add_pet(self, body, **kwargs): - """ - Add a new pet to the store - + def add_pet(self, body, **kwargs): # noqa: E501 + """Add a new pet to the store # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.add_pet(body, async=True) @@ -52,15 +50,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.add_pet_with_http_info(body, **kwargs) + return self.add_pet_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.add_pet_with_http_info(body, **kwargs) + (data) = self.add_pet_with_http_info(body, **kwargs) # noqa: E501 return data - def add_pet_with_http_info(self, body, **kwargs): - """ - Add a new pet to the store - + def add_pet_with_http_info(self, body, **kwargs): # noqa: E501 + """Add a new pet to the store # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.add_pet_with_http_info(body, async=True) @@ -73,14 +71,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -89,9 +87,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `add_pet`") # noqa: E501 collection_formats = {} @@ -108,35 +106,36 @@ class PetApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json', 'application/xml']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json', 'application/xml']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def delete_pet(self, pet_id, **kwargs): - """ - Deletes a pet - + def delete_pet(self, pet_id, **kwargs): # noqa: E501 + """Deletes a pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_pet(pet_id, async=True) @@ -151,15 +150,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.delete_pet_with_http_info(pet_id, **kwargs) + return self.delete_pet_with_http_info(pet_id, **kwargs) # noqa: E501 else: - (data) = self.delete_pet_with_http_info(pet_id, **kwargs) + (data) = self.delete_pet_with_http_info(pet_id, **kwargs) # noqa: E501 return data - def delete_pet_with_http_info(self, pet_id, **kwargs): - """ - Deletes a pet - + def delete_pet_with_http_info(self, pet_id, **kwargs): # noqa: E501 + """Deletes a pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_pet_with_http_info(pet_id, async=True) @@ -173,14 +172,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['pet_id', 'api_key'] + all_params = ['pet_id', 'api_key'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -189,52 +188,53 @@ 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`") - + if ('pet_id' not in params or + params['pet_id'] is None): + raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") # noqa: E501 collection_formats = {} path_params = {} if 'pet_id' in params: - path_params['petId'] = params['pet_id'] + path_params['petId'] = params['pet_id'] # noqa: E501 query_params = [] header_params = {} if 'api_key' in params: - header_params['api_key'] = params['api_key'] + header_params['api_key'] = params['api_key'] # noqa: E501 form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet/{petId}', 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/{petId}', 'DELETE', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def find_pets_by_status(self, status, **kwargs): - """ - Finds Pets by status - Multiple status values can be provided with comma separated strings + def find_pets_by_status(self, status, **kwargs): # noqa: E501 + """Finds Pets by status # noqa: E501 + + Multiple status values can be provided with comma separated strings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.find_pets_by_status(status, async=True) @@ -248,15 +248,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.find_pets_by_status_with_http_info(status, **kwargs) + return self.find_pets_by_status_with_http_info(status, **kwargs) # noqa: E501 else: - (data) = self.find_pets_by_status_with_http_info(status, **kwargs) + (data) = self.find_pets_by_status_with_http_info(status, **kwargs) # noqa: E501 return data - def find_pets_by_status_with_http_info(self, status, **kwargs): - """ - Finds Pets by status - Multiple status values can be provided with comma separated strings + def find_pets_by_status_with_http_info(self, status, **kwargs): # noqa: E501 + """Finds Pets by status # noqa: E501 + + Multiple status values can be provided with comma separated strings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.find_pets_by_status_with_http_info(status, async=True) @@ -269,14 +269,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['status'] + all_params = ['status'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -285,9 +285,9 @@ 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`") - + if ('status' not in params or + params['status'] is None): + raise ValueError("Missing the required parameter `status` when calling `find_pets_by_status`") # noqa: E501 collection_formats = {} @@ -295,8 +295,8 @@ class PetApi(object): query_params = [] if 'status' in params: - query_params.append(('status', params['status'])) - collection_formats['status'] = 'csv' + query_params.append(('status', params['status'])) # noqa: E501 + collection_formats['status'] = 'csv' # noqa: E501 header_params = {} @@ -305,31 +305,32 @@ class PetApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet/findByStatus', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[Pet]', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/findByStatus', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='list[Pet]', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def find_pets_by_tags(self, tags, **kwargs): - """ - Finds Pets by tags - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + def find_pets_by_tags(self, tags, **kwargs): # noqa: E501 + """Finds Pets by tags # noqa: E501 + + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.find_pets_by_tags(tags, async=True) @@ -343,15 +344,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.find_pets_by_tags_with_http_info(tags, **kwargs) + return self.find_pets_by_tags_with_http_info(tags, **kwargs) # noqa: E501 else: - (data) = self.find_pets_by_tags_with_http_info(tags, **kwargs) + (data) = self.find_pets_by_tags_with_http_info(tags, **kwargs) # noqa: E501 return data - def find_pets_by_tags_with_http_info(self, tags, **kwargs): - """ - Finds Pets by tags - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + def find_pets_by_tags_with_http_info(self, tags, **kwargs): # noqa: E501 + """Finds Pets by tags # noqa: E501 + + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.find_pets_by_tags_with_http_info(tags, async=True) @@ -364,14 +365,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['tags'] + all_params = ['tags'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -380,9 +381,9 @@ 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`") - + if ('tags' not in params or + params['tags'] is None): + raise ValueError("Missing the required parameter `tags` when calling `find_pets_by_tags`") # noqa: E501 collection_formats = {} @@ -390,8 +391,8 @@ class PetApi(object): query_params = [] if 'tags' in params: - query_params.append(('tags', params['tags'])) - collection_formats['tags'] = 'csv' + query_params.append(('tags', params['tags'])) # noqa: E501 + collection_formats['tags'] = 'csv' # noqa: E501 header_params = {} @@ -400,31 +401,32 @@ class PetApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet/findByTags', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[Pet]', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/findByTags', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='list[Pet]', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def get_pet_by_id(self, pet_id, **kwargs): - """ - Find pet by ID - Returns a single pet + def get_pet_by_id(self, pet_id, **kwargs): # noqa: E501 + """Find pet by ID # noqa: E501 + + Returns a single pet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_pet_by_id(pet_id, async=True) @@ -438,15 +440,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.get_pet_by_id_with_http_info(pet_id, **kwargs) + return self.get_pet_by_id_with_http_info(pet_id, **kwargs) # noqa: E501 else: - (data) = self.get_pet_by_id_with_http_info(pet_id, **kwargs) + (data) = self.get_pet_by_id_with_http_info(pet_id, **kwargs) # noqa: E501 return data - def get_pet_by_id_with_http_info(self, pet_id, **kwargs): - """ - Find pet by ID - Returns a single pet + def get_pet_by_id_with_http_info(self, pet_id, **kwargs): # noqa: E501 + """Find pet by ID # noqa: E501 + + Returns a single pet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_pet_by_id_with_http_info(pet_id, async=True) @@ -459,14 +461,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['pet_id'] + all_params = ['pet_id'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -475,15 +477,15 @@ 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`") - + 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`") # noqa: E501 collection_formats = {} path_params = {} if 'pet_id' in params: - path_params['petId'] = params['pet_id'] + path_params['petId'] = params['pet_id'] # noqa: E501 query_params = [] @@ -494,31 +496,32 @@ class PetApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = ['api_key'] + auth_settings = ['api_key'] # noqa: E501 - return self.api_client.call_api('/pet/{petId}', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Pet', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/{petId}', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Pet', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def update_pet(self, body, **kwargs): - """ - Update an existing pet - + def update_pet(self, body, **kwargs): # noqa: E501 + """Update an existing pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_pet(body, async=True) @@ -532,15 +535,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.update_pet_with_http_info(body, **kwargs) + return self.update_pet_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.update_pet_with_http_info(body, **kwargs) + (data) = self.update_pet_with_http_info(body, **kwargs) # noqa: E501 return data - def update_pet_with_http_info(self, body, **kwargs): - """ - Update an existing pet - + def update_pet_with_http_info(self, body, **kwargs): # noqa: E501 + """Update an existing pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_pet_with_http_info(body, async=True) @@ -553,14 +556,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -569,9 +572,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `update_pet`") # noqa: E501 collection_formats = {} @@ -588,35 +591,36 @@ class PetApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json', 'application/xml']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json', 'application/xml']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet', 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet', 'PUT', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def update_pet_with_form(self, pet_id, **kwargs): - """ - Updates a pet in the store with form data - + def update_pet_with_form(self, pet_id, **kwargs): # noqa: E501 + """Updates a pet in the store with form data # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_pet_with_form(pet_id, async=True) @@ -632,15 +636,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.update_pet_with_form_with_http_info(pet_id, **kwargs) + return self.update_pet_with_form_with_http_info(pet_id, **kwargs) # noqa: E501 else: - (data) = self.update_pet_with_form_with_http_info(pet_id, **kwargs) + (data) = self.update_pet_with_form_with_http_info(pet_id, **kwargs) # noqa: E501 return data - def update_pet_with_form_with_http_info(self, pet_id, **kwargs): - """ - Updates a pet in the store with form data - + def update_pet_with_form_with_http_info(self, pet_id, **kwargs): # noqa: E501 + """Updates a pet in the store with form data # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_pet_with_form_with_http_info(pet_id, async=True) @@ -655,14 +659,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['pet_id', 'name', 'status'] + all_params = ['pet_id', 'name', 'status'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -671,15 +675,15 @@ 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`") - + 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`") # noqa: E501 collection_formats = {} path_params = {} if 'pet_id' in params: - path_params['petId'] = params['pet_id'] + path_params['petId'] = params['pet_id'] # noqa: E501 query_params = [] @@ -688,41 +692,42 @@ class PetApi(object): form_params = [] local_var_files = {} if 'name' in params: - form_params.append(('name', params['name'])) + form_params.append(('name', params['name'])) # noqa: E501 if 'status' in params: - form_params.append(('status', params['status'])) + form_params.append(('status', params['status'])) # noqa: E501 body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/x-www-form-urlencoded']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/x-www-form-urlencoded']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet/{petId}', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/{petId}', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def upload_file(self, pet_id, **kwargs): - """ - uploads an image - + def upload_file(self, pet_id, **kwargs): # noqa: E501 + """uploads an image # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.upload_file(pet_id, async=True) @@ -738,15 +743,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.upload_file_with_http_info(pet_id, **kwargs) + return self.upload_file_with_http_info(pet_id, **kwargs) # noqa: E501 else: - (data) = self.upload_file_with_http_info(pet_id, **kwargs) + (data) = self.upload_file_with_http_info(pet_id, **kwargs) # noqa: E501 return data - def upload_file_with_http_info(self, pet_id, **kwargs): - """ - uploads an image - + def upload_file_with_http_info(self, pet_id, **kwargs): # noqa: E501 + """uploads an image # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.upload_file_with_http_info(pet_id, async=True) @@ -761,14 +766,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['pet_id', 'additional_metadata', 'file'] + all_params = ['pet_id', 'additional_metadata', 'file'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -777,15 +782,15 @@ 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`") - + if ('pet_id' not in params or + params['pet_id'] is None): + raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") # noqa: E501 collection_formats = {} path_params = {} if 'pet_id' in params: - path_params['petId'] = params['pet_id'] + path_params['petId'] = params['pet_id'] # noqa: E501 query_params = [] @@ -794,33 +799,34 @@ class PetApi(object): form_params = [] local_var_files = {} if 'additional_metadata' in params: - form_params.append(('additionalMetadata', params['additional_metadata'])) + form_params.append(('additionalMetadata', params['additional_metadata'])) # noqa: E501 if 'file' in params: - local_var_files['file'] = params['file'] + local_var_files['file'] = params['file'] # noqa: E501 body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['multipart/form-data']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['multipart/form-data']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet/{petId}/uploadImage', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='ApiResponse', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/{petId}/uploadImage', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='ApiResponse', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python-asyncio/petstore_api/apis/store_api.py b/samples/client/petstore/python-asyncio/petstore_api/api/store_api.py similarity index 57% rename from samples/client/petstore/python-asyncio/petstore_api/apis/store_api.py rename to samples/client/petstore/python-asyncio/petstore_api/api/store_api.py index e9d9599c363..ebb9a4eb27a 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/apis/store_api.py +++ b/samples/client/petstore/python-asyncio/petstore_api/api/store_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class StoreApi(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,10 +33,10 @@ class StoreApi(object): api_client = ApiClient() self.api_client = api_client - def delete_order(self, order_id, **kwargs): - """ - Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + def delete_order(self, order_id, **kwargs): # noqa: E501 + """Delete purchase order by ID # noqa: E501 + + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_order(order_id, async=True) @@ -52,15 +50,15 @@ class StoreApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.delete_order_with_http_info(order_id, **kwargs) + return self.delete_order_with_http_info(order_id, **kwargs) # noqa: E501 else: - (data) = self.delete_order_with_http_info(order_id, **kwargs) + (data) = self.delete_order_with_http_info(order_id, **kwargs) # noqa: E501 return data - def delete_order_with_http_info(self, order_id, **kwargs): - """ - Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + def delete_order_with_http_info(self, order_id, **kwargs): # noqa: E501 + """Delete purchase order by ID # noqa: E501 + + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_order_with_http_info(order_id, async=True) @@ -73,14 +71,14 @@ class StoreApi(object): returns the request thread. """ - all_params = ['order_id'] + all_params = ['order_id'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -89,15 +87,15 @@ 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' not in params or + params['order_id'] is None): + raise ValueError("Missing the required parameter `order_id` when calling `delete_order`") # noqa: E501 collection_formats = {} path_params = {} if 'order_id' in params: - path_params['order_id'] = params['order_id'] + path_params['order_id'] = params['order_id'] # noqa: E501 query_params = [] @@ -108,31 +106,32 @@ class StoreApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/store/order/{order_id}', 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/store/order/{order_id}', 'DELETE', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def get_inventory(self, **kwargs): - """ - Returns pet inventories by status - Returns a map of status codes to quantities + def get_inventory(self, **kwargs): # noqa: E501 + """Returns pet inventories by status # noqa: E501 + + Returns a map of status codes to quantities # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_inventory(async=True) @@ -145,15 +144,15 @@ class StoreApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.get_inventory_with_http_info(**kwargs) + return self.get_inventory_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.get_inventory_with_http_info(**kwargs) + (data) = self.get_inventory_with_http_info(**kwargs) # noqa: E501 return data - def get_inventory_with_http_info(self, **kwargs): - """ - Returns pet inventories by status - Returns a map of status codes to quantities + def get_inventory_with_http_info(self, **kwargs): # noqa: E501 + """Returns pet inventories by status # noqa: E501 + + Returns a map of status codes to quantities # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_inventory_with_http_info(async=True) @@ -165,14 +164,14 @@ class StoreApi(object): returns the request thread. """ - all_params = [] + all_params = [] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -194,31 +193,32 @@ class StoreApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 # Authentication setting - auth_settings = ['api_key'] + auth_settings = ['api_key'] # noqa: E501 - return self.api_client.call_api('/store/inventory', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='dict(str, int)', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/store/inventory', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='dict(str, int)', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def get_order_by_id(self, order_id, **kwargs): - """ - Find purchase order by ID - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + def get_order_by_id(self, order_id, **kwargs): # noqa: E501 + """Find purchase order by ID # noqa: E501 + + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_order_by_id(order_id, async=True) @@ -232,15 +232,15 @@ class StoreApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.get_order_by_id_with_http_info(order_id, **kwargs) + return self.get_order_by_id_with_http_info(order_id, **kwargs) # noqa: E501 else: - (data) = self.get_order_by_id_with_http_info(order_id, **kwargs) + (data) = self.get_order_by_id_with_http_info(order_id, **kwargs) # noqa: E501 return data - def get_order_by_id_with_http_info(self, order_id, **kwargs): - """ - Find purchase order by ID - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + def get_order_by_id_with_http_info(self, order_id, **kwargs): # noqa: E501 + """Find purchase order by ID # noqa: E501 + + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_order_by_id_with_http_info(order_id, async=True) @@ -253,14 +253,14 @@ class StoreApi(object): returns the request thread. """ - all_params = ['order_id'] + all_params = ['order_id'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -269,19 +269,19 @@ 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: - raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5`") - if 'order_id' in params and params['order_id'] < 1: - raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value greater than or equal to `1`") + 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`") # noqa: E501 + if 'order_id' in params and params['order_id'] > 5: # noqa: E501 + raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5`") # noqa: E501 + if 'order_id' in params and params['order_id'] < 1: # noqa: E501 + raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value greater than or equal to `1`") # noqa: E501 collection_formats = {} path_params = {} if 'order_id' in params: - path_params['order_id'] = params['order_id'] + path_params['order_id'] = params['order_id'] # noqa: E501 query_params = [] @@ -292,31 +292,32 @@ class StoreApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/store/order/{order_id}', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Order', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/store/order/{order_id}', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Order', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def place_order(self, body, **kwargs): - """ - Place an order for a pet - + def place_order(self, body, **kwargs): # noqa: E501 + """Place an order for a pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.place_order(body, async=True) @@ -330,15 +331,15 @@ class StoreApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.place_order_with_http_info(body, **kwargs) + return self.place_order_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.place_order_with_http_info(body, **kwargs) + (data) = self.place_order_with_http_info(body, **kwargs) # noqa: E501 return data - def place_order_with_http_info(self, body, **kwargs): - """ - Place an order for a pet - + def place_order_with_http_info(self, body, **kwargs): # noqa: E501 + """Place an order for a pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.place_order_with_http_info(body, async=True) @@ -351,14 +352,14 @@ class StoreApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -367,9 +368,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `place_order`") # noqa: E501 collection_formats = {} @@ -386,23 +387,24 @@ class StoreApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/store/order', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Order', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/store/order', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Order', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/user_api.py b/samples/client/petstore/python-asyncio/petstore_api/api/user_api.py similarity index 57% rename from samples/client/petstore/python/petstore_api/apis/user_api.py rename to samples/client/petstore/python-asyncio/petstore_api/api/user_api.py index ffdad2dd60f..89949844aa1 100644 --- a/samples/client/petstore/python/petstore_api/apis/user_api.py +++ b/samples/client/petstore/python-asyncio/petstore_api/api/user_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class UserApi(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,10 +33,10 @@ class UserApi(object): api_client = ApiClient() self.api_client = api_client - def create_user(self, body, **kwargs): - """ - Create user - This can only be done by the logged in user. + def create_user(self, body, **kwargs): # noqa: E501 + """Create user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_user(body, async=True) @@ -52,15 +50,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.create_user_with_http_info(body, **kwargs) + return self.create_user_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.create_user_with_http_info(body, **kwargs) + (data) = self.create_user_with_http_info(body, **kwargs) # noqa: E501 return data - def create_user_with_http_info(self, body, **kwargs): - """ - Create user - This can only be done by the logged in user. + def create_user_with_http_info(self, body, **kwargs): # noqa: E501 + """Create user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_user_with_http_info(body, async=True) @@ -73,14 +71,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -89,9 +87,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `create_user`") # noqa: E501 collection_formats = {} @@ -108,31 +106,32 @@ class UserApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def create_users_with_array_input(self, body, **kwargs): - """ - Creates list of users with given input array - + def create_users_with_array_input(self, body, **kwargs): # noqa: E501 + """Creates list of users with given input array # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_users_with_array_input(body, async=True) @@ -146,15 +145,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.create_users_with_array_input_with_http_info(body, **kwargs) + return self.create_users_with_array_input_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.create_users_with_array_input_with_http_info(body, **kwargs) + (data) = self.create_users_with_array_input_with_http_info(body, **kwargs) # noqa: E501 return data - def create_users_with_array_input_with_http_info(self, body, **kwargs): - """ - Creates list of users with given input array - + def create_users_with_array_input_with_http_info(self, body, **kwargs): # noqa: E501 + """Creates list of users with given input array # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_users_with_array_input_with_http_info(body, async=True) @@ -167,14 +166,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -183,9 +182,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `create_users_with_array_input`") # noqa: E501 collection_formats = {} @@ -202,31 +201,32 @@ class UserApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/createWithArray', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/createWithArray', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def create_users_with_list_input(self, body, **kwargs): - """ - Creates list of users with given input array - + def create_users_with_list_input(self, body, **kwargs): # noqa: E501 + """Creates list of users with given input array # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_users_with_list_input(body, async=True) @@ -240,15 +240,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.create_users_with_list_input_with_http_info(body, **kwargs) + return self.create_users_with_list_input_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.create_users_with_list_input_with_http_info(body, **kwargs) + (data) = self.create_users_with_list_input_with_http_info(body, **kwargs) # noqa: E501 return data - def create_users_with_list_input_with_http_info(self, body, **kwargs): - """ - Creates list of users with given input array - + def create_users_with_list_input_with_http_info(self, body, **kwargs): # noqa: E501 + """Creates list of users with given input array # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_users_with_list_input_with_http_info(body, async=True) @@ -261,14 +261,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -277,9 +277,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `create_users_with_list_input`") # noqa: E501 collection_formats = {} @@ -296,31 +296,32 @@ class UserApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/createWithList', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/createWithList', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def delete_user(self, username, **kwargs): - """ - Delete user - This can only be done by the logged in user. + def delete_user(self, username, **kwargs): # noqa: E501 + """Delete user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_user(username, async=True) @@ -334,15 +335,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.delete_user_with_http_info(username, **kwargs) + return self.delete_user_with_http_info(username, **kwargs) # noqa: E501 else: - (data) = self.delete_user_with_http_info(username, **kwargs) + (data) = self.delete_user_with_http_info(username, **kwargs) # noqa: E501 return data - def delete_user_with_http_info(self, username, **kwargs): - """ - Delete user - This can only be done by the logged in user. + def delete_user_with_http_info(self, username, **kwargs): # noqa: E501 + """Delete user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_user_with_http_info(username, async=True) @@ -355,14 +356,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['username'] + all_params = ['username'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -371,15 +372,15 @@ 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`") - + if ('username' not in params or + params['username'] is None): + raise ValueError("Missing the required parameter `username` when calling `delete_user`") # noqa: E501 collection_formats = {} path_params = {} if 'username' in params: - path_params['username'] = params['username'] + path_params['username'] = params['username'] # noqa: E501 query_params = [] @@ -390,31 +391,32 @@ class UserApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/{username}', 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/{username}', 'DELETE', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def get_user_by_name(self, username, **kwargs): - """ - Get user by user name - + def get_user_by_name(self, username, **kwargs): # noqa: E501 + """Get user by user name # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_user_by_name(username, async=True) @@ -428,15 +430,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.get_user_by_name_with_http_info(username, **kwargs) + return self.get_user_by_name_with_http_info(username, **kwargs) # noqa: E501 else: - (data) = self.get_user_by_name_with_http_info(username, **kwargs) + (data) = self.get_user_by_name_with_http_info(username, **kwargs) # noqa: E501 return data - def get_user_by_name_with_http_info(self, username, **kwargs): - """ - Get user by user name - + def get_user_by_name_with_http_info(self, username, **kwargs): # noqa: E501 + """Get user by user name # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_user_by_name_with_http_info(username, async=True) @@ -449,14 +451,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['username'] + all_params = ['username'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -465,15 +467,15 @@ 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`") - + if ('username' not in params or + params['username'] is None): + raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") # noqa: E501 collection_formats = {} path_params = {} if 'username' in params: - path_params['username'] = params['username'] + path_params['username'] = params['username'] # noqa: E501 query_params = [] @@ -484,31 +486,32 @@ class UserApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/{username}', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='User', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/{username}', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='User', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def login_user(self, username, password, **kwargs): - """ - Logs user into the system - + def login_user(self, username, password, **kwargs): # noqa: E501 + """Logs user into the system # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.login_user(username, password, async=True) @@ -523,15 +526,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.login_user_with_http_info(username, password, **kwargs) + return self.login_user_with_http_info(username, password, **kwargs) # noqa: E501 else: - (data) = self.login_user_with_http_info(username, password, **kwargs) + (data) = self.login_user_with_http_info(username, password, **kwargs) # noqa: E501 return data - def login_user_with_http_info(self, username, password, **kwargs): - """ - Logs user into the system - + def login_user_with_http_info(self, username, password, **kwargs): # noqa: E501 + """Logs user into the system # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.login_user_with_http_info(username, password, async=True) @@ -545,14 +548,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['username', 'password'] + all_params = ['username', 'password'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -561,12 +564,13 @@ 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`") + if ('username' not in params or + params['username'] is None): + raise ValueError("Missing the required parameter `username` when calling `login_user`") # noqa: E501 # verify the required parameter 'password' is set - if ('password' not in params) or (params['password'] is None): - raise ValueError("Missing the required parameter `password` when calling `login_user`") - + if ('password' not in params or + params['password'] is None): + raise ValueError("Missing the required parameter `password` when calling `login_user`") # noqa: E501 collection_formats = {} @@ -574,9 +578,9 @@ class UserApi(object): query_params = [] if 'username' in params: - query_params.append(('username', params['username'])) + query_params.append(('username', params['username'])) # noqa: E501 if 'password' in params: - query_params.append(('password', params['password'])) + query_params.append(('password', params['password'])) # noqa: E501 header_params = {} @@ -585,31 +589,32 @@ class UserApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/login', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='str', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/login', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='str', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def logout_user(self, **kwargs): - """ - Logs out current logged in user session - + def logout_user(self, **kwargs): # noqa: E501 + """Logs out current logged in user session # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.logout_user(async=True) @@ -622,15 +627,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.logout_user_with_http_info(**kwargs) + return self.logout_user_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.logout_user_with_http_info(**kwargs) + (data) = self.logout_user_with_http_info(**kwargs) # noqa: E501 return data - def logout_user_with_http_info(self, **kwargs): - """ - Logs out current logged in user session - + def logout_user_with_http_info(self, **kwargs): # noqa: E501 + """Logs out current logged in user session # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.logout_user_with_http_info(async=True) @@ -642,14 +647,14 @@ class UserApi(object): returns the request thread. """ - all_params = [] + all_params = [] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -671,31 +676,32 @@ class UserApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/logout', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/logout', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def update_user(self, username, body, **kwargs): - """ - Updated user - This can only be done by the logged in user. + def update_user(self, username, body, **kwargs): # noqa: E501 + """Updated user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_user(username, body, async=True) @@ -710,15 +716,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.update_user_with_http_info(username, body, **kwargs) + return self.update_user_with_http_info(username, body, **kwargs) # noqa: E501 else: - (data) = self.update_user_with_http_info(username, body, **kwargs) + (data) = self.update_user_with_http_info(username, body, **kwargs) # noqa: E501 return data - def update_user_with_http_info(self, username, body, **kwargs): - """ - Updated user - This can only be done by the logged in user. + def update_user_with_http_info(self, username, body, **kwargs): # noqa: E501 + """Updated user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_user_with_http_info(username, body, async=True) @@ -732,14 +738,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['username', 'body'] + all_params = ['username', 'body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -748,18 +754,19 @@ 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`") + if ('username' not in params or + params['username'] is None): + raise ValueError("Missing the required parameter `username` when calling `update_user`") # noqa: E501 # 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_user`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `update_user`") # noqa: E501 collection_formats = {} path_params = {} if 'username' in params: - path_params['username'] = params['username'] + path_params['username'] = params['username'] # noqa: E501 query_params = [] @@ -772,23 +779,24 @@ class UserApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/{username}', 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/{username}', 'PUT', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python-asyncio/petstore_api/api_client.py b/samples/client/petstore/python-asyncio/petstore_api/api_client.py index 9f265a7f94a..6029e8fa113 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/api_client.py +++ b/samples/client/petstore/python-asyncio/petstore_api/api_client.py @@ -2,7 +2,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,27 +11,25 @@ from __future__ import absolute_import -import os -import re +import datetime import json import mimetypes -import tempfile from multiprocessing.pool import ThreadPool - -from datetime import date, datetime +import os +import re +import tempfile # python 2 and python 3 compatibility library -from six import PY3, integer_types, iteritems, text_type +import six from six.moves.urllib.parse import quote -from . import models -from .configuration import Configuration -from .rest import ApiException, RESTClientObject +from petstore_api.configuration import Configuration +import petstore_api.models +from petstore_api import rest class ApiClient(object): - """ - Generic API client for Swagger client library builds. + """Generic API client for Swagger client library builds. Swagger generic API client. This client handles the client- server communication, and is invariant across implementations. Specifics of @@ -42,64 +40,63 @@ class ApiClient(object): Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. - :param host: The base path for the server to call. + :param configuration: .Configuration object for this client :param header_name: a header to pass when making calls to the API. - :param header_value: a header value to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API """ - PRIMITIVE_TYPES = (float, bool, bytes, text_type) + integer_types + PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types NATIVE_TYPES_MAPPING = { 'int': int, - 'long': int if PY3 else long, + 'long': int if six.PY3 else long, # noqa: F821 'float': float, 'str': str, 'bool': bool, - 'date': date, - 'datetime': datetime, + 'date': datetime.date, + 'datetime': datetime.datetime, 'object': object, } - def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None): + def __init__(self, configuration=None, header_name=None, header_value=None, + cookie=None): if configuration is None: configuration = Configuration() self.configuration = configuration self.pool = ThreadPool() - self.rest_client = RESTClientObject(configuration) + self.rest_client = rest.RESTClientObject(configuration) self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value self.cookie = cookie # Set default User-Agent. self.user_agent = 'Swagger-Codegen/1.0.0/python' - + def __del__(self): self.pool.close() self.pool.join() @property def user_agent(self): - """ - Gets user agent. - """ + """User agent for this API client""" return self.default_headers['User-Agent'] @user_agent.setter def user_agent(self, value): - """ - Sets user agent. - """ self.default_headers['User-Agent'] = value def set_default_header(self, header_name, header_value): self.default_headers[header_name] = header_value - async def __call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_type=None, auth_settings=None, - _return_http_data_only=None, collection_formats=None, _preload_content=True, - _request_timeout=None): + async def __call_api( + self, resource_path, method, path_params=None, + query_params=None, header_params=None, body=None, post_params=None, + files=None, response_type=None, auth_settings=None, + _return_http_data_only=None, collection_formats=None, + _preload_content=True, _request_timeout=None): config = self.configuration @@ -121,7 +118,9 @@ class ApiClient(object): for k, v in path_params: # specified safe chars, encode everything resource_path = resource_path.replace( - '{%s}' % k, quote(str(v), safe=config.safe_chars_for_path_param)) + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) # query parameters if query_params: @@ -147,12 +146,11 @@ class ApiClient(object): url = self.configuration.host + resource_path # perform request and return response - response_data = await self.request(method, url, - query_params=query_params, - headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) + response_data = await self.request( + method, url, query_params=query_params, headers=header_params, + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout) self.last_response = response_data @@ -167,11 +165,11 @@ class ApiClient(object): if _return_http_data_only: return (return_data) else: - return (return_data, response_data.status, response_data.getheaders()) + return (return_data, response_data.status, + response_data.getheaders()) def sanitize_for_serialization(self, obj): - """ - Builds a JSON POST object. + """Builds a JSON POST object. If obj is None, return None. If obj is str, int, long, float, bool, return directly. @@ -194,7 +192,7 @@ class ApiClient(object): elif isinstance(obj, tuple): return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj) - elif isinstance(obj, (datetime, date)): + elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() if isinstance(obj, dict): @@ -206,15 +204,14 @@ class ApiClient(object): # Convert attribute name to json key in # model definition for request. obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in iteritems(obj.swagger_types) + for attr, _ in six.iteritems(obj.swagger_types) if getattr(obj, attr) is not None} return {key: self.sanitize_for_serialization(val) - for key, val in iteritems(obj_dict)} + for key, val in six.iteritems(obj_dict)} def deserialize(self, response, response_type): - """ - Deserializes response into an object. + """Deserializes response into an object. :param response: RESTResponse object to be deserialized. :param response_type: class literal for @@ -236,8 +233,7 @@ class ApiClient(object): return self.__deserialize(data, response_type) def __deserialize(self, data, klass): - """ - Deserializes dict, list, str into an object. + """Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. @@ -256,21 +252,21 @@ class ApiClient(object): if klass.startswith('dict('): sub_kls = re.match('dict\(([^,]*), (.*)\)', klass).group(2) return {k: self.__deserialize(v, sub_kls) - for k, v in iteritems(data)} + for k, v in six.iteritems(data)} # convert str to class if klass in self.NATIVE_TYPES_MAPPING: klass = self.NATIVE_TYPES_MAPPING[klass] else: - klass = getattr(models, klass) + klass = getattr(petstore_api.models, klass) if klass in self.PRIMITIVE_TYPES: return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) - elif klass == date: + elif klass == datetime.date: return self.__deserialize_date(data) - elif klass == datetime: + elif klass == datetime.datetime: return self.__deserialize_datatime(data) else: return self.__deserialize_model(data, klass) @@ -279,10 +275,10 @@ class ApiClient(object): path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, async=None, - _return_http_data_only=None, collection_formats=None, _preload_content=True, - _request_timeout=None): - """ - Makes the HTTP request (synchronous) and return the deserialized data. + _return_http_data_only=None, collection_formats=None, + _preload_content=True, _request_timeout=None): + """Makes the HTTP request (synchronous) and returns deserialized data. + To make an async request, set the async parameter. :param resource_path: Path to method endpoint. @@ -299,13 +295,17 @@ class ApiClient(object): :param files dict: key -> filename, value -> filepath, for `multipart/form-data`. :param async bool: execute request asynchronously - :param _return_http_data_only: response data without head status code and headers + :param _return_http_data_only: response data without head status code + and headers :param collection_formats: dict of collection formats for path, query, header, and post parameters. - :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without - reading/decoding response data. Default is True. - :param _request_timeout: timeout setting for this request. If one number provided, it will be total request - timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: If async parameter is True, the request will be called asynchronously. @@ -318,22 +318,23 @@ class ApiClient(object): path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, - _return_http_data_only, collection_formats, _preload_content, _request_timeout) + _return_http_data_only, collection_formats, + _preload_content, _request_timeout) else: - thread = self.pool.apply_async(self.__call_api, (resource_path, method, - path_params, query_params, + thread = self.pool.apply_async(self.__call_api, (resource_path, + method, path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, _return_http_data_only, - collection_formats, _preload_content, _request_timeout)) + collection_formats, + _preload_content, _request_timeout)) return thread def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, _request_timeout=None): - """ - Makes the HTTP request using RESTClient. - """ + post_params=None, body=None, _preload_content=True, + _request_timeout=None): + """Makes the HTTP request using RESTClient.""" if method == "GET": return self.rest_client.GET(url, query_params=query_params, @@ -392,8 +393,7 @@ class ApiClient(object): ) def parameters_to_tuples(self, params, collection_formats): - """ - Get parameters as list of tuples, formatting collections. + """Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or list of two-tuples :param dict collection_formats: Parameter collection formats @@ -402,7 +402,7 @@ class ApiClient(object): new_params = [] if collection_formats is None: collection_formats = {} - for k, v in iteritems(params) if isinstance(params, dict) else params: + for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501 if k in collection_formats: collection_format = collection_formats[k] if collection_format == 'multi': @@ -423,8 +423,7 @@ class ApiClient(object): return new_params def prepare_post_parameters(self, post_params=None, files=None): - """ - Builds form parameters. + """Builds form parameters. :param post_params: Normal form parameters. :param files: File parameters. @@ -436,7 +435,7 @@ class ApiClient(object): params = post_params if files: - for k, v in iteritems(files): + for k, v in six.iteritems(files): if not v: continue file_names = v if type(v) is list else [v] @@ -444,15 +443,15 @@ class ApiClient(object): with open(n, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() - mimetype = mimetypes.\ - guess_type(filename)[0] or 'application/octet-stream' - params.append(tuple([k, tuple([filename, filedata, mimetype])])) + mimetype = (mimetypes.guess_type(filename)[0] or + 'application/octet-stream') + params.append( + tuple([k, tuple([filename, filedata, mimetype])])) return params def select_header_accept(self, accepts): - """ - Returns `Accept` based on an array of accepts provided. + """Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json). @@ -468,8 +467,7 @@ class ApiClient(object): return ', '.join(accepts) def select_header_content_type(self, content_types): - """ - Returns `Content-Type` based on an array of content_types provided. + """Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. :return: Content-Type (e.g. application/json). @@ -485,8 +483,7 @@ class ApiClient(object): return content_types[0] def update_params_for_auth(self, headers, querys, auth_settings): - """ - Updates header and query params based on authentication setting. + """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. :param querys: Query parameters tuple list to be updated. @@ -510,7 +507,8 @@ class ApiClient(object): ) def __deserialize_file(self, response): - """ + """Deserializes body to file + Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. @@ -523,19 +521,17 @@ class ApiClient(object): content_disposition = response.getheader("Content-Disposition") if content_disposition: - filename = re.\ - search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).\ - group(1) + filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition).group(1) path = os.path.join(os.path.dirname(path), filename) - with open(path, "w") as f: + with open(path, "wb") as f: f.write(response.data) return path def __deserialize_primitive(self, data, klass): - """ - Deserializes string to primitive type. + """Deserializes string to primitive type. :param data: str. :param klass: class literal. @@ -545,21 +541,19 @@ class ApiClient(object): try: return klass(data) except UnicodeEncodeError: - return unicode(data) + return six.u(data) except TypeError: return data def __deserialize_object(self, value): - """ - Return a original value. + """Return a original value. :return: object. """ return value def __deserialize_date(self, string): - """ - Deserializes string to date. + """Deserializes string to date. :param string: str. :return: date. @@ -570,14 +564,13 @@ class ApiClient(object): except ImportError: return string except ValueError: - raise ApiException( + raise rest.ApiException( status=0, - reason="Failed to parse `{0}` into a date object".format(string) + reason="Failed to parse `{0}` as date object".format(string) ) def __deserialize_datatime(self, string): - """ - Deserializes string to datetime. + """Deserializes string to datetime. The string should be in iso8601 datetime format. @@ -590,32 +583,32 @@ class ApiClient(object): except ImportError: return string except ValueError: - raise ApiException( + raise rest.ApiException( status=0, reason=( - "Failed to parse `{0}` into a datetime object" + "Failed to parse `{0}` as datetime object" .format(string) ) ) def __deserialize_model(self, data, klass): - """ - Deserializes list or dict to model. + """Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object. """ - if not klass.swagger_types and not hasattr(klass, 'get_real_child_model'): + if not klass.swagger_types and not hasattr(klass, + 'get_real_child_model'): return data kwargs = {} if klass.swagger_types is not None: - for attr, attr_type in iteritems(klass.swagger_types): - if data is not None \ - and klass.attribute_map[attr] in data \ - and isinstance(data, (list, dict)): + for attr, attr_type in six.iteritems(klass.swagger_types): + if (data is not None and + klass.attribute_map[attr] in data and + isinstance(data, (list, dict))): value = data[klass.attribute_map[attr]] kwargs[attr] = self.__deserialize(value, attr_type) diff --git a/samples/client/petstore/python-asyncio/petstore_api/apis/__init__.py b/samples/client/petstore/python-asyncio/petstore_api/apis/__init__.py deleted file mode 100644 index b4b975ca8e0..00000000000 --- a/samples/client/petstore/python-asyncio/petstore_api/apis/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -from __future__ import absolute_import - -# import apis into api package -from .another_fake_api import AnotherFakeApi -from .fake_api import FakeApi -from .fake_classname_tags_123_api import FakeClassnameTags123Api -from .pet_api import PetApi -from .store_api import StoreApi -from .user_api import UserApi diff --git a/samples/client/petstore/python-asyncio/petstore_api/configuration.py b/samples/client/petstore/python-asyncio/petstore_api/configuration.py index 29bf22034aa..f6273cf28cc 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/configuration.py +++ b/samples/client/petstore/python-asyncio/petstore_api/configuration.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,24 +13,23 @@ from __future__ import absolute_import -import urllib3 - import copy import logging import multiprocessing import sys +import urllib3 -from six import iteritems -from six import with_metaclass +import six from six.moves import http_client as httplib + class TypeWithDefault(type): def __init__(cls, name, bases, dct): super(TypeWithDefault, cls).__init__(name, bases, dct) cls._default = None def __call__(cls): - if cls._default == None: + if cls._default is None: cls._default = type.__call__(cls) return copy.copy(cls._default) @@ -38,17 +37,15 @@ class TypeWithDefault(type): cls._default = copy.copy(default) -class Configuration(with_metaclass(TypeWithDefault, object)): - """ - NOTE: This class is auto generated by the swagger code generator program. +class Configuration(six.with_metaclass(TypeWithDefault, object)): + """NOTE: This class is auto generated by the swagger code generator program. + Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. """ def __init__(self): - """ - Constructor - """ + """Constructor""" # Default Base url self.host = "http://petstore.swagger.io:80/v2" # Temp file folder for downloading files @@ -83,7 +80,8 @@ class Configuration(with_metaclass(TypeWithDefault, object)): self.debug = False # SSL/TLS verification - # Set this to false to skip verifying SSL certificate when calling API from https server. + # Set this to false to skip verifying SSL certificate when calling API + # from https server. self.verify_ssl = True # Set this to customize the certificate file to verify the peer. self.ssl_ca_cert = None @@ -101,7 +99,6 @@ class Configuration(with_metaclass(TypeWithDefault, object)): # cpu_count * 5 is used as default value to increase performance. self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - # Proxy URL self.proxy = None # Safe chars for path_param @@ -109,18 +106,22 @@ class Configuration(with_metaclass(TypeWithDefault, object)): @property def logger_file(self): - """ - Gets the logger_file. + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str """ return self.__logger_file @logger_file.setter def logger_file(self, value): - """ - Sets the logger_file. + """The logger file. - If the logger_file is None, then add stream handler and remove file handler. - Otherwise, add file handler and remove stream handler. + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. :param value: The logger_file path. :type: str @@ -131,7 +132,7 @@ class Configuration(with_metaclass(TypeWithDefault, object)): # then add file handler and remove stream handler. self.logger_file_handler = logging.FileHandler(self.__logger_file) self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.addHandler(self.logger_file_handler) if self.logger_stream_handler: logger.removeHandler(self.logger_stream_handler) @@ -140,22 +141,23 @@ class Configuration(with_metaclass(TypeWithDefault, object)): # then add stream handler and remove file handler. self.logger_stream_handler = logging.StreamHandler() self.logger_stream_handler.setFormatter(self.logger_formatter) - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.addHandler(self.logger_stream_handler) if self.logger_file_handler: logger.removeHandler(self.logger_file_handler) @property def debug(self): - """ - Gets the debug status. + """Debug status + + :param value: The debug status, True or False. + :type: bool """ return self.__debug @debug.setter def debug(self, value): - """ - Sets the debug status. + """Debug status :param value: The debug status, True or False. :type: bool @@ -163,29 +165,32 @@ class Configuration(with_metaclass(TypeWithDefault, object)): self.__debug = value if self.__debug: # if debug status is True, turn on debug logging - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.setLevel(logging.DEBUG) # turn on httplib debug httplib.HTTPConnection.debuglevel = 1 else: # if debug status is False, turn off debug logging, # setting log level to default `logging.WARNING` - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.setLevel(logging.WARNING) # turn off httplib debug httplib.HTTPConnection.debuglevel = 0 @property def logger_format(self): - """ - Gets the logger_format. + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str """ return self.__logger_format @logger_format.setter def logger_format(self, value): - """ - Sets the logger_format. + """The logger format. The logger_formatter will be updated when sets logger_format. @@ -196,29 +201,28 @@ class Configuration(with_metaclass(TypeWithDefault, object)): self.logger_formatter = logging.Formatter(self.__logger_format) def get_api_key_with_prefix(self, identifier): - """ - Gets API key (with prefix if set). + """Gets API key (with prefix if set). :param identifier: The identifier of apiKey. :return: The token for api key authentication. """ - if self.api_key.get(identifier) and self.api_key_prefix.get(identifier): - return self.api_key_prefix[identifier] + ' ' + self.api_key[identifier] + if (self.api_key.get(identifier) and + self.api_key_prefix.get(identifier)): + return self.api_key_prefix[identifier] + ' ' + self.api_key[identifier] # noqa: E501 elif self.api_key.get(identifier): return self.api_key[identifier] def get_basic_auth_token(self): - """ - Gets HTTP basic authentication header (string). + """Gets HTTP basic authentication header (string). :return: The token for basic HTTP authentication. """ - return urllib3.util.make_headers(basic_auth=self.username + ':' + self.password)\ - .get('authorization') + return urllib3.util.make_headers( + basic_auth=self.username + ':' + self.password + ).get('authorization') def auth_settings(self): - """ - Gets Auth Settings dict for api client. + """Gets Auth Settings dict for api client. :return: The Auth Settings information dict. """ @@ -256,8 +260,7 @@ class Configuration(with_metaclass(TypeWithDefault, object)): } def to_debug_report(self): - """ - Gets the essential information for debugging. + """Gets the essential information for debugging. :return: The report for debugging. """ diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/__init__.py b/samples/client/petstore/python-asyncio/petstore_api/models/__init__.py index 21b5d20fa3c..7b339102f9b 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/__init__.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/__init__.py @@ -1,9 +1,10 @@ # coding: utf-8 +# flake8: noqa """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -14,39 +15,39 @@ 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_of_array_of_number_only import ArrayOfArrayOfNumberOnly -from .array_of_number_only import ArrayOfNumberOnly -from .array_test import ArrayTest -from .capitalization import Capitalization -from .category import Category -from .class_model import ClassModel -from .client import Client -from .enum_arrays import EnumArrays -from .enum_class import EnumClass -from .enum_test import EnumTest -from .format_test import FormatTest -from .has_only_read_only import HasOnlyReadOnly -from .list import List -from .map_test import MapTest -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 .number_only import NumberOnly -from .order import Order -from .outer_boolean import OuterBoolean -from .outer_composite import OuterComposite -from .outer_enum import OuterEnum -from .outer_number import OuterNumber -from .outer_string import OuterString -from .pet import Pet -from .read_only_first import ReadOnlyFirst -from .special_model_name import SpecialModelName -from .tag import Tag -from .user import User -from .cat import Cat -from .dog import Dog +from petstore_api.models.additional_properties_class import AdditionalPropertiesClass +from petstore_api.models.animal import Animal +from petstore_api.models.animal_farm import AnimalFarm +from petstore_api.models.api_response import ApiResponse +from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly +from petstore_api.models.array_of_number_only import ArrayOfNumberOnly +from petstore_api.models.array_test import ArrayTest +from petstore_api.models.capitalization import Capitalization +from petstore_api.models.category import Category +from petstore_api.models.class_model import ClassModel +from petstore_api.models.client import Client +from petstore_api.models.enum_arrays import EnumArrays +from petstore_api.models.enum_class import EnumClass +from petstore_api.models.enum_test import EnumTest +from petstore_api.models.format_test import FormatTest +from petstore_api.models.has_only_read_only import HasOnlyReadOnly +from petstore_api.models.list import List +from petstore_api.models.map_test import MapTest +from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass +from petstore_api.models.model_200_response import Model200Response +from petstore_api.models.model_return import ModelReturn +from petstore_api.models.name import Name +from petstore_api.models.number_only import NumberOnly +from petstore_api.models.order import Order +from petstore_api.models.outer_boolean import OuterBoolean +from petstore_api.models.outer_composite import OuterComposite +from petstore_api.models.outer_enum import OuterEnum +from petstore_api.models.outer_number import OuterNumber +from petstore_api.models.outer_string import OuterString +from petstore_api.models.pet import Pet +from petstore_api.models.read_only_first import ReadOnlyFirst +from petstore_api.models.special_model_name import SpecialModelName +from petstore_api.models.tag import Tag +from petstore_api.models.user import User +from petstore_api.models.cat import Cat +from petstore_api.models.dog import Dog diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_class.py b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_class.py index a5329b411cd..03dbe975f1b 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_class.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_class.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class AdditionalPropertiesClass(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class AdditionalPropertiesClass(object): 'map_of_map_property': 'map_of_map_property' } - def __init__(self, map_property=None, map_of_map_property=None): - """ - AdditionalPropertiesClass - a model defined in Swagger - """ + def __init__(self, map_property=None, map_of_map_property=None): # noqa: E501 + """AdditionalPropertiesClass - a model defined in Swagger""" # noqa: E501 self._map_property = None self._map_of_map_property = None self.discriminator = None if map_property is not None: - self.map_property = map_property + self.map_property = map_property if map_of_map_property is not None: - self.map_of_map_property = map_of_map_property + self.map_of_map_property = map_of_map_property @property def map_property(self): - """ - Gets the map_property of this AdditionalPropertiesClass. + """Gets the map_property of this AdditionalPropertiesClass. # noqa: E501 - :return: The map_property of this AdditionalPropertiesClass. + + :return: The map_property of this AdditionalPropertiesClass. # noqa: E501 :rtype: dict(str, str) """ return self._map_property @map_property.setter def map_property(self, map_property): - """ - Sets the map_property of this AdditionalPropertiesClass. + """Sets the map_property of this AdditionalPropertiesClass. - :param map_property: The map_property of this AdditionalPropertiesClass. + + :param map_property: The map_property of this AdditionalPropertiesClass. # noqa: E501 :type: dict(str, str) """ @@ -77,32 +75,30 @@ class AdditionalPropertiesClass(object): @property def map_of_map_property(self): - """ - Gets the map_of_map_property of this AdditionalPropertiesClass. + """Gets the map_of_map_property of this AdditionalPropertiesClass. # noqa: E501 - :return: The map_of_map_property of this AdditionalPropertiesClass. + + :return: The map_of_map_property of this AdditionalPropertiesClass. # noqa: E501 :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. + """Sets the map_of_map_property of this AdditionalPropertiesClass. - :param map_of_map_property: The map_of_map_property of this AdditionalPropertiesClass. + + :param map_of_map_property: The map_of_map_property of this AdditionalPropertiesClass. # noqa: E501 :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 - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class AdditionalPropertiesClass(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, AdditionalPropertiesClass): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/animal.py b/samples/client/petstore/python-asyncio/petstore_api/models/animal.py index 13d8276713d..390ac83905e 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/animal.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/animal.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Animal(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -41,14 +41,12 @@ class Animal(object): } discriminator_value_class_map = { - '': 'Dog', - '': 'Cat' + 'Dog': 'Dog', + 'Cat': 'Cat' } - def __init__(self, class_name=None, color='red'): - """ - Animal - a model defined in Swagger - """ + def __init__(self, class_name=None, color='red'): # noqa: E501 + """Animal - a model defined in Swagger""" # noqa: E501 self._class_name = None self._color = None @@ -56,69 +54,62 @@ class Animal(object): self.class_name = class_name if color is not None: - self.color = color + self.color = color @property def class_name(self): - """ - Gets the class_name of this Animal. + """Gets the class_name of this Animal. # noqa: E501 - :return: The class_name of this Animal. + + :return: The class_name of this Animal. # noqa: E501 :rtype: str """ return self._class_name @class_name.setter def class_name(self, class_name): - """ - Sets the class_name of this Animal. + """Sets the class_name of this Animal. - :param class_name: The class_name of this Animal. + + :param class_name: The class_name of this Animal. # noqa: E501 :type: str """ if class_name is None: - raise ValueError("Invalid value for `class_name`, must not be `None`") + raise ValueError("Invalid value for `class_name`, must not be `None`") # noqa: E501 self._class_name = class_name @property def color(self): - """ - Gets the color of this Animal. + """Gets the color of this Animal. # noqa: E501 - :return: The color of this Animal. + + :return: The color of this Animal. # noqa: E501 :rtype: str """ return self._color @color.setter def color(self, color): - """ - Sets the color of this Animal. + """Sets the color of this Animal. - :param color: The color of this Animal. + + :param color: The color of this Animal. # noqa: E501 :type: str """ self._color = color def get_real_child_model(self, data): - """ - Returns the real base class specified by the discriminator - """ + """Returns the real base class specified by the discriminator""" discriminator_value = data[self.discriminator].lower() - if self.discriminator_value_class_map.has_key(discriminator_value): - return self.discriminator_value_class_map[discriminator_value] - else: - return None + return self.discriminator_value_class_map.get(discriminator_value) def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -139,28 +130,20 @@ class Animal(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Animal): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/animal_farm.py b/samples/client/petstore/python-asyncio/petstore_api/models/animal_farm.py index fa47d63f881..6371257286e 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/animal_farm.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/animal_farm.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.animal import Animal # noqa: F401,E501 class AnimalFarm(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -31,28 +33,20 @@ class AnimalFarm(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - AnimalFarm - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """AnimalFarm - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -73,28 +67,20 @@ class AnimalFarm(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, AnimalFarm): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/api_response.py b/samples/client/petstore/python-asyncio/petstore_api/models/api_response.py index b2d784d8020..45c4831bb10 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/api_response.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/api_response.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ApiResponse(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -42,10 +42,8 @@ class ApiResponse(object): 'message': 'message' } - def __init__(self, code=None, type=None, message=None): - """ - ApiResponse - a model defined in Swagger - """ + def __init__(self, code=None, type=None, message=None): # noqa: E501 + """ApiResponse - a model defined in Swagger""" # noqa: E501 self._code = None self._type = None @@ -53,28 +51,28 @@ class ApiResponse(object): self.discriminator = None if code is not None: - self.code = code + self.code = code if type is not None: - self.type = type + self.type = type if message is not None: - self.message = message + self.message = message @property def code(self): - """ - Gets the code of this ApiResponse. + """Gets the code of this ApiResponse. # noqa: E501 - :return: The code of this ApiResponse. + + :return: The code of this ApiResponse. # noqa: E501 :rtype: int """ return self._code @code.setter def code(self, code): - """ - Sets the code of this ApiResponse. + """Sets the code of this ApiResponse. - :param code: The code of this ApiResponse. + + :param code: The code of this ApiResponse. # noqa: E501 :type: int """ @@ -82,20 +80,20 @@ class ApiResponse(object): @property def type(self): - """ - Gets the type of this ApiResponse. + """Gets the type of this ApiResponse. # noqa: E501 - :return: The type of this ApiResponse. + + :return: The type of this ApiResponse. # noqa: E501 :rtype: str """ return self._type @type.setter def type(self, type): - """ - Sets the type of this ApiResponse. + """Sets the type of this ApiResponse. - :param type: The type of this ApiResponse. + + :param type: The type of this ApiResponse. # noqa: E501 :type: str """ @@ -103,32 +101,30 @@ class ApiResponse(object): @property def message(self): - """ - Gets the message of this ApiResponse. + """Gets the message of this ApiResponse. # noqa: E501 - :return: The message of this ApiResponse. + + :return: The message of this ApiResponse. # noqa: E501 :rtype: str """ return self._message @message.setter def message(self, message): - """ - Sets the message of this ApiResponse. + """Sets the message of this ApiResponse. - :param message: The message of this ApiResponse. + + :param message: The message of this ApiResponse. # noqa: E501 :type: str """ self._message = message def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -149,28 +145,20 @@ class ApiResponse(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ApiResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/array_of_array_of_number_only.py b/samples/client/petstore/python-asyncio/petstore_api/models/array_of_array_of_number_only.py index 0792f5a8a23..c6b363f19d8 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/array_of_array_of_number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ArrayOfArrayOfNumberOnly(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class ArrayOfArrayOfNumberOnly(object): 'array_array_number': 'ArrayArrayNumber' } - def __init__(self, array_array_number=None): - """ - ArrayOfArrayOfNumberOnly - a model defined in Swagger - """ + def __init__(self, array_array_number=None): # noqa: E501 + """ArrayOfArrayOfNumberOnly - a model defined in Swagger""" # noqa: E501 self._array_array_number = None self.discriminator = None if array_array_number is not None: - self.array_array_number = array_array_number + self.array_array_number = array_array_number @property def array_array_number(self): - """ - Gets the array_array_number of this ArrayOfArrayOfNumberOnly. + """Gets the array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501 - :return: The array_array_number of this ArrayOfArrayOfNumberOnly. + + :return: The array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501 :rtype: list[list[float]] """ return self._array_array_number @array_array_number.setter def array_array_number(self, array_array_number): - """ - Sets the array_array_number of this ArrayOfArrayOfNumberOnly. + """Sets the array_array_number of this ArrayOfArrayOfNumberOnly. - :param array_array_number: The array_array_number of this ArrayOfArrayOfNumberOnly. + + :param array_array_number: The array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501 :type: list[list[float]] """ self._array_array_number = array_array_number def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class ArrayOfArrayOfNumberOnly(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ArrayOfArrayOfNumberOnly): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/array_of_number_only.py b/samples/client/petstore/python-asyncio/petstore_api/models/array_of_number_only.py index 9d00e1b37a2..240362696cd 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/array_of_number_only.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/array_of_number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ArrayOfNumberOnly(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class ArrayOfNumberOnly(object): 'array_number': 'ArrayNumber' } - def __init__(self, array_number=None): - """ - ArrayOfNumberOnly - a model defined in Swagger - """ + def __init__(self, array_number=None): # noqa: E501 + """ArrayOfNumberOnly - a model defined in Swagger""" # noqa: E501 self._array_number = None self.discriminator = None if array_number is not None: - self.array_number = array_number + self.array_number = array_number @property def array_number(self): - """ - Gets the array_number of this ArrayOfNumberOnly. + """Gets the array_number of this ArrayOfNumberOnly. # noqa: E501 - :return: The array_number of this ArrayOfNumberOnly. + + :return: The array_number of this ArrayOfNumberOnly. # noqa: E501 :rtype: list[float] """ return self._array_number @array_number.setter def array_number(self, array_number): - """ - Sets the array_number of this ArrayOfNumberOnly. + """Sets the array_number of this ArrayOfNumberOnly. - :param array_number: The array_number of this ArrayOfNumberOnly. + + :param array_number: The array_number of this ArrayOfNumberOnly. # noqa: E501 :type: list[float] """ self._array_number = array_number def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class ArrayOfNumberOnly(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ArrayOfNumberOnly): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/array_test.py b/samples/client/petstore/python-asyncio/petstore_api/models/array_test.py index ac3079087c8..c5cd6bfe159 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/array_test.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/array_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.read_only_first import ReadOnlyFirst # noqa: F401,E501 class ArrayTest(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -42,10 +44,8 @@ class ArrayTest(object): 'array_array_of_model': 'array_array_of_model' } - def __init__(self, array_of_string=None, array_array_of_integer=None, array_array_of_model=None): - """ - ArrayTest - a model defined in Swagger - """ + def __init__(self, array_of_string=None, array_array_of_integer=None, array_array_of_model=None): # noqa: E501 + """ArrayTest - a model defined in Swagger""" # noqa: E501 self._array_of_string = None self._array_array_of_integer = None @@ -53,28 +53,28 @@ class ArrayTest(object): self.discriminator = None if array_of_string is not None: - self.array_of_string = array_of_string + self.array_of_string = array_of_string if array_array_of_integer is not None: - self.array_array_of_integer = array_array_of_integer + self.array_array_of_integer = array_array_of_integer if array_array_of_model is not None: - self.array_array_of_model = array_array_of_model + self.array_array_of_model = array_array_of_model @property def array_of_string(self): - """ - Gets the array_of_string of this ArrayTest. + """Gets the array_of_string of this ArrayTest. # noqa: E501 - :return: The array_of_string of this ArrayTest. + + :return: The array_of_string of this ArrayTest. # noqa: E501 :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. + """Sets the array_of_string of this ArrayTest. - :param array_of_string: The array_of_string of this ArrayTest. + + :param array_of_string: The array_of_string of this ArrayTest. # noqa: E501 :type: list[str] """ @@ -82,20 +82,20 @@ class ArrayTest(object): @property def array_array_of_integer(self): - """ - Gets the array_array_of_integer of this ArrayTest. + """Gets the array_array_of_integer of this ArrayTest. # noqa: E501 - :return: The array_array_of_integer of this ArrayTest. + + :return: The array_array_of_integer of this ArrayTest. # noqa: E501 :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. + """Sets the array_array_of_integer of this ArrayTest. - :param array_array_of_integer: The array_array_of_integer of this ArrayTest. + + :param array_array_of_integer: The array_array_of_integer of this ArrayTest. # noqa: E501 :type: list[list[int]] """ @@ -103,32 +103,30 @@ class ArrayTest(object): @property def array_array_of_model(self): - """ - Gets the array_array_of_model of this ArrayTest. + """Gets the array_array_of_model of this ArrayTest. # noqa: E501 - :return: The array_array_of_model of this ArrayTest. + + :return: The array_array_of_model of this ArrayTest. # noqa: E501 :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. + """Sets the array_array_of_model of this ArrayTest. - :param array_array_of_model: The array_array_of_model of this ArrayTest. + + :param array_array_of_model: The array_array_of_model of this ArrayTest. # noqa: E501 :type: list[list[ReadOnlyFirst]] """ self._array_array_of_model = array_array_of_model def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -149,28 +147,20 @@ class ArrayTest(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ArrayTest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/capitalization.py b/samples/client/petstore/python-asyncio/petstore_api/models/capitalization.py index c9be6ed4d15..309642bdeff 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/capitalization.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/capitalization.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Capitalization(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -48,10 +48,8 @@ class Capitalization(object): 'att_name': 'ATT_NAME' } - def __init__(self, small_camel=None, capital_camel=None, small_snake=None, capital_snake=None, sca_eth_flow_points=None, att_name=None): - """ - Capitalization - a model defined in Swagger - """ + def __init__(self, small_camel=None, capital_camel=None, small_snake=None, capital_snake=None, sca_eth_flow_points=None, att_name=None): # noqa: E501 + """Capitalization - a model defined in Swagger""" # noqa: E501 self._small_camel = None self._capital_camel = None @@ -62,34 +60,34 @@ class Capitalization(object): self.discriminator = None if small_camel is not None: - self.small_camel = small_camel + self.small_camel = small_camel if capital_camel is not None: - self.capital_camel = capital_camel + self.capital_camel = capital_camel if small_snake is not None: - self.small_snake = small_snake + self.small_snake = small_snake if capital_snake is not None: - self.capital_snake = capital_snake + self.capital_snake = capital_snake if sca_eth_flow_points is not None: - self.sca_eth_flow_points = sca_eth_flow_points + self.sca_eth_flow_points = sca_eth_flow_points if att_name is not None: - self.att_name = att_name + self.att_name = att_name @property def small_camel(self): - """ - Gets the small_camel of this Capitalization. + """Gets the small_camel of this Capitalization. # noqa: E501 - :return: The small_camel of this Capitalization. + + :return: The small_camel of this Capitalization. # noqa: E501 :rtype: str """ return self._small_camel @small_camel.setter def small_camel(self, small_camel): - """ - Sets the small_camel of this Capitalization. + """Sets the small_camel of this Capitalization. - :param small_camel: The small_camel of this Capitalization. + + :param small_camel: The small_camel of this Capitalization. # noqa: E501 :type: str """ @@ -97,20 +95,20 @@ class Capitalization(object): @property def capital_camel(self): - """ - Gets the capital_camel of this Capitalization. + """Gets the capital_camel of this Capitalization. # noqa: E501 - :return: The capital_camel of this Capitalization. + + :return: The capital_camel of this Capitalization. # noqa: E501 :rtype: str """ return self._capital_camel @capital_camel.setter def capital_camel(self, capital_camel): - """ - Sets the capital_camel of this Capitalization. + """Sets the capital_camel of this Capitalization. - :param capital_camel: The capital_camel of this Capitalization. + + :param capital_camel: The capital_camel of this Capitalization. # noqa: E501 :type: str """ @@ -118,20 +116,20 @@ class Capitalization(object): @property def small_snake(self): - """ - Gets the small_snake of this Capitalization. + """Gets the small_snake of this Capitalization. # noqa: E501 - :return: The small_snake of this Capitalization. + + :return: The small_snake of this Capitalization. # noqa: E501 :rtype: str """ return self._small_snake @small_snake.setter def small_snake(self, small_snake): - """ - Sets the small_snake of this Capitalization. + """Sets the small_snake of this Capitalization. - :param small_snake: The small_snake of this Capitalization. + + :param small_snake: The small_snake of this Capitalization. # noqa: E501 :type: str """ @@ -139,20 +137,20 @@ class Capitalization(object): @property def capital_snake(self): - """ - Gets the capital_snake of this Capitalization. + """Gets the capital_snake of this Capitalization. # noqa: E501 - :return: The capital_snake of this Capitalization. + + :return: The capital_snake of this Capitalization. # noqa: E501 :rtype: str """ return self._capital_snake @capital_snake.setter def capital_snake(self, capital_snake): - """ - Sets the capital_snake of this Capitalization. + """Sets the capital_snake of this Capitalization. - :param capital_snake: The capital_snake of this Capitalization. + + :param capital_snake: The capital_snake of this Capitalization. # noqa: E501 :type: str """ @@ -160,20 +158,20 @@ class Capitalization(object): @property def sca_eth_flow_points(self): - """ - Gets the sca_eth_flow_points of this Capitalization. + """Gets the sca_eth_flow_points of this Capitalization. # noqa: E501 - :return: The sca_eth_flow_points of this Capitalization. + + :return: The sca_eth_flow_points of this Capitalization. # noqa: E501 :rtype: str """ return self._sca_eth_flow_points @sca_eth_flow_points.setter def sca_eth_flow_points(self, sca_eth_flow_points): - """ - Sets the sca_eth_flow_points of this Capitalization. + """Sets the sca_eth_flow_points of this Capitalization. - :param sca_eth_flow_points: The sca_eth_flow_points of this Capitalization. + + :param sca_eth_flow_points: The sca_eth_flow_points of this Capitalization. # noqa: E501 :type: str """ @@ -181,34 +179,32 @@ class Capitalization(object): @property def att_name(self): - """ - Gets the att_name of this Capitalization. - Name of the pet + """Gets the att_name of this Capitalization. # noqa: E501 - :return: The att_name of this Capitalization. + Name of the pet # noqa: E501 + + :return: The att_name of this Capitalization. # noqa: E501 :rtype: str """ return self._att_name @att_name.setter def att_name(self, att_name): - """ - Sets the att_name of this Capitalization. - Name of the pet + """Sets the att_name of this Capitalization. - :param att_name: The att_name of this Capitalization. + Name of the pet # noqa: E501 + + :param att_name: The att_name of this Capitalization. # noqa: E501 :type: str """ self._att_name = att_name def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -229,28 +225,20 @@ class Capitalization(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Capitalization): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/cat.py b/samples/client/petstore/python-asyncio/petstore_api/models/cat.py index 76dfdc0e5b1..526d3e2aaf5 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/cat.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/cat.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.animal import Animal # noqa: F401,E501 class Cat(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +40,41 @@ class Cat(object): 'declawed': 'declawed' } - def __init__(self, declawed=None): - """ - Cat - a model defined in Swagger - """ + def __init__(self, declawed=None): # noqa: E501 + """Cat - a model defined in Swagger""" # noqa: E501 self._declawed = None self.discriminator = None if declawed is not None: - self.declawed = declawed + self.declawed = declawed @property def declawed(self): - """ - Gets the declawed of this Cat. + """Gets the declawed of this Cat. # noqa: E501 - :return: The declawed of this Cat. + + :return: The declawed of this Cat. # noqa: E501 :rtype: bool """ return self._declawed @declawed.setter def declawed(self, declawed): - """ - Sets the declawed of this Cat. + """Sets the declawed of this Cat. - :param declawed: The declawed of this Cat. + + :param declawed: The declawed of this Cat. # noqa: E501 :type: bool """ self._declawed = declawed def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +95,20 @@ class Cat(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Cat): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/category.py b/samples/client/petstore/python-asyncio/petstore_api/models/category.py index 859283a3f77..02d393af888 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/category.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/category.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Category(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class Category(object): 'name': 'name' } - def __init__(self, id=None, name=None): - """ - Category - a model defined in Swagger - """ + def __init__(self, id=None, name=None): # noqa: E501 + """Category - a model defined in Swagger""" # noqa: E501 self._id = None self._name = None self.discriminator = None if id is not None: - self.id = id + self.id = id if name is not None: - self.name = name + self.name = name @property def id(self): - """ - Gets the id of this Category. + """Gets the id of this Category. # noqa: E501 - :return: The id of this Category. + + :return: The id of this Category. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): - """ - Sets the id of this Category. + """Sets the id of this Category. - :param id: The id of this Category. + + :param id: The id of this Category. # noqa: E501 :type: int """ @@ -77,32 +75,30 @@ class Category(object): @property def name(self): - """ - Gets the name of this Category. + """Gets the name of this Category. # noqa: E501 - :return: The name of this Category. + + :return: The name of this Category. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): - """ - Sets the name of this Category. + """Sets the name of this Category. - :param name: The name of this Category. + + :param name: The name of this Category. # noqa: E501 :type: str """ self._name = name def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class Category(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Category): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/class_model.py b/samples/client/petstore/python-asyncio/petstore_api/models/class_model.py index 7b39d38abe9..4bcb19b8dc2 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/class_model.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/class_model.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ClassModel(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class ClassModel(object): '_class': '_class' } - def __init__(self, _class=None): - """ - ClassModel - a model defined in Swagger - """ + def __init__(self, _class=None): # noqa: E501 + """ClassModel - a model defined in Swagger""" # noqa: E501 self.__class = None self.discriminator = None if _class is not None: - self._class = _class + self._class = _class @property def _class(self): - """ - Gets the _class of this ClassModel. + """Gets the _class of this ClassModel. # noqa: E501 - :return: The _class of this ClassModel. + + :return: The _class of this ClassModel. # noqa: E501 :rtype: str """ return self.__class @_class.setter def _class(self, _class): - """ - Sets the _class of this ClassModel. + """Sets the _class of this ClassModel. - :param _class: The _class of this ClassModel. + + :param _class: The _class of this ClassModel. # noqa: E501 :type: str """ self.__class = _class def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class ClassModel(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ClassModel): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/client.py b/samples/client/petstore/python-asyncio/petstore_api/models/client.py index 395f77913cc..e267fed6d8c 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/client.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/client.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Client(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class Client(object): 'client': 'client' } - def __init__(self, client=None): - """ - Client - a model defined in Swagger - """ + def __init__(self, client=None): # noqa: E501 + """Client - a model defined in Swagger""" # noqa: E501 self._client = None self.discriminator = None if client is not None: - self.client = client + self.client = client @property def client(self): - """ - Gets the client of this Client. + """Gets the client of this Client. # noqa: E501 - :return: The client of this Client. + + :return: The client of this Client. # noqa: E501 :rtype: str """ return self._client @client.setter def client(self, client): - """ - Sets the client of this Client. + """Sets the client of this Client. - :param client: The client of this Client. + + :param client: The client of this Client. # noqa: E501 :type: str """ self._client = client def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class Client(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Client): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/dog.py b/samples/client/petstore/python-asyncio/petstore_api/models/dog.py index 3c159ad0d6f..34aac6aaad4 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/dog.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/dog.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.animal import Animal # noqa: F401,E501 class Dog(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +40,41 @@ class Dog(object): 'breed': 'breed' } - def __init__(self, breed=None): - """ - Dog - a model defined in Swagger - """ + def __init__(self, breed=None): # noqa: E501 + """Dog - a model defined in Swagger""" # noqa: E501 self._breed = None self.discriminator = None if breed is not None: - self.breed = breed + self.breed = breed @property def breed(self): - """ - Gets the breed of this Dog. + """Gets the breed of this Dog. # noqa: E501 - :return: The breed of this Dog. + + :return: The breed of this Dog. # noqa: E501 :rtype: str """ return self._breed @breed.setter def breed(self, breed): - """ - Sets the breed of this Dog. + """Sets the breed of this Dog. - :param breed: The breed of this Dog. + + :param breed: The breed of this Dog. # noqa: E501 :type: str """ self._breed = breed def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +95,20 @@ class Dog(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Dog): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/enum_arrays.py b/samples/client/petstore/python-asyncio/petstore_api/models/enum_arrays.py index 893085ea235..d02be298d2f 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/enum_arrays.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/enum_arrays.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class EnumArrays(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,42 +40,40 @@ class EnumArrays(object): 'array_enum': 'array_enum' } - def __init__(self, just_symbol=None, array_enum=None): - """ - EnumArrays - a model defined in Swagger - """ + def __init__(self, just_symbol=None, array_enum=None): # noqa: E501 + """EnumArrays - a model defined in Swagger""" # noqa: E501 self._just_symbol = None self._array_enum = None self.discriminator = None if just_symbol is not None: - self.just_symbol = just_symbol + self.just_symbol = just_symbol if array_enum is not None: - self.array_enum = array_enum + self.array_enum = array_enum @property def just_symbol(self): - """ - Gets the just_symbol of this EnumArrays. + """Gets the just_symbol of this EnumArrays. # noqa: E501 - :return: The just_symbol of this EnumArrays. + + :return: The just_symbol of this EnumArrays. # noqa: E501 :rtype: str """ return self._just_symbol @just_symbol.setter def just_symbol(self, just_symbol): - """ - Sets the just_symbol of this EnumArrays. + """Sets the just_symbol of this EnumArrays. - :param just_symbol: The just_symbol of this EnumArrays. + + :param just_symbol: The just_symbol of this EnumArrays. # noqa: E501 :type: str """ - allowed_values = [">=", "$"] + allowed_values = [">=", "$"] # noqa: E501 if just_symbol not in allowed_values: raise ValueError( - "Invalid value for `just_symbol` ({0}), must be one of {1}" + "Invalid value for `just_symbol` ({0}), must be one of {1}" # noqa: E501 .format(just_symbol, allowed_values) ) @@ -83,39 +81,37 @@ class EnumArrays(object): @property def array_enum(self): - """ - Gets the array_enum of this EnumArrays. + """Gets the array_enum of this EnumArrays. # noqa: E501 - :return: The array_enum of this EnumArrays. + + :return: The array_enum of this EnumArrays. # noqa: E501 :rtype: list[str] """ return self._array_enum @array_enum.setter def array_enum(self, array_enum): - """ - Sets the array_enum of this EnumArrays. + """Sets the array_enum of this EnumArrays. - :param array_enum: The array_enum of this EnumArrays. + + :param array_enum: The array_enum of this EnumArrays. # noqa: E501 :type: list[str] """ - allowed_values = ["fish", "crab"] + allowed_values = ["fish", "crab"] # noqa: E501 if not set(array_enum).issubset(set(allowed_values)): raise ValueError( - "Invalid values for `array_enum` [{0}], must be a subset of [{1}]" - .format(", ".join(map(str, set(array_enum)-set(allowed_values))), + "Invalid values for `array_enum` [{0}], must be a subset of [{1}]" # noqa: E501 + .format(", ".join(map(str, set(array_enum) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._array_enum = array_enum def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -136,28 +132,20 @@ class EnumArrays(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, EnumArrays): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/enum_class.py b/samples/client/petstore/python-asyncio/petstore_api/models/enum_class.py index d9e0b771a7d..e4721545e83 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/enum_class.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/enum_class.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,14 +11,15 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class EnumClass(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ @@ -37,28 +38,20 @@ class EnumClass(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - EnumClass - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """EnumClass - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -79,28 +72,20 @@ class EnumClass(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, EnumClass): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/enum_test.py b/samples/client/petstore/python-asyncio/petstore_api/models/enum_test.py index 6d7caa1f4bc..1bb234764ab 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/enum_test.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/enum_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.outer_enum import OuterEnum # noqa: F401,E501 class EnumTest(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -44,10 +46,8 @@ class EnumTest(object): 'outer_enum': 'outerEnum' } - def __init__(self, enum_string=None, enum_integer=None, enum_number=None, outer_enum=None): - """ - EnumTest - a model defined in Swagger - """ + def __init__(self, enum_string=None, enum_integer=None, enum_number=None, outer_enum=None): # noqa: E501 + """EnumTest - a model defined in Swagger""" # noqa: E501 self._enum_string = None self._enum_integer = None @@ -56,36 +56,36 @@ class EnumTest(object): self.discriminator = None if enum_string is not None: - self.enum_string = enum_string + self.enum_string = enum_string if enum_integer is not None: - self.enum_integer = enum_integer + self.enum_integer = enum_integer if enum_number is not None: - self.enum_number = enum_number + self.enum_number = enum_number if outer_enum is not None: - self.outer_enum = outer_enum + self.outer_enum = outer_enum @property def enum_string(self): - """ - Gets the enum_string of this EnumTest. + """Gets the enum_string of this EnumTest. # noqa: E501 - :return: The enum_string of this EnumTest. + + :return: The enum_string of this EnumTest. # noqa: E501 :rtype: str """ return self._enum_string @enum_string.setter def enum_string(self, enum_string): - """ - Sets the enum_string of this EnumTest. + """Sets the enum_string of this EnumTest. - :param enum_string: The enum_string of this EnumTest. + + :param enum_string: The enum_string of this EnumTest. # noqa: E501 :type: str """ - allowed_values = ["UPPER", "lower", ""] + allowed_values = ["UPPER", "lower", ""] # noqa: E501 if enum_string not in allowed_values: raise ValueError( - "Invalid value for `enum_string` ({0}), must be one of {1}" + "Invalid value for `enum_string` ({0}), must be one of {1}" # noqa: E501 .format(enum_string, allowed_values) ) @@ -93,26 +93,26 @@ class EnumTest(object): @property def enum_integer(self): - """ - Gets the enum_integer of this EnumTest. + """Gets the enum_integer of this EnumTest. # noqa: E501 - :return: The enum_integer of this EnumTest. + + :return: The enum_integer of this EnumTest. # noqa: E501 :rtype: int """ return self._enum_integer @enum_integer.setter def enum_integer(self, enum_integer): - """ - Sets the enum_integer of this EnumTest. + """Sets the enum_integer of this EnumTest. - :param enum_integer: The enum_integer of this EnumTest. + + :param enum_integer: The enum_integer of this EnumTest. # noqa: E501 :type: int """ - allowed_values = [1, -1] + allowed_values = [1, -1] # noqa: E501 if enum_integer not in allowed_values: raise ValueError( - "Invalid value for `enum_integer` ({0}), must be one of {1}" + "Invalid value for `enum_integer` ({0}), must be one of {1}" # noqa: E501 .format(enum_integer, allowed_values) ) @@ -120,26 +120,26 @@ class EnumTest(object): @property def enum_number(self): - """ - Gets the enum_number of this EnumTest. + """Gets the enum_number of this EnumTest. # noqa: E501 - :return: The enum_number of this EnumTest. + + :return: The enum_number of this EnumTest. # noqa: E501 :rtype: float """ return self._enum_number @enum_number.setter def enum_number(self, enum_number): - """ - Sets the enum_number of this EnumTest. + """Sets the enum_number of this EnumTest. - :param enum_number: The enum_number of this EnumTest. + + :param enum_number: The enum_number of this EnumTest. # noqa: E501 :type: float """ - allowed_values = [1.1, -1.2] + allowed_values = [1.1, -1.2] # noqa: E501 if enum_number not in allowed_values: raise ValueError( - "Invalid value for `enum_number` ({0}), must be one of {1}" + "Invalid value for `enum_number` ({0}), must be one of {1}" # noqa: E501 .format(enum_number, allowed_values) ) @@ -147,32 +147,30 @@ class EnumTest(object): @property def outer_enum(self): - """ - Gets the outer_enum of this EnumTest. + """Gets the outer_enum of this EnumTest. # noqa: E501 - :return: The outer_enum of this EnumTest. + + :return: The outer_enum of this EnumTest. # noqa: E501 :rtype: OuterEnum """ return self._outer_enum @outer_enum.setter def outer_enum(self, outer_enum): - """ - Sets the outer_enum of this EnumTest. + """Sets the outer_enum of this EnumTest. - :param outer_enum: The outer_enum of this EnumTest. + + :param outer_enum: The outer_enum of this EnumTest. # noqa: E501 :type: OuterEnum """ self._outer_enum = outer_enum def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -193,28 +191,20 @@ class EnumTest(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, EnumTest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/format_test.py b/samples/client/petstore/python-asyncio/petstore_api/models/format_test.py index 139d1733b35..7974d732fda 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/format_test.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/format_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class FormatTest(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -62,10 +62,8 @@ class FormatTest(object): 'password': 'password' } - 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 - """ + 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): # noqa: E501 + """FormatTest - a model defined in Swagger""" # noqa: E501 self._integer = None self._int32 = None @@ -83,94 +81,94 @@ class FormatTest(object): self.discriminator = None if integer is not None: - self.integer = integer + self.integer = integer if int32 is not None: - self.int32 = int32 + self.int32 = int32 if int64 is not None: - self.int64 = int64 + self.int64 = int64 self.number = number if float is not None: - self.float = float + self.float = float if double is not None: - self.double = double + self.double = double if string is not None: - self.string = string + self.string = string self.byte = byte if binary is not None: - self.binary = binary + self.binary = binary self.date = date if date_time is not None: - self.date_time = date_time + self.date_time = date_time if uuid is not None: - self.uuid = uuid + self.uuid = uuid self.password = password @property def integer(self): - """ - Gets the integer of this FormatTest. + """Gets the integer of this FormatTest. # noqa: E501 - :return: The integer of this FormatTest. + + :return: The integer of this FormatTest. # noqa: E501 :rtype: int """ return self._integer @integer.setter def integer(self, integer): - """ - Sets the integer of this FormatTest. + """Sets the integer of this FormatTest. - :param integer: The integer of this FormatTest. + + :param integer: The integer of this FormatTest. # noqa: E501 :type: int """ - if integer is not None and integer > 100: - raise ValueError("Invalid value for `integer`, must be a value less than or equal to `100`") - if integer is not None and integer < 10: - raise ValueError("Invalid value for `integer`, must be a value greater than or equal to `10`") + if integer is not None and integer > 100: # noqa: E501 + raise ValueError("Invalid value for `integer`, must be a value less than or equal to `100`") # noqa: E501 + if integer is not None and integer < 10: # noqa: E501 + raise ValueError("Invalid value for `integer`, must be a value greater than or equal to `10`") # noqa: E501 self._integer = integer @property def int32(self): - """ - Gets the int32 of this FormatTest. + """Gets the int32 of this FormatTest. # noqa: E501 - :return: The int32 of this FormatTest. + + :return: The int32 of this FormatTest. # noqa: E501 :rtype: int """ return self._int32 @int32.setter def int32(self, int32): - """ - Sets the int32 of this FormatTest. + """Sets the int32 of this FormatTest. - :param int32: The int32 of this FormatTest. + + :param int32: The int32 of this FormatTest. # noqa: E501 :type: int """ - if int32 is not None and int32 > 200: - raise ValueError("Invalid value for `int32`, must be a value less than or equal to `200`") - if int32 is not None and int32 < 20: - raise ValueError("Invalid value for `int32`, must be a value greater than or equal to `20`") + if int32 is not None and int32 > 200: # noqa: E501 + raise ValueError("Invalid value for `int32`, must be a value less than or equal to `200`") # noqa: E501 + if int32 is not None and int32 < 20: # noqa: E501 + raise ValueError("Invalid value for `int32`, must be a value greater than or equal to `20`") # noqa: E501 self._int32 = int32 @property def int64(self): - """ - Gets the int64 of this FormatTest. + """Gets the int64 of this FormatTest. # noqa: E501 - :return: The int64 of this FormatTest. + + :return: The int64 of this FormatTest. # noqa: E501 :rtype: int """ return self._int64 @int64.setter def int64(self, int64): - """ - Sets the int64 of this FormatTest. + """Sets the int64 of this FormatTest. - :param int64: The int64 of this FormatTest. + + :param int64: The int64 of this FormatTest. # noqa: E501 :type: int """ @@ -178,145 +176,145 @@ class FormatTest(object): @property def number(self): - """ - Gets the number of this FormatTest. + """Gets the number of this FormatTest. # noqa: E501 - :return: The number of this FormatTest. + + :return: The number of this FormatTest. # noqa: E501 :rtype: float """ return self._number @number.setter def number(self, number): - """ - Sets the number of this FormatTest. + """Sets the number of this FormatTest. - :param number: The number of this FormatTest. + + :param number: The number of this FormatTest. # noqa: E501 :type: float """ if number is None: - raise ValueError("Invalid value for `number`, must not be `None`") - if number is not None and number > 543.2: - raise ValueError("Invalid value for `number`, must be a value less than or equal to `543.2`") - if number is not None and number < 32.1: - raise ValueError("Invalid value for `number`, must be a value greater than or equal to `32.1`") + raise ValueError("Invalid value for `number`, must not be `None`") # noqa: E501 + if number is not None and number > 543.2: # noqa: E501 + raise ValueError("Invalid value for `number`, must be a value less than or equal to `543.2`") # noqa: E501 + if number is not None and number < 32.1: # noqa: E501 + raise ValueError("Invalid value for `number`, must be a value greater than or equal to `32.1`") # noqa: E501 self._number = number @property def float(self): - """ - Gets the float of this FormatTest. + """Gets the float of this FormatTest. # noqa: E501 - :return: The float of this FormatTest. + + :return: The float of this FormatTest. # noqa: E501 :rtype: float """ return self._float @float.setter def float(self, float): - """ - Sets the float of this FormatTest. + """Sets the float of this FormatTest. - :param float: The float of this FormatTest. + + :param float: The float of this FormatTest. # noqa: E501 :type: float """ - if float is not None and float > 987.6: - raise ValueError("Invalid value for `float`, must be a value less than or equal to `987.6`") - if float is not None and float < 54.3: - raise ValueError("Invalid value for `float`, must be a value greater than or equal to `54.3`") + if float is not None and float > 987.6: # noqa: E501 + raise ValueError("Invalid value for `float`, must be a value less than or equal to `987.6`") # noqa: E501 + if float is not None and float < 54.3: # noqa: E501 + raise ValueError("Invalid value for `float`, must be a value greater than or equal to `54.3`") # noqa: E501 self._float = float @property def double(self): - """ - Gets the double of this FormatTest. + """Gets the double of this FormatTest. # noqa: E501 - :return: The double of this FormatTest. + + :return: The double of this FormatTest. # noqa: E501 :rtype: float """ return self._double @double.setter def double(self, double): - """ - Sets the double of this FormatTest. + """Sets the double of this FormatTest. - :param double: The double of this FormatTest. + + :param double: The double of this FormatTest. # noqa: E501 :type: float """ - if double is not None and double > 123.4: - raise ValueError("Invalid value for `double`, must be a value less than or equal to `123.4`") - if double is not None and double < 67.8: - raise ValueError("Invalid value for `double`, must be a value greater than or equal to `67.8`") + if double is not None and double > 123.4: # noqa: E501 + raise ValueError("Invalid value for `double`, must be a value less than or equal to `123.4`") # noqa: E501 + if double is not None and double < 67.8: # noqa: E501 + raise ValueError("Invalid value for `double`, must be a value greater than or equal to `67.8`") # noqa: E501 self._double = double @property def string(self): - """ - Gets the string of this FormatTest. + """Gets the string of this FormatTest. # noqa: E501 - :return: The string of this FormatTest. + + :return: The string of this FormatTest. # noqa: E501 :rtype: str """ return self._string @string.setter def string(self, string): - """ - Sets the string of this FormatTest. + """Sets the string of this FormatTest. - :param string: The string of this FormatTest. + + :param string: The string of this FormatTest. # noqa: E501 :type: str """ - if string is not None and 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`") + if string is not None and not re.search('[a-z]', string, flags=re.IGNORECASE): # noqa: E501 + raise ValueError("Invalid value for `string`, must be a follow pattern or equal to `/[a-z]/i`") # noqa: E501 self._string = string @property def byte(self): - """ - Gets the byte of this FormatTest. + """Gets the byte of this FormatTest. # noqa: E501 - :return: The byte of this FormatTest. + + :return: The byte of this FormatTest. # noqa: E501 :rtype: str """ return self._byte @byte.setter def byte(self, byte): - """ - Sets the byte of this FormatTest. + """Sets the byte of this FormatTest. - :param byte: The byte of this FormatTest. + + :param byte: The byte of this FormatTest. # noqa: E501 :type: str """ if byte is None: - raise ValueError("Invalid value for `byte`, must not be `None`") - if byte is not None and not re.search('^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', byte): - raise ValueError("Invalid value for `byte`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") + raise ValueError("Invalid value for `byte`, must not be `None`") # noqa: E501 + if byte is not None and not re.search('^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', byte): # noqa: E501 + raise ValueError("Invalid value for `byte`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501 self._byte = byte @property def binary(self): - """ - Gets the binary of this FormatTest. + """Gets the binary of this FormatTest. # noqa: E501 - :return: The binary of this FormatTest. + + :return: The binary of this FormatTest. # noqa: E501 :rtype: str """ return self._binary @binary.setter def binary(self, binary): - """ - Sets the binary of this FormatTest. + """Sets the binary of this FormatTest. - :param binary: The binary of this FormatTest. + + :param binary: The binary of this FormatTest. # noqa: E501 :type: str """ @@ -324,43 +322,43 @@ class FormatTest(object): @property def date(self): - """ - Gets the date of this FormatTest. + """Gets the date of this FormatTest. # noqa: E501 - :return: The date of this FormatTest. + + :return: The date of this FormatTest. # noqa: E501 :rtype: date """ return self._date @date.setter def date(self, date): - """ - Sets the date of this FormatTest. + """Sets the date of this FormatTest. - :param date: The date of this FormatTest. + + :param date: The date of this FormatTest. # noqa: E501 :type: date """ if date is None: - raise ValueError("Invalid value for `date`, must not be `None`") + raise ValueError("Invalid value for `date`, must not be `None`") # noqa: E501 self._date = date @property def date_time(self): - """ - Gets the date_time of this FormatTest. + """Gets the date_time of this FormatTest. # noqa: E501 - :return: The date_time of this FormatTest. + + :return: The date_time of this FormatTest. # noqa: E501 :rtype: datetime """ return self._date_time @date_time.setter def date_time(self, date_time): - """ - Sets the date_time of this FormatTest. + """Sets the date_time of this FormatTest. - :param date_time: The date_time of this FormatTest. + + :param date_time: The date_time of this FormatTest. # noqa: E501 :type: datetime """ @@ -368,20 +366,20 @@ class FormatTest(object): @property def uuid(self): - """ - Gets the uuid of this FormatTest. + """Gets the uuid of this FormatTest. # noqa: E501 - :return: The uuid of this FormatTest. + + :return: The uuid of this FormatTest. # noqa: E501 :rtype: str """ return self._uuid @uuid.setter def uuid(self, uuid): - """ - Sets the uuid of this FormatTest. + """Sets the uuid of this FormatTest. - :param uuid: The uuid of this FormatTest. + + :param uuid: The uuid of this FormatTest. # noqa: E501 :type: str """ @@ -389,38 +387,36 @@ class FormatTest(object): @property def password(self): - """ - Gets the password of this FormatTest. + """Gets the password of this FormatTest. # noqa: E501 - :return: The password of this FormatTest. + + :return: The password of this FormatTest. # noqa: E501 :rtype: str """ return self._password @password.setter def password(self, password): - """ - Sets the password of this FormatTest. + """Sets the password of this FormatTest. - :param password: The password of this FormatTest. + + :param password: The password of this FormatTest. # noqa: E501 :type: str """ if password is None: - raise ValueError("Invalid value for `password`, must not be `None`") + raise ValueError("Invalid value for `password`, must not be `None`") # noqa: E501 if password is not None and len(password) > 64: - raise ValueError("Invalid value for `password`, length must be less than or equal to `64`") + raise ValueError("Invalid value for `password`, length must be less than or equal to `64`") # noqa: E501 if password is not None and len(password) < 10: - raise ValueError("Invalid value for `password`, length must be greater than or equal to `10`") + raise ValueError("Invalid value for `password`, length must be greater than or equal to `10`") # noqa: E501 self._password = password def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -441,28 +437,20 @@ class FormatTest(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, FormatTest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/has_only_read_only.py b/samples/client/petstore/python-asyncio/petstore_api/models/has_only_read_only.py index da0c14ec5b1..3c93eb30996 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/has_only_read_only.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/has_only_read_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class HasOnlyReadOnly(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class HasOnlyReadOnly(object): 'foo': 'foo' } - def __init__(self, bar=None, foo=None): - """ - HasOnlyReadOnly - a model defined in Swagger - """ + def __init__(self, bar=None, foo=None): # noqa: E501 + """HasOnlyReadOnly - a model defined in Swagger""" # noqa: E501 self._bar = None self._foo = None self.discriminator = None if bar is not None: - self.bar = bar + self.bar = bar if foo is not None: - self.foo = foo + self.foo = foo @property def bar(self): - """ - Gets the bar of this HasOnlyReadOnly. + """Gets the bar of this HasOnlyReadOnly. # noqa: E501 - :return: The bar of this HasOnlyReadOnly. + + :return: The bar of this HasOnlyReadOnly. # noqa: E501 :rtype: str """ return self._bar @bar.setter def bar(self, bar): - """ - Sets the bar of this HasOnlyReadOnly. + """Sets the bar of this HasOnlyReadOnly. - :param bar: The bar of this HasOnlyReadOnly. + + :param bar: The bar of this HasOnlyReadOnly. # noqa: E501 :type: str """ @@ -77,32 +75,30 @@ class HasOnlyReadOnly(object): @property def foo(self): - """ - Gets the foo of this HasOnlyReadOnly. + """Gets the foo of this HasOnlyReadOnly. # noqa: E501 - :return: The foo of this HasOnlyReadOnly. + + :return: The foo of this HasOnlyReadOnly. # noqa: E501 :rtype: str """ return self._foo @foo.setter def foo(self, foo): - """ - Sets the foo of this HasOnlyReadOnly. + """Sets the foo of this HasOnlyReadOnly. - :param foo: The foo of this HasOnlyReadOnly. + + :param foo: The foo of this HasOnlyReadOnly. # noqa: E501 :type: str """ self._foo = foo def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class HasOnlyReadOnly(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, HasOnlyReadOnly): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/list.py b/samples/client/petstore/python-asyncio/petstore_api/models/list.py index 2ac0e51fb12..fbe30e6d01e 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/list.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/list.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class List(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class List(object): '_123_list': '123-list' } - def __init__(self, _123_list=None): - """ - List - a model defined in Swagger - """ + def __init__(self, _123_list=None): # noqa: E501 + """List - a model defined in Swagger""" # noqa: E501 self.__123_list = None self.discriminator = None if _123_list is not None: - self._123_list = _123_list + self._123_list = _123_list @property def _123_list(self): - """ - Gets the _123_list of this List. + """Gets the _123_list of this List. # noqa: E501 - :return: The _123_list of this List. + + :return: The _123_list of this List. # noqa: E501 :rtype: str """ return self.__123_list @_123_list.setter def _123_list(self, _123_list): - """ - Sets the _123_list of this List. + """Sets the _123_list of this List. - :param _123_list: The _123_list of this List. + + :param _123_list: The _123_list of this List. # noqa: E501 :type: str """ self.__123_list = _123_list def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class List(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, List): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/map_test.py b/samples/client/petstore/python-asyncio/petstore_api/models/map_test.py index 3cb936e0db8..374c0661ba5 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/map_test.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/map_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class MapTest(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class MapTest(object): 'map_of_enum_string': 'map_of_enum_string' } - def __init__(self, map_map_of_string=None, map_of_enum_string=None): - """ - MapTest - a model defined in Swagger - """ + def __init__(self, map_map_of_string=None, map_of_enum_string=None): # noqa: E501 + """MapTest - a model defined in Swagger""" # noqa: E501 self._map_map_of_string = None self._map_of_enum_string = None self.discriminator = None if map_map_of_string is not None: - self.map_map_of_string = map_map_of_string + self.map_map_of_string = map_map_of_string if map_of_enum_string is not None: - self.map_of_enum_string = map_of_enum_string + self.map_of_enum_string = map_of_enum_string @property def map_map_of_string(self): - """ - Gets the map_map_of_string of this MapTest. + """Gets the map_map_of_string of this MapTest. # noqa: E501 - :return: The map_map_of_string of this MapTest. + + :return: The map_map_of_string of this MapTest. # noqa: E501 :rtype: dict(str, dict(str, str)) """ return self._map_map_of_string @map_map_of_string.setter def map_map_of_string(self, map_map_of_string): - """ - Sets the map_map_of_string of this MapTest. + """Sets the map_map_of_string of this MapTest. - :param map_map_of_string: The map_map_of_string of this MapTest. + + :param map_map_of_string: The map_map_of_string of this MapTest. # noqa: E501 :type: dict(str, dict(str, str)) """ @@ -77,39 +75,37 @@ class MapTest(object): @property def map_of_enum_string(self): - """ - Gets the map_of_enum_string of this MapTest. + """Gets the map_of_enum_string of this MapTest. # noqa: E501 - :return: The map_of_enum_string of this MapTest. + + :return: The map_of_enum_string of this MapTest. # noqa: E501 :rtype: dict(str, str) """ return self._map_of_enum_string @map_of_enum_string.setter def map_of_enum_string(self, map_of_enum_string): - """ - Sets the map_of_enum_string of this MapTest. + """Sets the map_of_enum_string of this MapTest. - :param map_of_enum_string: The map_of_enum_string of this MapTest. + + :param map_of_enum_string: The map_of_enum_string of this MapTest. # noqa: E501 :type: dict(str, str) """ - allowed_values = ["UPPER", "lower"] + allowed_values = ["UPPER", "lower"] # noqa: E501 if not set(map_of_enum_string.keys()).issubset(set(allowed_values)): raise ValueError( - "Invalid keys in `map_of_enum_string` [{0}], must be a subset of [{1}]" - .format(", ".join(map(str, set(map_of_enum_string.keys())-set(allowed_values))), + "Invalid keys in `map_of_enum_string` [{0}], must be a subset of [{1}]" # noqa: E501 + .format(", ".join(map(str, set(map_of_enum_string.keys()) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._map_of_enum_string = map_of_enum_string def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -130,28 +126,20 @@ class MapTest(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, MapTest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python-asyncio/petstore_api/models/mixed_properties_and_additional_properties_class.py index 4b773deacef..dba1f261352 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.animal import Animal # noqa: F401,E501 class MixedPropertiesAndAdditionalPropertiesClass(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -42,10 +44,8 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): 'map': 'map' } - def __init__(self, uuid=None, date_time=None, map=None): - """ - MixedPropertiesAndAdditionalPropertiesClass - a model defined in Swagger - """ + def __init__(self, uuid=None, date_time=None, map=None): # noqa: E501 + """MixedPropertiesAndAdditionalPropertiesClass - a model defined in Swagger""" # noqa: E501 self._uuid = None self._date_time = None @@ -53,28 +53,28 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): self.discriminator = None if uuid is not None: - self.uuid = uuid + self.uuid = uuid if date_time is not None: - self.date_time = date_time + self.date_time = date_time if map is not None: - self.map = map + self.map = map @property def uuid(self): - """ - Gets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. + """Gets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - :return: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. + + :return: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :rtype: str """ return self._uuid @uuid.setter def uuid(self, uuid): - """ - Sets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. + """Sets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. - :param uuid: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. + + :param uuid: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :type: str """ @@ -82,20 +82,20 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): @property def date_time(self): - """ - Gets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. + """Gets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - :return: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. + + :return: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :rtype: datetime """ return self._date_time @date_time.setter def date_time(self, date_time): - """ - Sets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. + """Sets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. - :param date_time: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. + + :param date_time: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :type: datetime """ @@ -103,32 +103,30 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): @property def map(self): - """ - Gets the map of this MixedPropertiesAndAdditionalPropertiesClass. + """Gets the map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - :return: The map of this MixedPropertiesAndAdditionalPropertiesClass. + + :return: The map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :rtype: dict(str, Animal) """ return self._map @map.setter def map(self, map): - """ - Sets the map of this MixedPropertiesAndAdditionalPropertiesClass. + """Sets the map of this MixedPropertiesAndAdditionalPropertiesClass. - :param map: The map of this MixedPropertiesAndAdditionalPropertiesClass. + + :param map: The map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :type: dict(str, Animal) """ self._map = map def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -149,28 +147,20 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, MixedPropertiesAndAdditionalPropertiesClass): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/model_200_response.py b/samples/client/petstore/python-asyncio/petstore_api/models/model_200_response.py index 2b6aeb090c0..60f9c96a676 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/model_200_response.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/model_200_response.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Model200Response(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class Model200Response(object): '_class': 'class' } - def __init__(self, name=None, _class=None): - """ - Model200Response - a model defined in Swagger - """ + def __init__(self, name=None, _class=None): # noqa: E501 + """Model200Response - a model defined in Swagger""" # noqa: E501 self._name = None self.__class = None self.discriminator = None if name is not None: - self.name = name + self.name = name if _class is not None: - self._class = _class + self._class = _class @property def name(self): - """ - Gets the name of this Model200Response. + """Gets the name of this Model200Response. # noqa: E501 - :return: The name of this Model200Response. + + :return: The name of this Model200Response. # noqa: E501 :rtype: int """ return self._name @name.setter def name(self, name): - """ - Sets the name of this Model200Response. + """Sets the name of this Model200Response. - :param name: The name of this Model200Response. + + :param name: The name of this Model200Response. # noqa: E501 :type: int """ @@ -77,32 +75,30 @@ class Model200Response(object): @property def _class(self): - """ - Gets the _class of this Model200Response. + """Gets the _class of this Model200Response. # noqa: E501 - :return: The _class of this Model200Response. + + :return: The _class of this Model200Response. # noqa: E501 :rtype: str """ return self.__class @_class.setter def _class(self, _class): - """ - Sets the _class of this Model200Response. + """Sets the _class of this Model200Response. - :param _class: The _class of this Model200Response. + + :param _class: The _class of this Model200Response. # noqa: E501 :type: str """ self.__class = _class def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class Model200Response(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Model200Response): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/model_return.py b/samples/client/petstore/python-asyncio/petstore_api/models/model_return.py index a2160d21dd1..c9d8b5682aa 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/model_return.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/model_return.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ModelReturn(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class ModelReturn(object): '_return': 'return' } - def __init__(self, _return=None): - """ - ModelReturn - a model defined in Swagger - """ + def __init__(self, _return=None): # noqa: E501 + """ModelReturn - a model defined in Swagger""" # noqa: E501 self.__return = None self.discriminator = None if _return is not None: - self._return = _return + self._return = _return @property def _return(self): - """ - Gets the _return of this ModelReturn. + """Gets the _return of this ModelReturn. # noqa: E501 - :return: The _return of this ModelReturn. + + :return: The _return of this ModelReturn. # noqa: E501 :rtype: int """ return self.__return @_return.setter def _return(self, _return): - """ - Sets the _return of this ModelReturn. + """Sets the _return of this ModelReturn. - :param _return: The _return of this ModelReturn. + + :param _return: The _return of this ModelReturn. # noqa: E501 :type: int """ self.__return = _return def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class ModelReturn(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ModelReturn): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/name.py b/samples/client/petstore/python-asyncio/petstore_api/models/name.py index 52b51890dde..cbfbddeb1ab 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/name.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/name.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Name(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -44,10 +44,8 @@ class Name(object): '_123_number': '123Number' } - def __init__(self, name=None, snake_case=None, _property=None, _123_number=None): - """ - Name - a model defined in Swagger - """ + def __init__(self, name=None, snake_case=None, _property=None, _123_number=None): # noqa: E501 + """Name - a model defined in Swagger""" # noqa: E501 self._name = None self._snake_case = None @@ -57,51 +55,51 @@ class Name(object): self.name = name if snake_case is not None: - self.snake_case = snake_case + self.snake_case = snake_case if _property is not None: - self._property = _property + self._property = _property if _123_number is not None: - self._123_number = _123_number + self._123_number = _123_number @property def name(self): - """ - Gets the name of this Name. + """Gets the name of this Name. # noqa: E501 - :return: The name of this Name. + + :return: The name of this Name. # noqa: E501 :rtype: int """ return self._name @name.setter def name(self, name): - """ - Sets the name of this Name. + """Sets the name of this Name. - :param name: The name of this Name. + + :param name: The name of this Name. # noqa: E501 :type: int """ if name is None: - raise ValueError("Invalid value for `name`, must not be `None`") + raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name @property def snake_case(self): - """ - Gets the snake_case of this Name. + """Gets the snake_case of this Name. # noqa: E501 - :return: The snake_case of this Name. + + :return: The snake_case of this Name. # noqa: E501 :rtype: int """ return self._snake_case @snake_case.setter def snake_case(self, snake_case): - """ - Sets the snake_case of this Name. + """Sets the snake_case of this Name. - :param snake_case: The snake_case of this Name. + + :param snake_case: The snake_case of this Name. # noqa: E501 :type: int """ @@ -109,20 +107,20 @@ class Name(object): @property def _property(self): - """ - Gets the _property of this Name. + """Gets the _property of this Name. # noqa: E501 - :return: The _property of this Name. + + :return: The _property of this Name. # noqa: E501 :rtype: str """ return self.__property @_property.setter def _property(self, _property): - """ - Sets the _property of this Name. + """Sets the _property of this Name. - :param _property: The _property of this Name. + + :param _property: The _property of this Name. # noqa: E501 :type: str """ @@ -130,32 +128,30 @@ class Name(object): @property def _123_number(self): - """ - Gets the _123_number of this Name. + """Gets the _123_number of this Name. # noqa: E501 - :return: The _123_number of this Name. + + :return: The _123_number of this Name. # noqa: E501 :rtype: int """ return self.__123_number @_123_number.setter def _123_number(self, _123_number): - """ - Sets the _123_number of this Name. + """Sets the _123_number of this Name. - :param _123_number: The _123_number of this Name. + + :param _123_number: The _123_number of this Name. # noqa: E501 :type: int """ self.__123_number = _123_number def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -176,28 +172,20 @@ class Name(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Name): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/number_only.py b/samples/client/petstore/python-asyncio/petstore_api/models/number_only.py index b0e279b53a5..b96321109b9 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/number_only.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class NumberOnly(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class NumberOnly(object): 'just_number': 'JustNumber' } - def __init__(self, just_number=None): - """ - NumberOnly - a model defined in Swagger - """ + def __init__(self, just_number=None): # noqa: E501 + """NumberOnly - a model defined in Swagger""" # noqa: E501 self._just_number = None self.discriminator = None if just_number is not None: - self.just_number = just_number + self.just_number = just_number @property def just_number(self): - """ - Gets the just_number of this NumberOnly. + """Gets the just_number of this NumberOnly. # noqa: E501 - :return: The just_number of this NumberOnly. + + :return: The just_number of this NumberOnly. # noqa: E501 :rtype: float """ return self._just_number @just_number.setter def just_number(self, just_number): - """ - Sets the just_number of this NumberOnly. + """Sets the just_number of this NumberOnly. - :param just_number: The just_number of this NumberOnly. + + :param just_number: The just_number of this NumberOnly. # noqa: E501 :type: float """ self._just_number = just_number def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class NumberOnly(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, NumberOnly): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/order.py b/samples/client/petstore/python-asyncio/petstore_api/models/order.py index 52c7b6c227e..6636542e941 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/order.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/order.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Order(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -48,10 +48,8 @@ class Order(object): 'complete': 'complete' } - def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=None, complete=False): - """ - Order - a model defined in Swagger - """ + def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=None, complete=False): # noqa: E501 + """Order - a model defined in Swagger""" # noqa: E501 self._id = None self._pet_id = None @@ -62,34 +60,34 @@ class Order(object): self.discriminator = None if id is not None: - self.id = id + self.id = id if pet_id is not None: - self.pet_id = pet_id + self.pet_id = pet_id if quantity is not None: - self.quantity = quantity + self.quantity = quantity if ship_date is not None: - self.ship_date = ship_date + self.ship_date = ship_date if status is not None: - self.status = status + self.status = status if complete is not None: - self.complete = complete + self.complete = complete @property def id(self): - """ - Gets the id of this Order. + """Gets the id of this Order. # noqa: E501 - :return: The id of this Order. + + :return: The id of this Order. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): - """ - Sets the id of this Order. + """Sets the id of this Order. - :param id: The id of this Order. + + :param id: The id of this Order. # noqa: E501 :type: int """ @@ -97,20 +95,20 @@ class Order(object): @property def pet_id(self): - """ - Gets the pet_id of this Order. + """Gets the pet_id of this Order. # noqa: E501 - :return: The pet_id of this Order. + + :return: The pet_id of this Order. # noqa: E501 :rtype: int """ return self._pet_id @pet_id.setter def pet_id(self, pet_id): - """ - Sets the pet_id of this Order. + """Sets the pet_id of this Order. - :param pet_id: The pet_id of this Order. + + :param pet_id: The pet_id of this Order. # noqa: E501 :type: int """ @@ -118,20 +116,20 @@ class Order(object): @property def quantity(self): - """ - Gets the quantity of this Order. + """Gets the quantity of this Order. # noqa: E501 - :return: The quantity of this Order. + + :return: The quantity of this Order. # noqa: E501 :rtype: int """ return self._quantity @quantity.setter def quantity(self, quantity): - """ - Sets the quantity of this Order. + """Sets the quantity of this Order. - :param quantity: The quantity of this Order. + + :param quantity: The quantity of this Order. # noqa: E501 :type: int """ @@ -139,20 +137,20 @@ class Order(object): @property def ship_date(self): - """ - Gets the ship_date of this Order. + """Gets the ship_date of this Order. # noqa: E501 - :return: The ship_date of this Order. + + :return: The ship_date of this Order. # noqa: E501 :rtype: datetime """ return self._ship_date @ship_date.setter def ship_date(self, ship_date): - """ - Sets the ship_date of this Order. + """Sets the ship_date of this Order. - :param ship_date: The ship_date of this Order. + + :param ship_date: The ship_date of this Order. # noqa: E501 :type: datetime """ @@ -160,28 +158,28 @@ class Order(object): @property def status(self): - """ - Gets the status of this Order. - Order Status + """Gets the status of this Order. # noqa: E501 - :return: The status of this Order. + Order Status # noqa: E501 + + :return: The status of this Order. # noqa: E501 :rtype: str """ return self._status @status.setter def status(self, status): - """ - Sets the status of this Order. - Order Status + """Sets the status of this Order. - :param status: The status of this Order. + Order Status # noqa: E501 + + :param status: The status of this Order. # noqa: E501 :type: str """ - allowed_values = ["placed", "approved", "delivered"] + allowed_values = ["placed", "approved", "delivered"] # noqa: E501 if status not in allowed_values: raise ValueError( - "Invalid value for `status` ({0}), must be one of {1}" + "Invalid value for `status` ({0}), must be one of {1}" # noqa: E501 .format(status, allowed_values) ) @@ -189,32 +187,30 @@ class Order(object): @property def complete(self): - """ - Gets the complete of this Order. + """Gets the complete of this Order. # noqa: E501 - :return: The complete of this Order. + + :return: The complete of this Order. # noqa: E501 :rtype: bool """ return self._complete @complete.setter def complete(self, complete): - """ - Sets the complete of this Order. + """Sets the complete of this Order. - :param complete: The complete of this Order. + + :param complete: The complete of this Order. # noqa: E501 :type: bool """ self._complete = complete def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -235,28 +231,20 @@ class Order(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Order): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/outer_boolean.py b/samples/client/petstore/python-asyncio/petstore_api/models/outer_boolean.py index aa9aee11973..9b3aebd3608 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/outer_boolean.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/outer_boolean.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class OuterBoolean(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -31,28 +31,20 @@ class OuterBoolean(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - OuterBoolean - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """OuterBoolean - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -73,28 +65,20 @@ class OuterBoolean(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, OuterBoolean): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/outer_composite.py b/samples/client/petstore/python-asyncio/petstore_api/models/outer_composite.py index 81611c17688..19775255e4e 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/outer_composite.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/outer_composite.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,22 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.outer_boolean import OuterBoolean # noqa: F401,E501 +from petstore_api.models.outer_number import OuterNumber # noqa: F401,E501 +from petstore_api.models.outer_string import OuterString # noqa: F401,E501 class OuterComposite(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -42,10 +46,8 @@ class OuterComposite(object): 'my_boolean': 'my_boolean' } - def __init__(self, my_number=None, my_string=None, my_boolean=None): - """ - OuterComposite - a model defined in Swagger - """ + def __init__(self, my_number=None, my_string=None, my_boolean=None): # noqa: E501 + """OuterComposite - a model defined in Swagger""" # noqa: E501 self._my_number = None self._my_string = None @@ -53,28 +55,28 @@ class OuterComposite(object): self.discriminator = None if my_number is not None: - self.my_number = my_number + self.my_number = my_number if my_string is not None: - self.my_string = my_string + self.my_string = my_string if my_boolean is not None: - self.my_boolean = my_boolean + self.my_boolean = my_boolean @property def my_number(self): - """ - Gets the my_number of this OuterComposite. + """Gets the my_number of this OuterComposite. # noqa: E501 - :return: The my_number of this OuterComposite. + + :return: The my_number of this OuterComposite. # noqa: E501 :rtype: OuterNumber """ return self._my_number @my_number.setter def my_number(self, my_number): - """ - Sets the my_number of this OuterComposite. + """Sets the my_number of this OuterComposite. - :param my_number: The my_number of this OuterComposite. + + :param my_number: The my_number of this OuterComposite. # noqa: E501 :type: OuterNumber """ @@ -82,20 +84,20 @@ class OuterComposite(object): @property def my_string(self): - """ - Gets the my_string of this OuterComposite. + """Gets the my_string of this OuterComposite. # noqa: E501 - :return: The my_string of this OuterComposite. + + :return: The my_string of this OuterComposite. # noqa: E501 :rtype: OuterString """ return self._my_string @my_string.setter def my_string(self, my_string): - """ - Sets the my_string of this OuterComposite. + """Sets the my_string of this OuterComposite. - :param my_string: The my_string of this OuterComposite. + + :param my_string: The my_string of this OuterComposite. # noqa: E501 :type: OuterString """ @@ -103,32 +105,30 @@ class OuterComposite(object): @property def my_boolean(self): - """ - Gets the my_boolean of this OuterComposite. + """Gets the my_boolean of this OuterComposite. # noqa: E501 - :return: The my_boolean of this OuterComposite. + + :return: The my_boolean of this OuterComposite. # noqa: E501 :rtype: OuterBoolean """ return self._my_boolean @my_boolean.setter def my_boolean(self, my_boolean): - """ - Sets the my_boolean of this OuterComposite. + """Sets the my_boolean of this OuterComposite. - :param my_boolean: The my_boolean of this OuterComposite. + + :param my_boolean: The my_boolean of this OuterComposite. # noqa: E501 :type: OuterBoolean """ self._my_boolean = my_boolean def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -149,28 +149,20 @@ class OuterComposite(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, OuterComposite): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/outer_enum.py b/samples/client/petstore/python-asyncio/petstore_api/models/outer_enum.py index 8772472c655..5ee1e49a587 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/outer_enum.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/outer_enum.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,14 +11,15 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class OuterEnum(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ @@ -37,28 +38,20 @@ class OuterEnum(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - OuterEnum - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """OuterEnum - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -79,28 +72,20 @@ class OuterEnum(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, OuterEnum): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/outer_number.py b/samples/client/petstore/python-asyncio/petstore_api/models/outer_number.py index 04c44923fb0..a35587be65e 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/outer_number.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/outer_number.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class OuterNumber(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -31,28 +31,20 @@ class OuterNumber(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - OuterNumber - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """OuterNumber - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -73,28 +65,20 @@ class OuterNumber(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, OuterNumber): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/outer_string.py b/samples/client/petstore/python-asyncio/petstore_api/models/outer_string.py index fd2d7c7623e..736edacd1bc 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/outer_string.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/outer_string.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class OuterString(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -31,28 +31,20 @@ class OuterString(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - OuterString - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """OuterString - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -73,28 +65,20 @@ class OuterString(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, OuterString): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/pet.py b/samples/client/petstore/python-asyncio/petstore_api/models/pet.py index e1afa26f785..81b2bb617f9 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/pet.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/pet.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,21 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.category import Category # noqa: F401,E501 +from petstore_api.models.tag import Tag # noqa: F401,E501 class Pet(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -48,10 +51,8 @@ class Pet(object): 'status': 'status' } - def __init__(self, id=None, category=None, name=None, photo_urls=None, tags=None, status=None): - """ - Pet - a model defined in Swagger - """ + def __init__(self, id=None, category=None, name=None, photo_urls=None, tags=None, status=None): # noqa: E501 + """Pet - a model defined in Swagger""" # noqa: E501 self._id = None self._category = None @@ -62,32 +63,32 @@ class Pet(object): self.discriminator = None if id is not None: - self.id = id + self.id = id if category is not None: - self.category = category + self.category = category self.name = name self.photo_urls = photo_urls if tags is not None: - self.tags = tags + self.tags = tags if status is not None: - self.status = status + self.status = status @property def id(self): - """ - Gets the id of this Pet. + """Gets the id of this Pet. # noqa: E501 - :return: The id of this Pet. + + :return: The id of this Pet. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): - """ - Sets the id of this Pet. + """Sets the id of this Pet. - :param id: The id of this Pet. + + :param id: The id of this Pet. # noqa: E501 :type: int """ @@ -95,20 +96,20 @@ class Pet(object): @property def category(self): - """ - Gets the category of this Pet. + """Gets the category of this Pet. # noqa: E501 - :return: The category of this Pet. + + :return: The category of this Pet. # noqa: E501 :rtype: Category """ return self._category @category.setter def category(self, category): - """ - Sets the category of this Pet. + """Sets the category of this Pet. - :param category: The category of this Pet. + + :param category: The category of this Pet. # noqa: E501 :type: Category """ @@ -116,66 +117,66 @@ class Pet(object): @property def name(self): - """ - Gets the name of this Pet. + """Gets the name of this Pet. # noqa: E501 - :return: The name of this Pet. + + :return: The name of this Pet. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): - """ - Sets the name of this Pet. + """Sets the name of this Pet. - :param name: The name of this Pet. + + :param name: The name of this Pet. # noqa: E501 :type: str """ if name is None: - raise ValueError("Invalid value for `name`, must not be `None`") + raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name @property def photo_urls(self): - """ - Gets the photo_urls of this Pet. + """Gets the photo_urls of this Pet. # noqa: E501 - :return: The photo_urls of this Pet. + + :return: The photo_urls of this Pet. # noqa: E501 :rtype: list[str] """ return self._photo_urls @photo_urls.setter def photo_urls(self, photo_urls): - """ - Sets the photo_urls of this Pet. + """Sets the photo_urls of this Pet. - :param photo_urls: The photo_urls of this Pet. + + :param photo_urls: The photo_urls of this Pet. # noqa: E501 :type: list[str] """ if photo_urls is None: - raise ValueError("Invalid value for `photo_urls`, must not be `None`") + raise ValueError("Invalid value for `photo_urls`, must not be `None`") # noqa: E501 self._photo_urls = photo_urls @property def tags(self): - """ - Gets the tags of this Pet. + """Gets the tags of this Pet. # noqa: E501 - :return: The tags of this Pet. + + :return: The tags of this Pet. # noqa: E501 :rtype: list[Tag] """ return self._tags @tags.setter def tags(self, tags): - """ - Sets the tags of this Pet. + """Sets the tags of this Pet. - :param tags: The tags of this Pet. + + :param tags: The tags of this Pet. # noqa: E501 :type: list[Tag] """ @@ -183,40 +184,38 @@ class Pet(object): @property def status(self): - """ - Gets the status of this Pet. - pet status in the store + """Gets the status of this Pet. # noqa: E501 - :return: The status of this Pet. + pet status in the store # noqa: E501 + + :return: The status of this Pet. # noqa: E501 :rtype: str """ return self._status @status.setter def status(self, status): - """ - Sets the status of this Pet. - pet status in the store + """Sets the status of this Pet. - :param status: The status of this Pet. + pet status in the store # noqa: E501 + + :param status: The status of this Pet. # noqa: E501 :type: str """ - allowed_values = ["available", "pending", "sold"] + allowed_values = ["available", "pending", "sold"] # noqa: E501 if status not in allowed_values: raise ValueError( - "Invalid value for `status` ({0}), must be one of {1}" + "Invalid value for `status` ({0}), must be one of {1}" # noqa: E501 .format(status, allowed_values) ) self._status = status def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -237,28 +236,20 @@ class Pet(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Pet): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/read_only_first.py b/samples/client/petstore/python-asyncio/petstore_api/models/read_only_first.py index a26d1f33c87..106463077e8 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/read_only_first.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/read_only_first.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ReadOnlyFirst(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class ReadOnlyFirst(object): 'baz': 'baz' } - def __init__(self, bar=None, baz=None): - """ - ReadOnlyFirst - a model defined in Swagger - """ + def __init__(self, bar=None, baz=None): # noqa: E501 + """ReadOnlyFirst - a model defined in Swagger""" # noqa: E501 self._bar = None self._baz = None self.discriminator = None if bar is not None: - self.bar = bar + self.bar = bar if baz is not None: - self.baz = baz + self.baz = baz @property def bar(self): - """ - Gets the bar of this ReadOnlyFirst. + """Gets the bar of this ReadOnlyFirst. # noqa: E501 - :return: The bar of this ReadOnlyFirst. + + :return: The bar of this ReadOnlyFirst. # noqa: E501 :rtype: str """ return self._bar @bar.setter def bar(self, bar): - """ - Sets the bar of this ReadOnlyFirst. + """Sets the bar of this ReadOnlyFirst. - :param bar: The bar of this ReadOnlyFirst. + + :param bar: The bar of this ReadOnlyFirst. # noqa: E501 :type: str """ @@ -77,32 +75,30 @@ class ReadOnlyFirst(object): @property def baz(self): - """ - Gets the baz of this ReadOnlyFirst. + """Gets the baz of this ReadOnlyFirst. # noqa: E501 - :return: The baz of this ReadOnlyFirst. + + :return: The baz of this ReadOnlyFirst. # noqa: E501 :rtype: str """ return self._baz @baz.setter def baz(self, baz): - """ - Sets the baz of this ReadOnlyFirst. + """Sets the baz of this ReadOnlyFirst. - :param baz: The baz of this ReadOnlyFirst. + + :param baz: The baz of this ReadOnlyFirst. # noqa: E501 :type: str """ self._baz = baz def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class ReadOnlyFirst(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ReadOnlyFirst): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/special_model_name.py b/samples/client/petstore/python-asyncio/petstore_api/models/special_model_name.py index 6be888fb9e3..a31b8db66e2 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/special_model_name.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/special_model_name.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class SpecialModelName(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class SpecialModelName(object): 'special_property_name': '$special[property.name]' } - def __init__(self, special_property_name=None): - """ - SpecialModelName - a model defined in Swagger - """ + def __init__(self, special_property_name=None): # noqa: E501 + """SpecialModelName - a model defined in Swagger""" # noqa: E501 self._special_property_name = None self.discriminator = None if special_property_name is not None: - self.special_property_name = special_property_name + self.special_property_name = special_property_name @property def special_property_name(self): - """ - Gets the special_property_name of this SpecialModelName. + """Gets the special_property_name of this SpecialModelName. # noqa: E501 - :return: The special_property_name of this SpecialModelName. + + :return: The special_property_name of this SpecialModelName. # noqa: E501 :rtype: int """ return self._special_property_name @special_property_name.setter def special_property_name(self, special_property_name): - """ - Sets the special_property_name of this SpecialModelName. + """Sets the special_property_name of this SpecialModelName. - :param special_property_name: The special_property_name of this SpecialModelName. + + :param special_property_name: The special_property_name of this SpecialModelName. # noqa: E501 :type: int """ self._special_property_name = special_property_name def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class SpecialModelName(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, SpecialModelName): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/tag.py b/samples/client/petstore/python-asyncio/petstore_api/models/tag.py index d59a490a07d..b486a672b88 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/tag.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/tag.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Tag(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class Tag(object): 'name': 'name' } - def __init__(self, id=None, name=None): - """ - Tag - a model defined in Swagger - """ + def __init__(self, id=None, name=None): # noqa: E501 + """Tag - a model defined in Swagger""" # noqa: E501 self._id = None self._name = None self.discriminator = None if id is not None: - self.id = id + self.id = id if name is not None: - self.name = name + self.name = name @property def id(self): - """ - Gets the id of this Tag. + """Gets the id of this Tag. # noqa: E501 - :return: The id of this Tag. + + :return: The id of this Tag. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): - """ - Sets the id of this Tag. + """Sets the id of this Tag. - :param id: The id of this Tag. + + :param id: The id of this Tag. # noqa: E501 :type: int """ @@ -77,32 +75,30 @@ class Tag(object): @property def name(self): - """ - Gets the name of this Tag. + """Gets the name of this Tag. # noqa: E501 - :return: The name of this Tag. + + :return: The name of this Tag. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): - """ - Sets the name of this Tag. + """Sets the name of this Tag. - :param name: The name of this Tag. + + :param name: The name of this Tag. # noqa: E501 :type: str """ self._name = name def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class Tag(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Tag): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/user.py b/samples/client/petstore/python-asyncio/petstore_api/models/user.py index 21993e90521..c9fe0072a9c 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/user.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/user.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class User(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -52,10 +52,8 @@ class User(object): 'user_status': 'userStatus' } - 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 - """ + def __init__(self, id=None, username=None, first_name=None, last_name=None, email=None, password=None, phone=None, user_status=None): # noqa: E501 + """User - a model defined in Swagger""" # noqa: E501 self._id = None self._username = None @@ -68,38 +66,38 @@ class User(object): self.discriminator = None if id is not None: - self.id = id + self.id = id if username is not None: - self.username = username + self.username = username if first_name is not None: - self.first_name = first_name + self.first_name = first_name if last_name is not None: - self.last_name = last_name + self.last_name = last_name if email is not None: - self.email = email + self.email = email if password is not None: - self.password = password + self.password = password if phone is not None: - self.phone = phone + self.phone = phone if user_status is not None: - self.user_status = user_status + self.user_status = user_status @property def id(self): - """ - Gets the id of this User. + """Gets the id of this User. # noqa: E501 - :return: The id of this User. + + :return: The id of this User. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): - """ - Sets the id of this User. + """Sets the id of this User. - :param id: The id of this User. + + :param id: The id of this User. # noqa: E501 :type: int """ @@ -107,20 +105,20 @@ class User(object): @property def username(self): - """ - Gets the username of this User. + """Gets the username of this User. # noqa: E501 - :return: The username of this User. + + :return: The username of this User. # noqa: E501 :rtype: str """ return self._username @username.setter def username(self, username): - """ - Sets the username of this User. + """Sets the username of this User. - :param username: The username of this User. + + :param username: The username of this User. # noqa: E501 :type: str """ @@ -128,20 +126,20 @@ class User(object): @property def first_name(self): - """ - Gets the first_name of this User. + """Gets the first_name of this User. # noqa: E501 - :return: The first_name of this User. + + :return: The first_name of this User. # noqa: E501 :rtype: str """ return self._first_name @first_name.setter def first_name(self, first_name): - """ - Sets the first_name of this User. + """Sets the first_name of this User. - :param first_name: The first_name of this User. + + :param first_name: The first_name of this User. # noqa: E501 :type: str """ @@ -149,20 +147,20 @@ class User(object): @property def last_name(self): - """ - Gets the last_name of this User. + """Gets the last_name of this User. # noqa: E501 - :return: The last_name of this User. + + :return: The last_name of this User. # noqa: E501 :rtype: str """ return self._last_name @last_name.setter def last_name(self, last_name): - """ - Sets the last_name of this User. + """Sets the last_name of this User. - :param last_name: The last_name of this User. + + :param last_name: The last_name of this User. # noqa: E501 :type: str """ @@ -170,20 +168,20 @@ class User(object): @property def email(self): - """ - Gets the email of this User. + """Gets the email of this User. # noqa: E501 - :return: The email of this User. + + :return: The email of this User. # noqa: E501 :rtype: str """ return self._email @email.setter def email(self, email): - """ - Sets the email of this User. + """Sets the email of this User. - :param email: The email of this User. + + :param email: The email of this User. # noqa: E501 :type: str """ @@ -191,20 +189,20 @@ class User(object): @property def password(self): - """ - Gets the password of this User. + """Gets the password of this User. # noqa: E501 - :return: The password of this User. + + :return: The password of this User. # noqa: E501 :rtype: str """ return self._password @password.setter def password(self, password): - """ - Sets the password of this User. + """Sets the password of this User. - :param password: The password of this User. + + :param password: The password of this User. # noqa: E501 :type: str """ @@ -212,20 +210,20 @@ class User(object): @property def phone(self): - """ - Gets the phone of this User. + """Gets the phone of this User. # noqa: E501 - :return: The phone of this User. + + :return: The phone of this User. # noqa: E501 :rtype: str """ return self._phone @phone.setter def phone(self, phone): - """ - Sets the phone of this User. + """Sets the phone of this User. - :param phone: The phone of this User. + + :param phone: The phone of this User. # noqa: E501 :type: str """ @@ -233,34 +231,32 @@ class User(object): @property def user_status(self): - """ - Gets the user_status of this User. - User Status + """Gets the user_status of this User. # noqa: E501 - :return: The user_status of this User. + User Status # noqa: E501 + + :return: The user_status of this User. # noqa: E501 :rtype: int """ return self._user_status @user_status.setter def user_status(self, user_status): - """ - Sets the user_status of this User. - User Status + """Sets the user_status of this User. - :param user_status: The user_status of this User. + User Status # noqa: E501 + + :param user_status: The user_status of this User. # noqa: E501 :type: int """ self._user_status = user_status def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -281,28 +277,20 @@ class User(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, User): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-asyncio/petstore_api/rest.py b/samples/client/petstore/python-asyncio/petstore_api/rest.py index 8cb130e035b..497882aaa9f 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/rest.py +++ b/samples/client/petstore/python-asyncio/petstore_api/rest.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,16 +11,15 @@ """ -import aiohttp import io import json -import ssl -import certifi import logging import re +import ssl +import aiohttp +import certifi # python 2 and python 3 compatibility library -from six import PY3 from six.moves.urllib.parse import urlencode logger = logging.getLogger(__name__) @@ -35,22 +34,18 @@ class RESTResponse(io.IOBase): self.data = data def getheaders(self): - """ - Returns a CIMultiDictProxy of the response headers. - """ + """Returns a CIMultiDictProxy of the response headers.""" return self.aiohttp_response.headers def getheader(self, name, default=None): - """ - Returns a given response header. - """ + """Returns a given response header.""" return self.aiohttp_response.headers.get(name, default) -class RESTClientObject: +class RESTClientObject(object): def __init__(self, configuration, pools_size=4, maxsize=4): - # maxsize is the number of requests to host that are allowed in parallel + # maxsize is number of requests to host that are allowed in parallel # ca_certs vs cert_file vs key_file # http://stackoverflow.com/a/23957365/2985775 @@ -62,6 +57,7 @@ class RESTClientObject: ca_certs = certifi.where() ssl_context = ssl.SSLContext() + ssl_context.load_verify_locations(cafile=ca_certs) if configuration.cert_file: ssl_context.load_cert_chain( configuration.cert_file, keyfile=configuration.key_file @@ -69,6 +65,7 @@ class RESTClientObject: connector = aiohttp.TCPConnector( limit=maxsize, + ssl_context=ssl_context, verify_ssl=configuration.verify_ssl ) @@ -84,8 +81,10 @@ class RESTClientObject: ) async def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, _request_timeout=None): - """ + body=None, post_params=None, _preload_content=True, + _request_timeout=None): + """Execute request + :param method: http request method :param url: http request url :param query_params: query parameters in the url @@ -94,12 +93,16 @@ class RESTClientObject: :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` - :param _preload_content: this is a non-applicable field for the AiohttpClient. - :param _request_timeout: timeout setting for this request. If one number provided, it will be total request - timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :param _preload_content: this is a non-applicable field for + the AiohttpClient. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', + 'PATCH', 'OPTIONS'] if post_params and body: raise ValueError( @@ -127,7 +130,7 @@ class RESTClientObject: if body is not None: body = json.dumps(body) args["data"] = body - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 data = aiohttp.FormData() for k, v in post_params.items(): data.add_field(k, v) @@ -141,8 +144,9 @@ class RESTClientObject: args["data"] = body else: # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided arguments. - Please check that your arguments match declared content type.""" + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" raise ApiException(status=0, reason=msg) else: args["data"] = query_params @@ -159,22 +163,25 @@ class RESTClientObject: return r - async def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): + async def GET(self, url, headers=None, query_params=None, + _preload_content=True, _request_timeout=None): return (await self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params)) + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params)) - async def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): + async def HEAD(self, url, headers=None, query_params=None, + _preload_content=True, _request_timeout=None): return (await self.request("HEAD", url, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout, query_params=query_params)) - async def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + async def OPTIONS(self, url, headers=None, query_params=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): return (await self.request("OPTIONS", url, headers=headers, query_params=query_params, @@ -183,7 +190,8 @@ class RESTClientObject: _request_timeout=_request_timeout, body=body)) - async def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None): + async def DELETE(self, url, headers=None, query_params=None, body=None, + _preload_content=True, _request_timeout=None): return (await self.request("DELETE", url, headers=headers, query_params=query_params, @@ -191,8 +199,9 @@ class RESTClientObject: _request_timeout=_request_timeout, body=body)) - async def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + async def POST(self, url, headers=None, query_params=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): return (await self.request("POST", url, headers=headers, query_params=query_params, @@ -201,8 +210,8 @@ class RESTClientObject: _request_timeout=_request_timeout, body=body)) - async def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + async def PUT(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): return (await self.request("PUT", url, headers=headers, query_params=query_params, @@ -211,8 +220,9 @@ class RESTClientObject: _request_timeout=_request_timeout, body=body)) - async def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + async def PATCH(self, url, headers=None, query_params=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): return (await self.request("PATCH", url, headers=headers, query_params=query_params, @@ -237,13 +247,11 @@ class ApiException(Exception): self.headers = None def __str__(self): - """ - Custom error messages for exception - """ - error_message = "({0})\n"\ - "Reason: {1}\n".format(self.status, self.reason) + """Custom error messages for exception""" + error_message = "({0})\nReason: {1}\n".format(self.status, self.reason) if self.headers: - error_message += "HTTP response headers: {0}\n".format(self.headers) + error_message += "HTTP response headers: {0}\n".format( + self.headers) if self.body: error_message += "HTTP response body: {0}\n".format(self.body) diff --git a/samples/client/petstore/python-asyncio/setup.py b/samples/client/petstore/python-asyncio/setup.py index b04ac0abe10..30a70401fbc 100644 --- a/samples/client/petstore/python-asyncio/setup.py +++ b/samples/client/petstore/python-asyncio/setup.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,8 +11,7 @@ """ -import sys -from setuptools import setup, find_packages +from setuptools import setup, find_packages # noqa: H301 NAME = "petstore-api" VERSION = "1.0.0" @@ -37,6 +36,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. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 """ ) diff --git a/samples/client/petstore/python-asyncio/test/test_additional_properties_class.py b/samples/client/petstore/python-asyncio/test/test_additional_properties_class.py index e90e5f92efc..77ccb73b028 100644 --- a/samples/client/petstore/python-asyncio/test/test_additional_properties_class.py +++ b/samples/client/petstore/python-asyncio/test/test_additional_properties_class.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.additional_properties_class import AdditionalPropertiesClass # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.additional_properties_class import AdditionalPropertiesClass class TestAdditionalPropertiesClass(unittest.TestCase): - """ AdditionalPropertiesClass unit test stubs """ + """AdditionalPropertiesClass unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestAdditionalPropertiesClass(unittest.TestCase): pass def testAdditionalPropertiesClass(self): - """ - Test AdditionalPropertiesClass - """ + """Test AdditionalPropertiesClass""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.additional_properties_class.AdditionalPropertiesClass() + # model = petstore_api.models.additional_properties_class.AdditionalPropertiesClass() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_animal.py b/samples/client/petstore/python-asyncio/test/test_animal.py index c675d583ccc..eb5f7cb930e 100644 --- a/samples/client/petstore/python-asyncio/test/test_animal.py +++ b/samples/client/petstore/python-asyncio/test/test_animal.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.animal import Animal # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.animal import Animal class TestAnimal(unittest.TestCase): - """ Animal unit test stubs """ + """Animal unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestAnimal(unittest.TestCase): pass def testAnimal(self): - """ - Test Animal - """ + """Test Animal""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.animal.Animal() + # model = petstore_api.models.animal.Animal() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_animal_farm.py b/samples/client/petstore/python-asyncio/test/test_animal_farm.py index e459318a948..8f79946fa73 100644 --- a/samples/client/petstore/python-asyncio/test/test_animal_farm.py +++ b/samples/client/petstore/python-asyncio/test/test_animal_farm.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.animal_farm import AnimalFarm # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.animal_farm import AnimalFarm class TestAnimalFarm(unittest.TestCase): - """ AnimalFarm unit test stubs """ + """AnimalFarm unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestAnimalFarm(unittest.TestCase): pass def testAnimalFarm(self): - """ - Test AnimalFarm - """ + """Test AnimalFarm""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.animal_farm.AnimalFarm() + # model = petstore_api.models.animal_farm.AnimalFarm() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_another_fake_api.py b/samples/client/petstore/python-asyncio/test/test_another_fake_api.py index 9f562fe1134..c294aa90359 100644 --- a/samples/client/petstore/python-asyncio/test/test_another_fake_api.py +++ b/samples/client/petstore/python-asyncio/test/test_another_fake_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,29 +13,26 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.another_fake_api import AnotherFakeApi # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.another_fake_api import AnotherFakeApi class TestAnotherFakeApi(unittest.TestCase): - """ AnotherFakeApi unit test stubs """ + """AnotherFakeApi unit test stubs""" def setUp(self): - self.api = petstore_api.apis.another_fake_api.AnotherFakeApi() + self.api = petstore_api.api.another_fake_api.AnotherFakeApi() # noqa: E501 def tearDown(self): pass def test_test_special_tags(self): - """ - Test case for test_special_tags + """Test case for test_special_tags - To test special tags + To test special tags # noqa: E501 """ pass diff --git a/samples/client/petstore/python-asyncio/test/test_api_response.py b/samples/client/petstore/python-asyncio/test/test_api_response.py index 928af048b43..97ed978a5f6 100644 --- a/samples/client/petstore/python-asyncio/test/test_api_response.py +++ b/samples/client/petstore/python-asyncio/test/test_api_response.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.api_response import ApiResponse # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.api_response import ApiResponse class TestApiResponse(unittest.TestCase): - """ ApiResponse unit test stubs """ + """ApiResponse unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestApiResponse(unittest.TestCase): pass def testApiResponse(self): - """ - Test ApiResponse - """ + """Test ApiResponse""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.api_response.ApiResponse() + # model = petstore_api.models.api_response.ApiResponse() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_array_of_array_of_number_only.py b/samples/client/petstore/python-asyncio/test/test_array_of_array_of_number_only.py index 740e45cbafd..b617ed2cd3e 100644 --- a/samples/client/petstore/python-asyncio/test/test_array_of_array_of_number_only.py +++ b/samples/client/petstore/python-asyncio/test/test_array_of_array_of_number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly class TestArrayOfArrayOfNumberOnly(unittest.TestCase): - """ ArrayOfArrayOfNumberOnly unit test stubs """ + """ArrayOfArrayOfNumberOnly unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestArrayOfArrayOfNumberOnly(unittest.TestCase): pass def testArrayOfArrayOfNumberOnly(self): - """ - Test ArrayOfArrayOfNumberOnly - """ + """Test ArrayOfArrayOfNumberOnly""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.array_of_array_of_number_only.ArrayOfArrayOfNumberOnly() + # model = petstore_api.models.array_of_array_of_number_only.ArrayOfArrayOfNumberOnly() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_array_of_number_only.py b/samples/client/petstore/python-asyncio/test/test_array_of_number_only.py index 6da67a490b6..7439364c7b1 100644 --- a/samples/client/petstore/python-asyncio/test/test_array_of_number_only.py +++ b/samples/client/petstore/python-asyncio/test/test_array_of_number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.array_of_number_only import ArrayOfNumberOnly # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.array_of_number_only import ArrayOfNumberOnly class TestArrayOfNumberOnly(unittest.TestCase): - """ ArrayOfNumberOnly unit test stubs """ + """ArrayOfNumberOnly unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestArrayOfNumberOnly(unittest.TestCase): pass def testArrayOfNumberOnly(self): - """ - Test ArrayOfNumberOnly - """ + """Test ArrayOfNumberOnly""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.array_of_number_only.ArrayOfNumberOnly() + # model = petstore_api.models.array_of_number_only.ArrayOfNumberOnly() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_array_test.py b/samples/client/petstore/python-asyncio/test/test_array_test.py index dcf8cc111c0..d7feb2ac8f4 100644 --- a/samples/client/petstore/python-asyncio/test/test_array_test.py +++ b/samples/client/petstore/python-asyncio/test/test_array_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.array_test import ArrayTest # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.array_test import ArrayTest class TestArrayTest(unittest.TestCase): - """ ArrayTest unit test stubs """ + """ArrayTest unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestArrayTest(unittest.TestCase): pass def testArrayTest(self): - """ - Test ArrayTest - """ + """Test ArrayTest""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.array_test.ArrayTest() + # model = petstore_api.models.array_test.ArrayTest() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_capitalization.py b/samples/client/petstore/python-asyncio/test/test_capitalization.py index 4ea6d2e3fd0..4ac874e817c 100644 --- a/samples/client/petstore/python-asyncio/test/test_capitalization.py +++ b/samples/client/petstore/python-asyncio/test/test_capitalization.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.capitalization import Capitalization # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.capitalization import Capitalization class TestCapitalization(unittest.TestCase): - """ Capitalization unit test stubs """ + """Capitalization unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestCapitalization(unittest.TestCase): pass def testCapitalization(self): - """ - Test Capitalization - """ + """Test Capitalization""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.capitalization.Capitalization() + # model = petstore_api.models.capitalization.Capitalization() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_cat.py b/samples/client/petstore/python-asyncio/test/test_cat.py index 9d9fbc50ab3..370f1081383 100644 --- a/samples/client/petstore/python-asyncio/test/test_cat.py +++ b/samples/client/petstore/python-asyncio/test/test_cat.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.cat import Cat # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.cat import Cat class TestCat(unittest.TestCase): - """ Cat unit test stubs """ + """Cat unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestCat(unittest.TestCase): pass def testCat(self): - """ - Test Cat - """ + """Test Cat""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.cat.Cat() + # model = petstore_api.models.cat.Cat() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_category.py b/samples/client/petstore/python-asyncio/test/test_category.py index 6ded8f0f1ac..7a9e40a1f65 100644 --- a/samples/client/petstore/python-asyncio/test/test_category.py +++ b/samples/client/petstore/python-asyncio/test/test_category.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.category import Category # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.category import Category class TestCategory(unittest.TestCase): - """ Category unit test stubs """ + """Category unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestCategory(unittest.TestCase): pass def testCategory(self): - """ - Test Category - """ + """Test Category""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.category.Category() + # model = petstore_api.models.category.Category() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_class_model.py b/samples/client/petstore/python-asyncio/test/test_class_model.py index 85d56bbe52a..a42127abf50 100644 --- a/samples/client/petstore/python-asyncio/test/test_class_model.py +++ b/samples/client/petstore/python-asyncio/test/test_class_model.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.class_model import ClassModel # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.class_model import ClassModel class TestClassModel(unittest.TestCase): - """ ClassModel unit test stubs """ + """ClassModel unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestClassModel(unittest.TestCase): pass def testClassModel(self): - """ - Test ClassModel - """ + """Test ClassModel""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.class_model.ClassModel() + # model = petstore_api.models.class_model.ClassModel() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_client.py b/samples/client/petstore/python-asyncio/test/test_client.py index 363ced2923c..81df726dbfc 100644 --- a/samples/client/petstore/python-asyncio/test/test_client.py +++ b/samples/client/petstore/python-asyncio/test/test_client.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.client import Client # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.client import Client class TestClient(unittest.TestCase): - """ Client unit test stubs """ + """Client unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestClient(unittest.TestCase): pass def testClient(self): - """ - Test Client - """ + """Test Client""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.client.Client() + # model = petstore_api.models.client.Client() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_dog.py b/samples/client/petstore/python-asyncio/test/test_dog.py index b0428646591..ae13869b99f 100644 --- a/samples/client/petstore/python-asyncio/test/test_dog.py +++ b/samples/client/petstore/python-asyncio/test/test_dog.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.dog import Dog # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.dog import Dog class TestDog(unittest.TestCase): - """ Dog unit test stubs """ + """Dog unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestDog(unittest.TestCase): pass def testDog(self): - """ - Test Dog - """ + """Test Dog""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.dog.Dog() + # model = petstore_api.models.dog.Dog() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_enum_arrays.py b/samples/client/petstore/python-asyncio/test/test_enum_arrays.py index 2803f17aede..144e48883e5 100644 --- a/samples/client/petstore/python-asyncio/test/test_enum_arrays.py +++ b/samples/client/petstore/python-asyncio/test/test_enum_arrays.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.enum_arrays import EnumArrays # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.enum_arrays import EnumArrays class TestEnumArrays(unittest.TestCase): - """ EnumArrays unit test stubs """ + """EnumArrays unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestEnumArrays(unittest.TestCase): pass def testEnumArrays(self): - """ - Test EnumArrays - """ + """Test EnumArrays""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.enum_arrays.EnumArrays() + # model = petstore_api.models.enum_arrays.EnumArrays() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_enum_class.py b/samples/client/petstore/python-asyncio/test/test_enum_class.py index f673e741f84..a47581d2820 100644 --- a/samples/client/petstore/python-asyncio/test/test_enum_class.py +++ b/samples/client/petstore/python-asyncio/test/test_enum_class.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.enum_class import EnumClass # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.enum_class import EnumClass class TestEnumClass(unittest.TestCase): - """ EnumClass unit test stubs """ + """EnumClass unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestEnumClass(unittest.TestCase): pass def testEnumClass(self): - """ - Test EnumClass - """ + """Test EnumClass""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.enum_class.EnumClass() + # model = petstore_api.models.enum_class.EnumClass() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_enum_test.py b/samples/client/petstore/python-asyncio/test/test_enum_test.py index e27c0107fd2..7487efe9fa1 100644 --- a/samples/client/petstore/python-asyncio/test/test_enum_test.py +++ b/samples/client/petstore/python-asyncio/test/test_enum_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.enum_test import EnumTest # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.enum_test import EnumTest class TestEnumTest(unittest.TestCase): - """ EnumTest unit test stubs """ + """EnumTest unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestEnumTest(unittest.TestCase): pass def testEnumTest(self): - """ - Test EnumTest - """ + """Test EnumTest""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.enum_test.EnumTest() + # model = petstore_api.models.enum_test.EnumTest() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_fake_api.py b/samples/client/petstore/python-asyncio/test/test_fake_api.py index 55a02cf899c..00473d4a13b 100644 --- a/samples/client/petstore/python-asyncio/test/test_fake_api.py +++ b/samples/client/petstore/python-asyncio/test/test_fake_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,85 +13,78 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.fake_api import FakeApi # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.fake_api import FakeApi class TestFakeApi(unittest.TestCase): - """ FakeApi unit test stubs """ + """FakeApi unit test stubs""" def setUp(self): - self.api = petstore_api.apis.fake_api.FakeApi() + self.api = petstore_api.api.fake_api.FakeApi() # noqa: E501 def tearDown(self): pass def test_fake_outer_boolean_serialize(self): - """ - Test case for fake_outer_boolean_serialize + """Test case for fake_outer_boolean_serialize - """ pass def test_fake_outer_composite_serialize(self): - """ - Test case for fake_outer_composite_serialize + """Test case for fake_outer_composite_serialize - """ pass def test_fake_outer_number_serialize(self): - """ - Test case for fake_outer_number_serialize + """Test case for fake_outer_number_serialize - """ pass def test_fake_outer_string_serialize(self): - """ - Test case for fake_outer_string_serialize + """Test case for fake_outer_string_serialize - """ pass def test_test_client_model(self): - """ - Test case for test_client_model + """Test case for test_client_model - To test \"client\" model + To test \"client\" model # noqa: E501 """ pass def test_test_endpoint_parameters(self): - """ - Test case for test_endpoint_parameters + """Test case for test_endpoint_parameters - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 """ pass def test_test_enum_parameters(self): - """ - Test case for test_enum_parameters + """Test case for test_enum_parameters - To test enum parameters + To test enum parameters # noqa: E501 + """ + pass + + def test_test_inline_additional_properties(self): + """Test case for test_inline_additional_properties + + test inline additionalProperties # noqa: E501 """ pass def test_test_json_form_data(self): - """ - Test case for test_json_form_data + """Test case for test_json_form_data - test json serialization of form data + test json serialization of form data # noqa: E501 """ pass diff --git a/samples/client/petstore/python-asyncio/test/test_fake_classname_tags_123_api.py b/samples/client/petstore/python-asyncio/test/test_fake_classname_tags_123_api.py index 7a11a2378bf..8f40062a929 100644 --- a/samples/client/petstore/python-asyncio/test/test_fake_classname_tags_123_api.py +++ b/samples/client/petstore/python-asyncio/test/test_fake_classname_tags_123_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,29 +13,26 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.fake_classname_tags_123_api import FakeClassnameTags123Api # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.fake_classname_tags_123_api import FakeClassnameTags123Api class TestFakeClassnameTags123Api(unittest.TestCase): - """ FakeClassnameTags123Api unit test stubs """ + """FakeClassnameTags123Api unit test stubs""" def setUp(self): - self.api = petstore_api.apis.fake_classname_tags_123_api.FakeClassnameTags123Api() + self.api = petstore_api.api.fake_classname_tags_123_api.FakeClassnameTags123Api() # noqa: E501 def tearDown(self): pass def test_test_classname(self): - """ - Test case for test_classname + """Test case for test_classname - To test class name in snake case + To test class name in snake case # noqa: E501 """ pass diff --git a/samples/client/petstore/python-asyncio/test/test_format_test.py b/samples/client/petstore/python-asyncio/test/test_format_test.py index ad028c0b431..59809b9f442 100644 --- a/samples/client/petstore/python-asyncio/test/test_format_test.py +++ b/samples/client/petstore/python-asyncio/test/test_format_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.format_test import FormatTest # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.format_test import FormatTest class TestFormatTest(unittest.TestCase): - """ FormatTest unit test stubs """ + """FormatTest unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestFormatTest(unittest.TestCase): pass def testFormatTest(self): - """ - Test FormatTest - """ + """Test FormatTest""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.format_test.FormatTest() + # model = petstore_api.models.format_test.FormatTest() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_has_only_read_only.py b/samples/client/petstore/python-asyncio/test/test_has_only_read_only.py index af029f26814..26d14aef1f8 100644 --- a/samples/client/petstore/python-asyncio/test/test_has_only_read_only.py +++ b/samples/client/petstore/python-asyncio/test/test_has_only_read_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.has_only_read_only import HasOnlyReadOnly # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.has_only_read_only import HasOnlyReadOnly class TestHasOnlyReadOnly(unittest.TestCase): - """ HasOnlyReadOnly unit test stubs """ + """HasOnlyReadOnly unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestHasOnlyReadOnly(unittest.TestCase): pass def testHasOnlyReadOnly(self): - """ - Test HasOnlyReadOnly - """ + """Test HasOnlyReadOnly""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.has_only_read_only.HasOnlyReadOnly() + # model = petstore_api.models.has_only_read_only.HasOnlyReadOnly() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_list.py b/samples/client/petstore/python-asyncio/test/test_list.py index 14400e35281..c2cca419f37 100644 --- a/samples/client/petstore/python-asyncio/test/test_list.py +++ b/samples/client/petstore/python-asyncio/test/test_list.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.list import List # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.list import List class TestList(unittest.TestCase): - """ List unit test stubs """ + """List unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestList(unittest.TestCase): pass def testList(self): - """ - Test List - """ + """Test List""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.list.List() + # model = petstore_api.models.list.List() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_map_test.py b/samples/client/petstore/python-asyncio/test/test_map_test.py index c4b2092f0ce..155797d9b2d 100644 --- a/samples/client/petstore/python-asyncio/test/test_map_test.py +++ b/samples/client/petstore/python-asyncio/test/test_map_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.map_test import MapTest # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.map_test import MapTest class TestMapTest(unittest.TestCase): - """ MapTest unit test stubs """ + """MapTest unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestMapTest(unittest.TestCase): pass def testMapTest(self): - """ - Test MapTest - """ + """Test MapTest""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.map_test.MapTest() + # model = petstore_api.models.map_test.MapTest() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python-asyncio/test/test_mixed_properties_and_additional_properties_class.py index f614d36da8a..12a56764080 100644 --- a/samples/client/petstore/python-asyncio/test/test_mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python-asyncio/test/test_mixed_properties_and_additional_properties_class.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass # noqa: E501 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 """ + """MixedPropertiesAndAdditionalPropertiesClass unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestMixedPropertiesAndAdditionalPropertiesClass(unittest.TestCase): pass def testMixedPropertiesAndAdditionalPropertiesClass(self): - """ - Test MixedPropertiesAndAdditionalPropertiesClass - """ + """Test MixedPropertiesAndAdditionalPropertiesClass""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.mixed_properties_and_additional_properties_class.MixedPropertiesAndAdditionalPropertiesClass() + # model = petstore_api.models.mixed_properties_and_additional_properties_class.MixedPropertiesAndAdditionalPropertiesClass() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_model_200_response.py b/samples/client/petstore/python-asyncio/test/test_model_200_response.py index f202a2d454f..f577dd42144 100644 --- a/samples/client/petstore/python-asyncio/test/test_model_200_response.py +++ b/samples/client/petstore/python-asyncio/test/test_model_200_response.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.model_200_response import Model200Response # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.model_200_response import Model200Response class TestModel200Response(unittest.TestCase): - """ Model200Response unit test stubs """ + """Model200Response unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestModel200Response(unittest.TestCase): pass def testModel200Response(self): - """ - Test Model200Response - """ + """Test Model200Response""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.model_200_response.Model200Response() + # model = petstore_api.models.model_200_response.Model200Response() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_model_return.py b/samples/client/petstore/python-asyncio/test/test_model_return.py index 347c8e4d7cb..64cf27f63ab 100644 --- a/samples/client/petstore/python-asyncio/test/test_model_return.py +++ b/samples/client/petstore/python-asyncio/test/test_model_return.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.model_return import ModelReturn # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.model_return import ModelReturn class TestModelReturn(unittest.TestCase): - """ ModelReturn unit test stubs """ + """ModelReturn unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestModelReturn(unittest.TestCase): pass def testModelReturn(self): - """ - Test ModelReturn - """ + """Test ModelReturn""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.model_return.ModelReturn() + # model = petstore_api.models.model_return.ModelReturn() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_name.py b/samples/client/petstore/python-asyncio/test/test_name.py index c06e35427f6..beba143f39c 100644 --- a/samples/client/petstore/python-asyncio/test/test_name.py +++ b/samples/client/petstore/python-asyncio/test/test_name.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.name import Name # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.name import Name class TestName(unittest.TestCase): - """ Name unit test stubs """ + """Name unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestName(unittest.TestCase): pass def testName(self): - """ - Test Name - """ + """Test Name""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.name.Name() + # model = petstore_api.models.name.Name() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_number_only.py b/samples/client/petstore/python-asyncio/test/test_number_only.py index db3197a9e5b..f2600c79526 100644 --- a/samples/client/petstore/python-asyncio/test/test_number_only.py +++ b/samples/client/petstore/python-asyncio/test/test_number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.number_only import NumberOnly # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.number_only import NumberOnly class TestNumberOnly(unittest.TestCase): - """ NumberOnly unit test stubs """ + """NumberOnly unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestNumberOnly(unittest.TestCase): pass def testNumberOnly(self): - """ - Test NumberOnly - """ + """Test NumberOnly""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.number_only.NumberOnly() + # model = petstore_api.models.number_only.NumberOnly() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_order.py b/samples/client/petstore/python-asyncio/test/test_order.py index d911487ce97..ed4f8c7d161 100644 --- a/samples/client/petstore/python-asyncio/test/test_order.py +++ b/samples/client/petstore/python-asyncio/test/test_order.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.order import Order # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.order import Order class TestOrder(unittest.TestCase): - """ Order unit test stubs """ + """Order unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestOrder(unittest.TestCase): pass def testOrder(self): - """ - Test Order - """ + """Test Order""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.order.Order() + # model = petstore_api.models.order.Order() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_outer_boolean.py b/samples/client/petstore/python-asyncio/test/test_outer_boolean.py index 9474ab76968..4a7e446693e 100644 --- a/samples/client/petstore/python-asyncio/test/test_outer_boolean.py +++ b/samples/client/petstore/python-asyncio/test/test_outer_boolean.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.outer_boolean import OuterBoolean # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.outer_boolean import OuterBoolean class TestOuterBoolean(unittest.TestCase): - """ OuterBoolean unit test stubs """ + """OuterBoolean unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestOuterBoolean(unittest.TestCase): pass def testOuterBoolean(self): - """ - Test OuterBoolean - """ + """Test OuterBoolean""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.outer_boolean.OuterBoolean() + # model = petstore_api.models.outer_boolean.OuterBoolean() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_outer_composite.py b/samples/client/petstore/python-asyncio/test/test_outer_composite.py index ebbd9d03e6f..e444e695fe8 100644 --- a/samples/client/petstore/python-asyncio/test/test_outer_composite.py +++ b/samples/client/petstore/python-asyncio/test/test_outer_composite.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.outer_composite import OuterComposite # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.outer_composite import OuterComposite class TestOuterComposite(unittest.TestCase): - """ OuterComposite unit test stubs """ + """OuterComposite unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestOuterComposite(unittest.TestCase): pass def testOuterComposite(self): - """ - Test OuterComposite - """ + """Test OuterComposite""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.outer_composite.OuterComposite() + # model = petstore_api.models.outer_composite.OuterComposite() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_outer_enum.py b/samples/client/petstore/python-asyncio/test/test_outer_enum.py index c6e1f030ef1..e3fb15e1b6b 100644 --- a/samples/client/petstore/python-asyncio/test/test_outer_enum.py +++ b/samples/client/petstore/python-asyncio/test/test_outer_enum.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.outer_enum import OuterEnum # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.outer_enum import OuterEnum class TestOuterEnum(unittest.TestCase): - """ OuterEnum unit test stubs """ + """OuterEnum unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestOuterEnum(unittest.TestCase): pass def testOuterEnum(self): - """ - Test OuterEnum - """ + """Test OuterEnum""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.outer_enum.OuterEnum() + # model = petstore_api.models.outer_enum.OuterEnum() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_outer_number.py b/samples/client/petstore/python-asyncio/test/test_outer_number.py index 9f97b407047..da5d3ceee61 100644 --- a/samples/client/petstore/python-asyncio/test/test_outer_number.py +++ b/samples/client/petstore/python-asyncio/test/test_outer_number.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.outer_number import OuterNumber # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.outer_number import OuterNumber class TestOuterNumber(unittest.TestCase): - """ OuterNumber unit test stubs """ + """OuterNumber unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestOuterNumber(unittest.TestCase): pass def testOuterNumber(self): - """ - Test OuterNumber - """ + """Test OuterNumber""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.outer_number.OuterNumber() + # model = petstore_api.models.outer_number.OuterNumber() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_outer_string.py b/samples/client/petstore/python-asyncio/test/test_outer_string.py index b0ac85ed934..02b4967e3b9 100644 --- a/samples/client/petstore/python-asyncio/test/test_outer_string.py +++ b/samples/client/petstore/python-asyncio/test/test_outer_string.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.outer_string import OuterString # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.outer_string import OuterString class TestOuterString(unittest.TestCase): - """ OuterString unit test stubs """ + """OuterString unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestOuterString(unittest.TestCase): pass def testOuterString(self): - """ - Test OuterString - """ + """Test OuterString""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.outer_string.OuterString() + # model = petstore_api.models.outer_string.OuterString() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_pet.py b/samples/client/petstore/python-asyncio/test/test_pet.py index c3e8191bec3..d8df24f92b1 100644 --- a/samples/client/petstore/python-asyncio/test/test_pet.py +++ b/samples/client/petstore/python-asyncio/test/test_pet.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.pet import Pet # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.pet import Pet class TestPet(unittest.TestCase): - """ Pet unit test stubs """ + """Pet unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestPet(unittest.TestCase): pass def testPet(self): - """ - Test Pet - """ + """Test Pet""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.pet.Pet() + # model = petstore_api.models.pet.Pet() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_pet_api.py b/samples/client/petstore/python-asyncio/test/test_pet_api.py index 1eafc35b28c..1e2dd1c42b6 100644 --- a/samples/client/petstore/python-asyncio/test/test_pet_api.py +++ b/samples/client/petstore/python-asyncio/test/test_pet_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,85 +13,75 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.pet_api import PetApi # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.pet_api import PetApi class TestPetApi(unittest.TestCase): - """ PetApi unit test stubs """ + """PetApi unit test stubs""" def setUp(self): - self.api = petstore_api.apis.pet_api.PetApi() + self.api = petstore_api.api.pet_api.PetApi() # noqa: E501 def tearDown(self): pass def test_add_pet(self): - """ - Test case for add_pet + """Test case for add_pet - Add a new pet to the store + Add a new pet to the store # noqa: E501 """ pass def test_delete_pet(self): - """ - Test case for delete_pet + """Test case for delete_pet - Deletes a pet + Deletes a pet # noqa: E501 """ pass def test_find_pets_by_status(self): - """ - Test case for find_pets_by_status + """Test case for find_pets_by_status - Finds Pets by status + Finds Pets by status # noqa: E501 """ pass def test_find_pets_by_tags(self): - """ - Test case for find_pets_by_tags + """Test case for find_pets_by_tags - Finds Pets by tags + Finds Pets by tags # noqa: E501 """ pass def test_get_pet_by_id(self): - """ - Test case for get_pet_by_id + """Test case for get_pet_by_id - Find pet by ID + Find pet by ID # noqa: E501 """ pass def test_update_pet(self): - """ - Test case for update_pet + """Test case for update_pet - Update an existing pet + Update an existing pet # noqa: E501 """ pass def test_update_pet_with_form(self): - """ - Test case for update_pet_with_form + """Test case for update_pet_with_form - Updates a pet in the store with form data + Updates a pet in the store with form data # noqa: E501 """ pass def test_upload_file(self): - """ - Test case for upload_file + """Test case for upload_file - uploads an image + uploads an image # noqa: E501 """ pass diff --git a/samples/client/petstore/python-asyncio/test/test_read_only_first.py b/samples/client/petstore/python-asyncio/test/test_read_only_first.py index c89d5d3b6a1..94bf3d127de 100644 --- a/samples/client/petstore/python-asyncio/test/test_read_only_first.py +++ b/samples/client/petstore/python-asyncio/test/test_read_only_first.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.read_only_first import ReadOnlyFirst # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.read_only_first import ReadOnlyFirst class TestReadOnlyFirst(unittest.TestCase): - """ ReadOnlyFirst unit test stubs """ + """ReadOnlyFirst unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestReadOnlyFirst(unittest.TestCase): pass def testReadOnlyFirst(self): - """ - Test ReadOnlyFirst - """ + """Test ReadOnlyFirst""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.read_only_first.ReadOnlyFirst() + # model = petstore_api.models.read_only_first.ReadOnlyFirst() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_special_model_name.py b/samples/client/petstore/python-asyncio/test/test_special_model_name.py index d9fa392c36b..002f660cc26 100644 --- a/samples/client/petstore/python-asyncio/test/test_special_model_name.py +++ b/samples/client/petstore/python-asyncio/test/test_special_model_name.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.special_model_name import SpecialModelName # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.special_model_name import SpecialModelName class TestSpecialModelName(unittest.TestCase): - """ SpecialModelName unit test stubs """ + """SpecialModelName unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestSpecialModelName(unittest.TestCase): pass def testSpecialModelName(self): - """ - Test SpecialModelName - """ + """Test SpecialModelName""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.special_model_name.SpecialModelName() + # model = petstore_api.models.special_model_name.SpecialModelName() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_store_api.py b/samples/client/petstore/python-asyncio/test/test_store_api.py index f131b6068b2..537c1bc03f1 100644 --- a/samples/client/petstore/python-asyncio/test/test_store_api.py +++ b/samples/client/petstore/python-asyncio/test/test_store_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,53 +13,47 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.store_api import StoreApi # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.store_api import StoreApi class TestStoreApi(unittest.TestCase): - """ StoreApi unit test stubs """ + """StoreApi unit test stubs""" def setUp(self): - self.api = petstore_api.apis.store_api.StoreApi() + self.api = petstore_api.api.store_api.StoreApi() # noqa: E501 def tearDown(self): pass def test_delete_order(self): - """ - Test case for delete_order + """Test case for delete_order - Delete purchase order by ID + Delete purchase order by ID # noqa: E501 """ pass def test_get_inventory(self): - """ - Test case for get_inventory + """Test case for get_inventory - Returns pet inventories by status + Returns pet inventories by status # noqa: E501 """ pass def test_get_order_by_id(self): - """ - Test case for get_order_by_id + """Test case for get_order_by_id - Find purchase order by ID + Find purchase order by ID # noqa: E501 """ pass def test_place_order(self): - """ - Test case for place_order + """Test case for place_order - Place an order for a pet + Place an order for a pet # noqa: E501 """ pass diff --git a/samples/client/petstore/python-asyncio/test/test_tag.py b/samples/client/petstore/python-asyncio/test/test_tag.py index 76f79932c96..e9bc1d471d1 100644 --- a/samples/client/petstore/python-asyncio/test/test_tag.py +++ b/samples/client/petstore/python-asyncio/test/test_tag.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.tag import Tag # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.tag import Tag class TestTag(unittest.TestCase): - """ Tag unit test stubs """ + """Tag unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestTag(unittest.TestCase): pass def testTag(self): - """ - Test Tag - """ + """Test Tag""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.tag.Tag() + # model = petstore_api.models.tag.Tag() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_user.py b/samples/client/petstore/python-asyncio/test/test_user.py index 82f5d9058b0..3575746c00f 100644 --- a/samples/client/petstore/python-asyncio/test/test_user.py +++ b/samples/client/petstore/python-asyncio/test/test_user.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.user import User # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.user import User class TestUser(unittest.TestCase): - """ User unit test stubs """ + """User unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestUser(unittest.TestCase): pass def testUser(self): - """ - Test User - """ + """Test User""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.user.User() + # model = petstore_api.models.user.User() # noqa: E501 pass diff --git a/samples/client/petstore/python-asyncio/test/test_user_api.py b/samples/client/petstore/python-asyncio/test/test_user_api.py index 3e0be964a2d..4ebd90f95e2 100644 --- a/samples/client/petstore/python-asyncio/test/test_user_api.py +++ b/samples/client/petstore/python-asyncio/test/test_user_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,85 +13,75 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.user_api import UserApi # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.user_api import UserApi class TestUserApi(unittest.TestCase): - """ UserApi unit test stubs """ + """UserApi unit test stubs""" def setUp(self): - self.api = petstore_api.apis.user_api.UserApi() + self.api = petstore_api.api.user_api.UserApi() # noqa: E501 def tearDown(self): pass def test_create_user(self): - """ - Test case for create_user + """Test case for create_user - Create user + Create user # noqa: E501 """ pass def test_create_users_with_array_input(self): - """ - Test case for create_users_with_array_input + """Test case for create_users_with_array_input - Creates list of users with given input array + Creates list of users with given input array # noqa: E501 """ pass def test_create_users_with_list_input(self): - """ - Test case for create_users_with_list_input + """Test case for create_users_with_list_input - Creates list of users with given input array + Creates list of users with given input array # noqa: E501 """ pass def test_delete_user(self): - """ - Test case for delete_user + """Test case for delete_user - Delete user + Delete user # noqa: E501 """ pass def test_get_user_by_name(self): - """ - Test case for get_user_by_name + """Test case for get_user_by_name - Get user by user name + Get user by user name # noqa: E501 """ pass def test_login_user(self): - """ - Test case for login_user + """Test case for login_user - Logs user into the system + Logs user into the system # noqa: E501 """ pass def test_logout_user(self): - """ - Test case for logout_user + """Test case for logout_user - Logs out current logged in user session + Logs out current logged in user session # noqa: E501 """ pass def test_update_user(self): - """ - Test case for update_user + """Test case for update_user - Updated user + Updated user # noqa: E501 """ pass diff --git a/samples/client/petstore/python-tornado/Makefile b/samples/client/petstore/python-tornado/Makefile new file mode 100644 index 00000000000..ba5c5e73c63 --- /dev/null +++ b/samples/client/petstore/python-tornado/Makefile @@ -0,0 +1,21 @@ + #!/bin/bash + +REQUIREMENTS_FILE=dev-requirements.txt +REQUIREMENTS_OUT=dev-requirements.txt.log +SETUP_OUT=*.egg-info +VENV=.venv + +clean: + rm -rf $(REQUIREMENTS_OUT) + rm -rf $(SETUP_OUT) + rm -rf $(VENV) + rm -rf .tox + rm -rf .coverage + find . -name "*.py[oc]" -delete + find . -name "__pycache__" -delete + +test: clean + bash ./test_python2.sh + +test-all: clean + bash ./test_python2_and_3.sh diff --git a/samples/client/petstore/python-tornado/README.md b/samples/client/petstore/python-tornado/README.md index 87f80990fc5..a49d99c556c 100644 --- a/samples/client/petstore/python-tornado/README.md +++ b/samples/client/petstore/python-tornado/README.md @@ -77,6 +77,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model *FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**test_inline_additional_properties**](docs/FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties *FakeApi* | [**test_json_form_data**](docs/FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data *FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store diff --git a/samples/client/petstore/python-tornado/dev-requirements.txt b/samples/client/petstore/python-tornado/dev-requirements.txt new file mode 100644 index 00000000000..f50c13b5c50 --- /dev/null +++ b/samples/client/petstore/python-tornado/dev-requirements.txt @@ -0,0 +1,5 @@ +nose +tox +coverage +randomize +flake8 diff --git a/samples/client/petstore/python-tornado/docs/AdditionalPropertiesClass.md b/samples/client/petstore/python-tornado/docs/AdditionalPropertiesClass.md index ea12f270f02..796a789d4c4 100644 --- a/samples/client/petstore/python-tornado/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/python-tornado/docs/AdditionalPropertiesClass.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **map_property** | **dict(str, str)** | | [optional] -**map_of_map_property** | [**dict(str, dict(str, str))**](dict.md) | | [optional] +**map_of_map_property** | **dict(str, dict(str, 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-tornado/docs/AnotherFakeApi.md b/samples/client/petstore/python-tornado/docs/AnotherFakeApi.md index b78fcf86f43..3d70f7a2875 100644 --- a/samples/client/petstore/python-tornado/docs/AnotherFakeApi.md +++ b/samples/client/petstore/python-tornado/docs/AnotherFakeApi.md @@ -14,7 +14,7 @@ To test special tags To test special tags -### Example +### Example ```python from __future__ import print_function import time @@ -26,7 +26,7 @@ from pprint import pprint api_instance = petstore_api.AnotherFakeApi() body = petstore_api.Client() # Client | client model -try: +try: # To test special tags api_response = api_instance.test_special_tags(body) pprint(api_response) diff --git a/samples/client/petstore/python-tornado/docs/FakeApi.md b/samples/client/petstore/python-tornado/docs/FakeApi.md index eb669540e53..1da84500bfe 100644 --- a/samples/client/petstore/python-tornado/docs/FakeApi.md +++ b/samples/client/petstore/python-tornado/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model [**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +[**test_inline_additional_properties**](FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**test_json_form_data**](FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data @@ -21,7 +22,7 @@ Method | HTTP request | Description Test serialization of outer boolean types -### Example +### Example ```python from __future__ import print_function import time @@ -33,7 +34,7 @@ from pprint import pprint api_instance = petstore_api.FakeApi() body = petstore_api.OuterBoolean() # OuterBoolean | Input boolean as post body (optional) -try: +try: api_response = api_instance.fake_outer_boolean_serialize(body=body) pprint(api_response) except ApiException as e: @@ -68,7 +69,7 @@ No authorization required Test serialization of object with outer number type -### Example +### Example ```python from __future__ import print_function import time @@ -80,7 +81,7 @@ from pprint import pprint api_instance = petstore_api.FakeApi() body = petstore_api.OuterComposite() # OuterComposite | Input composite as post body (optional) -try: +try: api_response = api_instance.fake_outer_composite_serialize(body=body) pprint(api_response) except ApiException as e: @@ -115,7 +116,7 @@ No authorization required Test serialization of outer number types -### Example +### Example ```python from __future__ import print_function import time @@ -127,7 +128,7 @@ from pprint import pprint api_instance = petstore_api.FakeApi() body = petstore_api.OuterNumber() # OuterNumber | Input number as post body (optional) -try: +try: api_response = api_instance.fake_outer_number_serialize(body=body) pprint(api_response) except ApiException as e: @@ -162,7 +163,7 @@ No authorization required Test serialization of outer string types -### Example +### Example ```python from __future__ import print_function import time @@ -174,7 +175,7 @@ from pprint import pprint api_instance = petstore_api.FakeApi() body = petstore_api.OuterString() # OuterString | Input string as post body (optional) -try: +try: api_response = api_instance.fake_outer_string_serialize(body=body) pprint(api_response) except ApiException as e: @@ -209,7 +210,7 @@ To test \"client\" model To test \"client\" model -### Example +### Example ```python from __future__ import print_function import time @@ -221,7 +222,7 @@ from pprint import pprint api_instance = petstore_api.FakeApi() body = petstore_api.Client() # Client | client model -try: +try: # To test \"client\" model api_response = api_instance.test_client_model(body) pprint(api_response) @@ -257,7 +258,7 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -### Example +### Example ```python from __future__ import print_function import time @@ -272,10 +273,10 @@ configuration.password = 'YOUR_PASSWORD' # create an instance of the API class api_instance = petstore_api.FakeApi(petstore_api.ApiClient(configuration)) -number = 3.4 # float | None +number = 8.14 # float | None double = 1.2 # float | None pattern_without_delimiter = 'pattern_without_delimiter_example' # str | None -byte = 'byte_example' # str | None +byte = 'B' # str | None integer = 56 # int | None (optional) int32 = 56 # int | None (optional) int64 = 789 # int | None (optional) @@ -287,7 +288,7 @@ date_time = '2013-10-20T19:20:30+01:00' # datetime | None (optional) password = 'password_example' # str | None (optional) param_callback = 'param_callback_example' # str | None (optional) -try: +try: # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password, param_callback=param_callback) except ApiException as e: @@ -335,7 +336,7 @@ To test enum parameters To test enum parameters -### Example +### Example ```python from __future__ import print_function import time @@ -354,7 +355,7 @@ enum_query_string = '-efg' # str | Query parameter enum test (string) (optional) enum_query_integer = 56 # int | Query parameter enum test (double) (optional) enum_query_double = 1.2 # float | Query parameter enum test (double) (optional) -try: +try: # To test enum parameters api_instance.test_enum_parameters(enum_form_string_array=enum_form_string_array, enum_form_string=enum_form_string, enum_header_string_array=enum_header_string_array, enum_header_string=enum_header_string, enum_query_string_array=enum_query_string_array, enum_query_string=enum_query_string, enum_query_integer=enum_query_integer, enum_query_double=enum_query_double) except ApiException as e: @@ -389,6 +390,53 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_inline_additional_properties** +> test_inline_additional_properties(param) + +test inline additionalProperties + + + +### Example +```python +from __future__ import print_function +import time +import petstore_api +from petstore_api.rest import ApiException +from pprint import pprint + +# create an instance of the API class +api_instance = petstore_api.FakeApi() +param = NULL # object | request body + +try: + # test inline additionalProperties + api_instance.test_inline_additional_properties(param) +except ApiException as e: + print("Exception when calling FakeApi->test_inline_additional_properties: %s\n" % e) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **object**| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_json_form_data** > test_json_form_data(param, param2) @@ -396,7 +444,7 @@ test json serialization of form data -### Example +### Example ```python from __future__ import print_function import time @@ -409,7 +457,7 @@ api_instance = petstore_api.FakeApi() param = 'param_example' # str | field1 param2 = 'param2_example' # str | field2 -try: +try: # test json serialization of form data api_instance.test_json_form_data(param, param2) except ApiException as e: diff --git a/samples/client/petstore/python-tornado/docs/FakeClassnameTags123Api.md b/samples/client/petstore/python-tornado/docs/FakeClassnameTags123Api.md index a103a4ee327..2546c09ca4a 100644 --- a/samples/client/petstore/python-tornado/docs/FakeClassnameTags123Api.md +++ b/samples/client/petstore/python-tornado/docs/FakeClassnameTags123Api.md @@ -12,7 +12,7 @@ Method | HTTP request | Description To test class name in snake case -### Example +### Example ```python from __future__ import print_function import time @@ -30,7 +30,7 @@ configuration.api_key['api_key_query'] = 'YOUR_API_KEY' api_instance = petstore_api.FakeClassnameTags123Api(petstore_api.ApiClient(configuration)) body = petstore_api.Client() # Client | client model -try: +try: # To test class name in snake case api_response = api_instance.test_classname(body) pprint(api_response) diff --git a/samples/client/petstore/python-tornado/docs/MapTest.md b/samples/client/petstore/python-tornado/docs/MapTest.md index 63cdab0374a..68844755d42 100644 --- a/samples/client/petstore/python-tornado/docs/MapTest.md +++ b/samples/client/petstore/python-tornado/docs/MapTest.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**map_map_of_string** | [**dict(str, dict(str, str))**](dict.md) | | [optional] +**map_map_of_string** | **dict(str, dict(str, str))** | | [optional] **map_of_enum_string** | **dict(str, 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-tornado/docs/PetApi.md b/samples/client/petstore/python-tornado/docs/PetApi.md index 74c6a5196fd..53b9158e699 100644 --- a/samples/client/petstore/python-tornado/docs/PetApi.md +++ b/samples/client/petstore/python-tornado/docs/PetApi.md @@ -21,7 +21,7 @@ Add a new pet to the store -### Example +### Example ```python from __future__ import print_function import time @@ -37,7 +37,7 @@ configuration.access_token = 'YOUR_ACCESS_TOKEN' api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) body = petstore_api.Pet() # Pet | Pet object that needs to be added to the store -try: +try: # Add a new pet to the store api_instance.add_pet(body) except ApiException as e: @@ -72,7 +72,7 @@ Deletes a pet -### Example +### Example ```python from __future__ import print_function import time @@ -89,7 +89,7 @@ api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) pet_id = 789 # int | Pet id to delete api_key = 'api_key_example' # str | (optional) -try: +try: # Deletes a pet api_instance.delete_pet(pet_id, api_key=api_key) except ApiException as e: @@ -125,7 +125,7 @@ Finds Pets by status Multiple status values can be provided with comma separated strings -### Example +### Example ```python from __future__ import print_function import time @@ -141,7 +141,7 @@ configuration.access_token = 'YOUR_ACCESS_TOKEN' api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) status = ['status_example'] # list[str] | Status values that need to be considered for filter -try: +try: # Finds Pets by status api_response = api_instance.find_pets_by_status(status) pprint(api_response) @@ -177,7 +177,7 @@ Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. -### Example +### Example ```python from __future__ import print_function import time @@ -193,7 +193,7 @@ configuration.access_token = 'YOUR_ACCESS_TOKEN' api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) tags = ['tags_example'] # list[str] | Tags to filter by -try: +try: # Finds Pets by tags api_response = api_instance.find_pets_by_tags(tags) pprint(api_response) @@ -229,7 +229,7 @@ Find pet by ID Returns a single pet -### Example +### Example ```python from __future__ import print_function import time @@ -247,7 +247,7 @@ configuration.api_key['api_key'] = 'YOUR_API_KEY' api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) pet_id = 789 # int | ID of pet to return -try: +try: # Find pet by ID api_response = api_instance.get_pet_by_id(pet_id) pprint(api_response) @@ -283,7 +283,7 @@ Update an existing pet -### Example +### Example ```python from __future__ import print_function import time @@ -299,7 +299,7 @@ configuration.access_token = 'YOUR_ACCESS_TOKEN' api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) body = petstore_api.Pet() # Pet | Pet object that needs to be added to the store -try: +try: # Update an existing pet api_instance.update_pet(body) except ApiException as e: @@ -334,7 +334,7 @@ Updates a pet in the store with form data -### Example +### Example ```python from __future__ import print_function import time @@ -352,7 +352,7 @@ 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) -try: +try: # Updates a pet in the store with form data api_instance.update_pet_with_form(pet_id, name=name, status=status) except ApiException as e: @@ -389,7 +389,7 @@ uploads an image -### Example +### Example ```python from __future__ import print_function import time @@ -407,7 +407,7 @@ 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) -try: +try: # uploads an image api_response = api_instance.upload_file(pet_id, additional_metadata=additional_metadata, file=file) pprint(api_response) diff --git a/samples/client/petstore/python-tornado/docs/StoreApi.md b/samples/client/petstore/python-tornado/docs/StoreApi.md index a75113975ef..6cbb6b45145 100644 --- a/samples/client/petstore/python-tornado/docs/StoreApi.md +++ b/samples/client/petstore/python-tornado/docs/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 ```python from __future__ import print_function import time @@ -29,7 +29,7 @@ from pprint import pprint api_instance = petstore_api.StoreApi() order_id = 'order_id_example' # str | ID of the order that needs to be deleted -try: +try: # Delete purchase order by ID api_instance.delete_order(order_id) except ApiException as e: @@ -64,7 +64,7 @@ Returns pet inventories by status Returns a map of status codes to quantities -### Example +### Example ```python from __future__ import print_function import time @@ -81,7 +81,7 @@ configuration.api_key['api_key'] = 'YOUR_API_KEY' # create an instance of the API class api_instance = petstore_api.StoreApi(petstore_api.ApiClient(configuration)) -try: +try: # Returns pet inventories by status api_response = api_instance.get_inventory() pprint(api_response) @@ -114,7 +114,7 @@ Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions -### Example +### Example ```python from __future__ import print_function import time @@ -126,7 +126,7 @@ from pprint import pprint api_instance = petstore_api.StoreApi() order_id = 789 # int | ID of pet that needs to be fetched -try: +try: # Find purchase order by ID api_response = api_instance.get_order_by_id(order_id) pprint(api_response) @@ -162,7 +162,7 @@ Place an order for a pet -### Example +### Example ```python from __future__ import print_function import time @@ -174,7 +174,7 @@ from pprint import pprint api_instance = petstore_api.StoreApi() body = petstore_api.Order() # Order | order placed for purchasing the pet -try: +try: # Place an order for a pet api_response = api_instance.place_order(body) pprint(api_response) diff --git a/samples/client/petstore/python-tornado/docs/UserApi.md b/samples/client/petstore/python-tornado/docs/UserApi.md index 5b73179dce3..969485595ae 100644 --- a/samples/client/petstore/python-tornado/docs/UserApi.md +++ b/samples/client/petstore/python-tornado/docs/UserApi.md @@ -21,7 +21,7 @@ Create user This can only be done by the logged in user. -### Example +### Example ```python from __future__ import print_function import time @@ -33,7 +33,7 @@ from pprint import pprint api_instance = petstore_api.UserApi() body = petstore_api.User() # User | Created user object -try: +try: # Create user api_instance.create_user(body) except ApiException as e: @@ -68,7 +68,7 @@ Creates list of users with given input array -### Example +### Example ```python from __future__ import print_function import time @@ -80,7 +80,7 @@ from pprint import pprint api_instance = petstore_api.UserApi() body = [petstore_api.User()] # list[User] | List of user object -try: +try: # Creates list of users with given input array api_instance.create_users_with_array_input(body) except ApiException as e: @@ -115,7 +115,7 @@ Creates list of users with given input array -### Example +### Example ```python from __future__ import print_function import time @@ -127,7 +127,7 @@ from pprint import pprint api_instance = petstore_api.UserApi() body = [petstore_api.User()] # list[User] | List of user object -try: +try: # Creates list of users with given input array api_instance.create_users_with_list_input(body) except ApiException as e: @@ -162,7 +162,7 @@ Delete user This can only be done by the logged in user. -### Example +### Example ```python from __future__ import print_function import time @@ -174,7 +174,7 @@ from pprint import pprint api_instance = petstore_api.UserApi() username = 'username_example' # str | The name that needs to be deleted -try: +try: # Delete user api_instance.delete_user(username) except ApiException as e: @@ -209,7 +209,7 @@ Get user by user name -### Example +### Example ```python from __future__ import print_function import time @@ -221,7 +221,7 @@ from pprint import pprint api_instance = petstore_api.UserApi() username = 'username_example' # str | The name that needs to be fetched. Use user1 for testing. -try: +try: # Get user by user name api_response = api_instance.get_user_by_name(username) pprint(api_response) @@ -257,7 +257,7 @@ Logs user into the system -### Example +### Example ```python from __future__ import print_function import time @@ -270,7 +270,7 @@ 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 -try: +try: # Logs user into the system api_response = api_instance.login_user(username, password) pprint(api_response) @@ -307,7 +307,7 @@ Logs out current logged in user session -### Example +### Example ```python from __future__ import print_function import time @@ -318,7 +318,7 @@ from pprint import pprint # create an instance of the API class api_instance = petstore_api.UserApi() -try: +try: # Logs out current logged in user session api_instance.logout_user() except ApiException as e: @@ -350,7 +350,7 @@ Updated user This can only be done by the logged in user. -### Example +### Example ```python from __future__ import print_function import time @@ -363,7 +363,7 @@ api_instance = petstore_api.UserApi() username = 'username_example' # str | name that need to be deleted body = petstore_api.User() # User | Updated user object -try: +try: # Updated user api_instance.update_user(username, body) except ApiException as e: diff --git a/samples/client/petstore/python-tornado/petstore_api/__init__.py b/samples/client/petstore/python-tornado/petstore_api/__init__.py index cad09e2691c..c368867dd11 100644 --- a/samples/client/petstore/python-tornado/petstore_api/__init__.py +++ b/samples/client/petstore/python-tornado/petstore_api/__init__.py @@ -1,9 +1,11 @@ # coding: utf-8 +# flake8: noqa + """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,53 +15,51 @@ 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_of_array_of_number_only import ArrayOfArrayOfNumberOnly -from .models.array_of_number_only import ArrayOfNumberOnly -from .models.array_test import ArrayTest -from .models.capitalization import Capitalization -from .models.category import Category -from .models.class_model import ClassModel -from .models.client import Client -from .models.enum_arrays import EnumArrays -from .models.enum_class import EnumClass -from .models.enum_test import EnumTest -from .models.format_test import FormatTest -from .models.has_only_read_only import HasOnlyReadOnly -from .models.list import List -from .models.map_test import MapTest -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.number_only import NumberOnly -from .models.order import Order -from .models.outer_boolean import OuterBoolean -from .models.outer_composite import OuterComposite -from .models.outer_enum import OuterEnum -from .models.outer_number import OuterNumber -from .models.outer_string import OuterString -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 -from .models.cat import Cat -from .models.dog import Dog - # import apis into sdk package -from .apis.another_fake_api import AnotherFakeApi -from .apis.fake_api import FakeApi -from .apis.fake_classname_tags_123_api import FakeClassnameTags123Api -from .apis.pet_api import PetApi -from .apis.store_api import StoreApi -from .apis.user_api import UserApi +from petstore_api.api.another_fake_api import AnotherFakeApi +from petstore_api.api.fake_api import FakeApi +from petstore_api.api.fake_classname_tags_123_api import FakeClassnameTags123Api +from petstore_api.api.pet_api import PetApi +from petstore_api.api.store_api import StoreApi +from petstore_api.api.user_api import UserApi # import ApiClient -from .api_client import ApiClient - -from .configuration import Configuration +from petstore_api.api_client import ApiClient +from petstore_api.configuration import Configuration +# import models into sdk package +from petstore_api.models.additional_properties_class import AdditionalPropertiesClass +from petstore_api.models.animal import Animal +from petstore_api.models.animal_farm import AnimalFarm +from petstore_api.models.api_response import ApiResponse +from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly +from petstore_api.models.array_of_number_only import ArrayOfNumberOnly +from petstore_api.models.array_test import ArrayTest +from petstore_api.models.capitalization import Capitalization +from petstore_api.models.category import Category +from petstore_api.models.class_model import ClassModel +from petstore_api.models.client import Client +from petstore_api.models.enum_arrays import EnumArrays +from petstore_api.models.enum_class import EnumClass +from petstore_api.models.enum_test import EnumTest +from petstore_api.models.format_test import FormatTest +from petstore_api.models.has_only_read_only import HasOnlyReadOnly +from petstore_api.models.list import List +from petstore_api.models.map_test import MapTest +from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass +from petstore_api.models.model_200_response import Model200Response +from petstore_api.models.model_return import ModelReturn +from petstore_api.models.name import Name +from petstore_api.models.number_only import NumberOnly +from petstore_api.models.order import Order +from petstore_api.models.outer_boolean import OuterBoolean +from petstore_api.models.outer_composite import OuterComposite +from petstore_api.models.outer_enum import OuterEnum +from petstore_api.models.outer_number import OuterNumber +from petstore_api.models.outer_string import OuterString +from petstore_api.models.pet import Pet +from petstore_api.models.read_only_first import ReadOnlyFirst +from petstore_api.models.special_model_name import SpecialModelName +from petstore_api.models.tag import Tag +from petstore_api.models.user import User +from petstore_api.models.cat import Cat +from petstore_api.models.dog import Dog diff --git a/samples/client/petstore/python-tornado/petstore_api/api/__init__.py b/samples/client/petstore/python-tornado/petstore_api/api/__init__.py new file mode 100644 index 00000000000..74496adb5a2 --- /dev/null +++ b/samples/client/petstore/python-tornado/petstore_api/api/__init__.py @@ -0,0 +1,11 @@ +from __future__ import absolute_import + +# flake8: noqa + +# import apis into api package +from petstore_api.api.another_fake_api import AnotherFakeApi +from petstore_api.api.fake_api import FakeApi +from petstore_api.api.fake_classname_tags_123_api import FakeClassnameTags123Api +from petstore_api.api.pet_api import PetApi +from petstore_api.api.store_api import StoreApi +from petstore_api.api.user_api import UserApi diff --git a/samples/client/petstore/python-asyncio/petstore_api/apis/another_fake_api.py b/samples/client/petstore/python-tornado/petstore_api/api/another_fake_api.py similarity index 59% rename from samples/client/petstore/python-asyncio/petstore_api/apis/another_fake_api.py rename to samples/client/petstore/python-tornado/petstore_api/api/another_fake_api.py index 8fb991ff3df..0096dad1a37 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/apis/another_fake_api.py +++ b/samples/client/petstore/python-tornado/petstore_api/api/another_fake_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class AnotherFakeApi(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,10 +33,10 @@ class AnotherFakeApi(object): api_client = ApiClient() self.api_client = api_client - def test_special_tags(self, body, **kwargs): - """ - To test special tags - To test special tags + def test_special_tags(self, body, **kwargs): # noqa: E501 + """To test special tags # noqa: E501 + + To test special tags # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_special_tags(body, async=True) @@ -52,15 +50,15 @@ class AnotherFakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_special_tags_with_http_info(body, **kwargs) + return self.test_special_tags_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.test_special_tags_with_http_info(body, **kwargs) + (data) = self.test_special_tags_with_http_info(body, **kwargs) # noqa: E501 return data - def test_special_tags_with_http_info(self, body, **kwargs): - """ - To test special tags - To test special tags + def test_special_tags_with_http_info(self, body, **kwargs): # noqa: E501 + """To test special tags # noqa: E501 + + To test special tags # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_special_tags_with_http_info(body, async=True) @@ -73,14 +71,14 @@ class AnotherFakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -89,9 +87,9 @@ class AnotherFakeApi(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 `test_special_tags`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `test_special_tags`") # noqa: E501 collection_formats = {} @@ -108,27 +106,28 @@ class AnotherFakeApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/another-fake/dummy', 'PATCH', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Client', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/another-fake/dummy', 'PATCH', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Client', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/fake_api.py b/samples/client/petstore/python-tornado/petstore_api/api/fake_api.py similarity index 57% rename from samples/client/petstore/python/petstore_api/apis/fake_api.py rename to samples/client/petstore/python-tornado/petstore_api/api/fake_api.py index 46fb22f7290..4c52ee51647 100644 --- a/samples/client/petstore/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore/python-tornado/petstore_api/api/fake_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class FakeApi(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,9 +33,10 @@ class FakeApi(object): api_client = ApiClient() self.api_client = api_client - def fake_outer_boolean_serialize(self, **kwargs): - """ - Test serialization of outer boolean types + def fake_outer_boolean_serialize(self, **kwargs): # noqa: E501 + """fake_outer_boolean_serialize # noqa: E501 + + Test serialization of outer boolean types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_boolean_serialize(async=True) @@ -51,14 +50,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.fake_outer_boolean_serialize_with_http_info(**kwargs) + return self.fake_outer_boolean_serialize_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.fake_outer_boolean_serialize_with_http_info(**kwargs) + (data) = self.fake_outer_boolean_serialize_with_http_info(**kwargs) # noqa: E501 return data - def fake_outer_boolean_serialize_with_http_info(self, **kwargs): - """ - Test serialization of outer boolean types + def fake_outer_boolean_serialize_with_http_info(self, **kwargs): # noqa: E501 + """fake_outer_boolean_serialize # noqa: E501 + + Test serialization of outer boolean types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_boolean_serialize_with_http_info(async=True) @@ -71,14 +71,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -87,7 +87,6 @@ class FakeApi(object): params[key] = val del params['kwargs'] - collection_formats = {} path_params = {} @@ -103,26 +102,28 @@ class FakeApi(object): if 'body' in params: body_params = params['body'] # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake/outer/boolean', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='OuterBoolean', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake/outer/boolean', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='OuterBoolean', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def fake_outer_composite_serialize(self, **kwargs): - """ - Test serialization of object with outer number type + def fake_outer_composite_serialize(self, **kwargs): # noqa: E501 + """fake_outer_composite_serialize # noqa: E501 + + Test serialization of object with outer number type # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_composite_serialize(async=True) @@ -136,14 +137,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.fake_outer_composite_serialize_with_http_info(**kwargs) + return self.fake_outer_composite_serialize_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.fake_outer_composite_serialize_with_http_info(**kwargs) + (data) = self.fake_outer_composite_serialize_with_http_info(**kwargs) # noqa: E501 return data - def fake_outer_composite_serialize_with_http_info(self, **kwargs): - """ - Test serialization of object with outer number type + def fake_outer_composite_serialize_with_http_info(self, **kwargs): # noqa: E501 + """fake_outer_composite_serialize # noqa: E501 + + Test serialization of object with outer number type # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_composite_serialize_with_http_info(async=True) @@ -156,14 +158,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -172,7 +174,6 @@ class FakeApi(object): params[key] = val del params['kwargs'] - collection_formats = {} path_params = {} @@ -188,26 +189,28 @@ class FakeApi(object): if 'body' in params: body_params = params['body'] # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake/outer/composite', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='OuterComposite', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake/outer/composite', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='OuterComposite', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def fake_outer_number_serialize(self, **kwargs): - """ - Test serialization of outer number types + def fake_outer_number_serialize(self, **kwargs): # noqa: E501 + """fake_outer_number_serialize # noqa: E501 + + Test serialization of outer number types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_number_serialize(async=True) @@ -221,14 +224,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.fake_outer_number_serialize_with_http_info(**kwargs) + return self.fake_outer_number_serialize_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.fake_outer_number_serialize_with_http_info(**kwargs) + (data) = self.fake_outer_number_serialize_with_http_info(**kwargs) # noqa: E501 return data - def fake_outer_number_serialize_with_http_info(self, **kwargs): - """ - Test serialization of outer number types + def fake_outer_number_serialize_with_http_info(self, **kwargs): # noqa: E501 + """fake_outer_number_serialize # noqa: E501 + + Test serialization of outer number types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_number_serialize_with_http_info(async=True) @@ -241,14 +245,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -257,7 +261,6 @@ class FakeApi(object): params[key] = val del params['kwargs'] - collection_formats = {} path_params = {} @@ -273,26 +276,28 @@ class FakeApi(object): if 'body' in params: body_params = params['body'] # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake/outer/number', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='OuterNumber', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake/outer/number', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='OuterNumber', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def fake_outer_string_serialize(self, **kwargs): - """ - Test serialization of outer string types + def fake_outer_string_serialize(self, **kwargs): # noqa: E501 + """fake_outer_string_serialize # noqa: E501 + + Test serialization of outer string types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_string_serialize(async=True) @@ -306,14 +311,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.fake_outer_string_serialize_with_http_info(**kwargs) + return self.fake_outer_string_serialize_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.fake_outer_string_serialize_with_http_info(**kwargs) + (data) = self.fake_outer_string_serialize_with_http_info(**kwargs) # noqa: E501 return data - def fake_outer_string_serialize_with_http_info(self, **kwargs): - """ - Test serialization of outer string types + def fake_outer_string_serialize_with_http_info(self, **kwargs): # noqa: E501 + """fake_outer_string_serialize # noqa: E501 + + Test serialization of outer string types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_string_serialize_with_http_info(async=True) @@ -326,14 +332,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -342,7 +348,6 @@ class FakeApi(object): params[key] = val del params['kwargs'] - collection_formats = {} path_params = {} @@ -358,27 +363,28 @@ class FakeApi(object): if 'body' in params: body_params = params['body'] # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake/outer/string', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='OuterString', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake/outer/string', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='OuterString', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def test_client_model(self, body, **kwargs): - """ - To test \"client\" model - To test \"client\" model + def test_client_model(self, body, **kwargs): # noqa: E501 + """To test \"client\" model # noqa: E501 + + To test \"client\" model # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_client_model(body, async=True) @@ -392,15 +398,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_client_model_with_http_info(body, **kwargs) + return self.test_client_model_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.test_client_model_with_http_info(body, **kwargs) + (data) = self.test_client_model_with_http_info(body, **kwargs) # noqa: E501 return data - def test_client_model_with_http_info(self, body, **kwargs): - """ - To test \"client\" model - To test \"client\" model + def test_client_model_with_http_info(self, body, **kwargs): # noqa: E501 + """To test \"client\" model # noqa: E501 + + To test \"client\" model # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_client_model_with_http_info(body, async=True) @@ -413,14 +419,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -429,9 +435,9 @@ class FakeApi(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 `test_client_model`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `test_client_model`") # noqa: E501 collection_formats = {} @@ -448,35 +454,36 @@ class FakeApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake', 'PATCH', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Client', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake', 'PATCH', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Client', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def test_endpoint_parameters(self, number, double, pattern_without_delimiter, byte, **kwargs): - """ - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + def test_endpoint_parameters(self, number, double, pattern_without_delimiter, byte, **kwargs): # noqa: E501 + """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 + + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, async=True) @@ -503,15 +510,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, **kwargs) + return self.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, **kwargs) # noqa: E501 else: - (data) = self.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, **kwargs) + (data) = self.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, **kwargs) # noqa: E501 return data - def test_endpoint_parameters_with_http_info(self, number, double, pattern_without_delimiter, byte, **kwargs): - """ - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + def test_endpoint_parameters_with_http_info(self, number, double, pattern_without_delimiter, byte, **kwargs): # noqa: E501 + """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 + + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, async=True) @@ -537,14 +544,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['number', 'double', 'pattern_without_delimiter', 'byte', 'integer', 'int32', 'int64', 'float', 'string', 'binary', 'date', 'date_time', 'password', 'param_callback'] + all_params = ['number', 'double', 'pattern_without_delimiter', 'byte', 'integer', 'int32', 'int64', 'float', 'string', 'binary', 'date', 'date_time', 'password', 'param_callback'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -553,45 +560,50 @@ 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`") + if ('number' not in params or + params['number'] is None): + raise ValueError("Missing the required parameter `number` when calling `test_endpoint_parameters`") # noqa: E501 # verify the required parameter 'double' is set - if ('double' not in params) or (params['double'] is None): - raise ValueError("Missing the required parameter `double` when calling `test_endpoint_parameters`") + if ('double' not in params or + params['double'] is None): + raise ValueError("Missing the required parameter `double` when calling `test_endpoint_parameters`") # noqa: E501 # verify the required parameter 'pattern_without_delimiter' is set - if ('pattern_without_delimiter' not in params) or (params['pattern_without_delimiter'] is None): - raise ValueError("Missing the required parameter `pattern_without_delimiter` when calling `test_endpoint_parameters`") + if ('pattern_without_delimiter' not in params or + params['pattern_without_delimiter'] is None): + raise ValueError("Missing the required parameter `pattern_without_delimiter` when calling `test_endpoint_parameters`") # noqa: E501 # verify the required parameter 'byte' is set - 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: - 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: - 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: - 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: - raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value greater than or equal to `67.8`") - if 'pattern_without_delimiter' in params and not re.search('^[A-Z].*', params['pattern_without_delimiter']): - raise ValueError("Invalid value for parameter `pattern_without_delimiter` when calling `test_endpoint_parameters`, must conform to the pattern `/^[A-Z].*/`") - if 'integer' in params and params['integer'] > 100: - raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100`") - if 'integer' in params and params['integer'] < 10: - raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value greater than or equal to `10`") - if 'int32' in params and params['int32'] > 200: - raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value less than or equal to `200`") - if 'int32' in params and params['int32'] < 20: - raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value greater than or equal to `20`") - 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 '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 '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: - raise ValueError("Invalid value for parameter `password` when calling `test_endpoint_parameters`, length must be greater than or equal to `10`") + if ('byte' not in params or + params['byte'] is None): + raise ValueError("Missing the required parameter `byte` when calling `test_endpoint_parameters`") # noqa: E501 + if 'number' in params and params['number'] > 543.2: # noqa: E501 + raise ValueError("Invalid value for parameter `number` when calling `test_endpoint_parameters`, must be a value less than or equal to `543.2`") # noqa: E501 + if 'number' in params and params['number'] < 32.1: # noqa: E501 + raise ValueError("Invalid value for parameter `number` when calling `test_endpoint_parameters`, must be a value greater than or equal to `32.1`") # noqa: E501 + if 'double' in params and params['double'] > 123.4: # noqa: E501 + raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value less than or equal to `123.4`") # noqa: E501 + if 'double' in params and params['double'] < 67.8: # noqa: E501 + raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value greater than or equal to `67.8`") # noqa: E501 + if 'pattern_without_delimiter' in params and not re.search('^[A-Z].*', params['pattern_without_delimiter']): # noqa: E501 + raise ValueError("Invalid value for parameter `pattern_without_delimiter` when calling `test_endpoint_parameters`, must conform to the pattern `/^[A-Z].*/`") # noqa: E501 + if 'integer' in params and params['integer'] > 100: # noqa: E501 + raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100`") # noqa: E501 + if 'integer' in params and params['integer'] < 10: # noqa: E501 + raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value greater than or equal to `10`") # noqa: E501 + if 'int32' in params and params['int32'] > 200: # noqa: E501 + raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value less than or equal to `200`") # noqa: E501 + if 'int32' in params and params['int32'] < 20: # noqa: E501 + raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value greater than or equal to `20`") # noqa: E501 + if 'float' in params and params['float'] > 987.6: # noqa: E501 + raise ValueError("Invalid value for parameter `float` when calling `test_endpoint_parameters`, must be a value less than or equal to `987.6`") # noqa: E501 + if 'string' in params and not re.search('[a-z]', params['string'], flags=re.IGNORECASE): # noqa: E501 + raise ValueError("Invalid value for parameter `string` when calling `test_endpoint_parameters`, must conform to the pattern `/[a-z]/i`") # noqa: E501 + 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`") # noqa: E501 + 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`") # noqa: E501 collection_formats = {} path_params = {} @@ -603,65 +615,66 @@ class FakeApi(object): form_params = [] local_var_files = {} if 'integer' in params: - form_params.append(('integer', params['integer'])) + form_params.append(('integer', params['integer'])) # noqa: E501 if 'int32' in params: - form_params.append(('int32', params['int32'])) + form_params.append(('int32', params['int32'])) # noqa: E501 if 'int64' in params: - form_params.append(('int64', params['int64'])) + form_params.append(('int64', params['int64'])) # noqa: E501 if 'number' in params: - form_params.append(('number', params['number'])) + form_params.append(('number', params['number'])) # noqa: E501 if 'float' in params: - form_params.append(('float', params['float'])) + form_params.append(('float', params['float'])) # noqa: E501 if 'double' in params: - form_params.append(('double', params['double'])) + form_params.append(('double', params['double'])) # noqa: E501 if 'string' in params: - form_params.append(('string', params['string'])) + form_params.append(('string', params['string'])) # noqa: E501 if 'pattern_without_delimiter' in params: - form_params.append(('pattern_without_delimiter', params['pattern_without_delimiter'])) + form_params.append(('pattern_without_delimiter', params['pattern_without_delimiter'])) # noqa: E501 if 'byte' in params: - form_params.append(('byte', params['byte'])) + form_params.append(('byte', params['byte'])) # noqa: E501 if 'binary' in params: - form_params.append(('binary', params['binary'])) + form_params.append(('binary', params['binary'])) # noqa: E501 if 'date' in params: - form_params.append(('date', params['date'])) + form_params.append(('date', params['date'])) # noqa: E501 if 'date_time' in params: - form_params.append(('dateTime', params['date_time'])) + form_params.append(('dateTime', params['date_time'])) # noqa: E501 if 'password' in params: - form_params.append(('password', params['password'])) + form_params.append(('password', params['password'])) # noqa: E501 if 'param_callback' in params: - form_params.append(('callback', params['param_callback'])) + form_params.append(('callback', params['param_callback'])) # noqa: E501 body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml; charset=utf-8', 'application/json; charset=utf-8']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml; charset=utf-8', 'application/json; charset=utf-8']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/xml; charset=utf-8', 'application/json; charset=utf-8']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/xml; charset=utf-8', 'application/json; charset=utf-8']) # noqa: E501 # Authentication setting - auth_settings = ['http_basic_test'] + auth_settings = ['http_basic_test'] # noqa: E501 - return self.api_client.call_api('/fake', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def test_enum_parameters(self, **kwargs): - """ - To test enum parameters - To test enum parameters + def test_enum_parameters(self, **kwargs): # noqa: E501 + """To test enum parameters # noqa: E501 + + To test enum parameters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_enum_parameters(async=True) @@ -682,15 +695,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_enum_parameters_with_http_info(**kwargs) + return self.test_enum_parameters_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.test_enum_parameters_with_http_info(**kwargs) + (data) = self.test_enum_parameters_with_http_info(**kwargs) # noqa: E501 return data - def test_enum_parameters_with_http_info(self, **kwargs): - """ - To test enum parameters - To test enum parameters + def test_enum_parameters_with_http_info(self, **kwargs): # noqa: E501 + """To test enum parameters # noqa: E501 + + To test enum parameters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_enum_parameters_with_http_info(async=True) @@ -710,14 +723,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['enum_form_string_array', 'enum_form_string', 'enum_header_string_array', 'enum_header_string', 'enum_query_string_array', 'enum_query_string', 'enum_query_integer', 'enum_query_double'] + all_params = ['enum_form_string_array', 'enum_form_string', 'enum_header_string_array', 'enum_header_string', 'enum_query_string_array', 'enum_query_string', 'enum_query_integer', 'enum_query_double'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -726,68 +739,163 @@ class FakeApi(object): params[key] = val del params['kwargs'] - collection_formats = {} path_params = {} query_params = [] if 'enum_query_string_array' in params: - query_params.append(('enum_query_string_array', params['enum_query_string_array'])) - collection_formats['enum_query_string_array'] = 'csv' + query_params.append(('enum_query_string_array', params['enum_query_string_array'])) # noqa: E501 + collection_formats['enum_query_string_array'] = 'csv' # noqa: E501 if 'enum_query_string' in params: - query_params.append(('enum_query_string', params['enum_query_string'])) + query_params.append(('enum_query_string', params['enum_query_string'])) # noqa: E501 if 'enum_query_integer' in params: - query_params.append(('enum_query_integer', params['enum_query_integer'])) + query_params.append(('enum_query_integer', params['enum_query_integer'])) # noqa: E501 header_params = {} if 'enum_header_string_array' in params: - header_params['enum_header_string_array'] = params['enum_header_string_array'] - collection_formats['enum_header_string_array'] = 'csv' + header_params['enum_header_string_array'] = params['enum_header_string_array'] # noqa: E501 + collection_formats['enum_header_string_array'] = 'csv' # noqa: E501 if 'enum_header_string' in params: - header_params['enum_header_string'] = params['enum_header_string'] + header_params['enum_header_string'] = params['enum_header_string'] # noqa: E501 form_params = [] local_var_files = {} if 'enum_form_string_array' in params: - form_params.append(('enum_form_string_array', params['enum_form_string_array'])) - collection_formats['enum_form_string_array'] = 'csv' + form_params.append(('enum_form_string_array', params['enum_form_string_array'])) # noqa: E501 + collection_formats['enum_form_string_array'] = 'csv' # noqa: E501 if 'enum_form_string' in params: - form_params.append(('enum_form_string', params['enum_form_string'])) + form_params.append(('enum_form_string', params['enum_form_string'])) # noqa: E501 if 'enum_query_double' in params: - form_params.append(('enum_query_double', params['enum_query_double'])) + form_params.append(('enum_query_double', params['enum_query_double'])) # noqa: E501 body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['*/*']) + header_params['Accept'] = self.api_client.select_header_accept( + ['*/*']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['*/*']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['*/*']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def test_json_form_data(self, param, param2, **kwargs): + def test_inline_additional_properties(self, param, **kwargs): # noqa: E501 + """test inline additionalProperties # noqa: E501 + + # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async=True + >>> thread = api.test_inline_additional_properties(param, async=True) + >>> result = thread.get() + + :param async bool + :param object param: request body (required) + :return: None + If the method is called asynchronously, + returns the request thread. """ - test json serialization of form data - + kwargs['_return_http_data_only'] = True + if kwargs.get('async'): + return self.test_inline_additional_properties_with_http_info(param, **kwargs) # noqa: E501 + else: + (data) = self.test_inline_additional_properties_with_http_info(param, **kwargs) # noqa: E501 + return data + + def test_inline_additional_properties_with_http_info(self, param, **kwargs): # noqa: E501 + """test inline additionalProperties # noqa: E501 + + # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async=True + >>> thread = api.test_inline_additional_properties_with_http_info(param, async=True) + >>> result = thread.get() + + :param async bool + :param object param: request body (required) + :return: None + If the method is called asynchronously, + returns the request thread. + """ + + all_params = ['param'] # noqa: E501 + all_params.append('async') + all_params.append('_return_http_data_only') + all_params.append('_preload_content') + all_params.append('_request_timeout') + + params = locals() + for key, val in six.iteritems(params['kwargs']): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method test_inline_additional_properties" % key + ) + params[key] = val + del params['kwargs'] + # verify the required parameter 'param' is set + if ('param' not in params or + params['param'] is None): + raise ValueError("Missing the required parameter `param` when calling `test_inline_additional_properties`") # noqa: E501 + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if 'param' in params: + body_params = params['param'] + # HTTP header `Content-Type` + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json']) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + '/fake/inline-additionalProperties', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) + + def test_json_form_data(self, param, param2, **kwargs): # noqa: E501 + """test json serialization of form data # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_json_form_data(param, param2, async=True) @@ -802,15 +910,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_json_form_data_with_http_info(param, param2, **kwargs) + return self.test_json_form_data_with_http_info(param, param2, **kwargs) # noqa: E501 else: - (data) = self.test_json_form_data_with_http_info(param, param2, **kwargs) + (data) = self.test_json_form_data_with_http_info(param, param2, **kwargs) # noqa: E501 return data - def test_json_form_data_with_http_info(self, param, param2, **kwargs): - """ - test json serialization of form data - + def test_json_form_data_with_http_info(self, param, param2, **kwargs): # noqa: E501 + """test json serialization of form data # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_json_form_data_with_http_info(param, param2, async=True) @@ -824,14 +932,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['param', 'param2'] + all_params = ['param', 'param2'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -840,12 +948,13 @@ class FakeApi(object): params[key] = val del params['kwargs'] # verify the required parameter 'param' is set - if ('param' not in params) or (params['param'] is None): - raise ValueError("Missing the required parameter `param` when calling `test_json_form_data`") + if ('param' not in params or + params['param'] is None): + raise ValueError("Missing the required parameter `param` when calling `test_json_form_data`") # noqa: E501 # verify the required parameter 'param2' is set - if ('param2' not in params) or (params['param2'] is None): - raise ValueError("Missing the required parameter `param2` when calling `test_json_form_data`") - + if ('param2' not in params or + params['param2'] is None): + raise ValueError("Missing the required parameter `param2` when calling `test_json_form_data`") # noqa: E501 collection_formats = {} @@ -858,29 +967,30 @@ class FakeApi(object): form_params = [] local_var_files = {} if 'param' in params: - form_params.append(('param', params['param'])) + form_params.append(('param', params['param'])) # noqa: E501 if 'param2' in params: - form_params.append(('param2', params['param2'])) + form_params.append(('param2', params['param2'])) # noqa: E501 body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake/jsonFormData', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake/jsonFormData', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python-asyncio/petstore_api/apis/fake_classname_tags_123_api.py b/samples/client/petstore/python-tornado/petstore_api/api/fake_classname_tags_123_api.py similarity index 60% rename from samples/client/petstore/python-asyncio/petstore_api/apis/fake_classname_tags_123_api.py rename to samples/client/petstore/python-tornado/petstore_api/api/fake_classname_tags_123_api.py index da75ad3cccd..6b6606dc096 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/apis/fake_classname_tags_123_api.py +++ b/samples/client/petstore/python-tornado/petstore_api/api/fake_classname_tags_123_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class FakeClassnameTags123Api(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,9 +33,9 @@ class FakeClassnameTags123Api(object): api_client = ApiClient() self.api_client = api_client - def test_classname(self, body, **kwargs): - """ - To test class name in snake case + def test_classname(self, body, **kwargs): # noqa: E501 + """To test class name in snake case # noqa: E501 + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_classname(body, async=True) @@ -51,14 +49,14 @@ class FakeClassnameTags123Api(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_classname_with_http_info(body, **kwargs) + return self.test_classname_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.test_classname_with_http_info(body, **kwargs) + (data) = self.test_classname_with_http_info(body, **kwargs) # noqa: E501 return data - def test_classname_with_http_info(self, body, **kwargs): - """ - To test class name in snake case + def test_classname_with_http_info(self, body, **kwargs): # noqa: E501 + """To test class name in snake case # noqa: E501 + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_classname_with_http_info(body, async=True) @@ -71,14 +69,14 @@ class FakeClassnameTags123Api(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -87,9 +85,9 @@ class FakeClassnameTags123Api(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 `test_classname`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `test_classname`") # noqa: E501 collection_formats = {} @@ -106,27 +104,28 @@ class FakeClassnameTags123Api(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json']) # noqa: E501 # Authentication setting - auth_settings = ['api_key_query'] + auth_settings = ['api_key_query'] # noqa: E501 - return self.api_client.call_api('/fake_classname_test', 'PATCH', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Client', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake_classname_test', 'PATCH', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Client', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python-asyncio/petstore_api/apis/pet_api.py b/samples/client/petstore/python-tornado/petstore_api/api/pet_api.py similarity index 57% rename from samples/client/petstore/python-asyncio/petstore_api/apis/pet_api.py rename to samples/client/petstore/python-tornado/petstore_api/api/pet_api.py index 51b6ce82540..ff1026f3fae 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/apis/pet_api.py +++ b/samples/client/petstore/python-tornado/petstore_api/api/pet_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class PetApi(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,10 +33,10 @@ class PetApi(object): api_client = ApiClient() self.api_client = api_client - def add_pet(self, body, **kwargs): - """ - Add a new pet to the store - + def add_pet(self, body, **kwargs): # noqa: E501 + """Add a new pet to the store # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.add_pet(body, async=True) @@ -52,15 +50,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.add_pet_with_http_info(body, **kwargs) + return self.add_pet_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.add_pet_with_http_info(body, **kwargs) + (data) = self.add_pet_with_http_info(body, **kwargs) # noqa: E501 return data - def add_pet_with_http_info(self, body, **kwargs): - """ - Add a new pet to the store - + def add_pet_with_http_info(self, body, **kwargs): # noqa: E501 + """Add a new pet to the store # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.add_pet_with_http_info(body, async=True) @@ -73,14 +71,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -89,9 +87,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `add_pet`") # noqa: E501 collection_formats = {} @@ -108,35 +106,36 @@ class PetApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json', 'application/xml']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json', 'application/xml']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def delete_pet(self, pet_id, **kwargs): - """ - Deletes a pet - + def delete_pet(self, pet_id, **kwargs): # noqa: E501 + """Deletes a pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_pet(pet_id, async=True) @@ -151,15 +150,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.delete_pet_with_http_info(pet_id, **kwargs) + return self.delete_pet_with_http_info(pet_id, **kwargs) # noqa: E501 else: - (data) = self.delete_pet_with_http_info(pet_id, **kwargs) + (data) = self.delete_pet_with_http_info(pet_id, **kwargs) # noqa: E501 return data - def delete_pet_with_http_info(self, pet_id, **kwargs): - """ - Deletes a pet - + def delete_pet_with_http_info(self, pet_id, **kwargs): # noqa: E501 + """Deletes a pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_pet_with_http_info(pet_id, async=True) @@ -173,14 +172,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['pet_id', 'api_key'] + all_params = ['pet_id', 'api_key'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -189,52 +188,53 @@ 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`") - + if ('pet_id' not in params or + params['pet_id'] is None): + raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") # noqa: E501 collection_formats = {} path_params = {} if 'pet_id' in params: - path_params['petId'] = params['pet_id'] + path_params['petId'] = params['pet_id'] # noqa: E501 query_params = [] header_params = {} if 'api_key' in params: - header_params['api_key'] = params['api_key'] + header_params['api_key'] = params['api_key'] # noqa: E501 form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet/{petId}', 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/{petId}', 'DELETE', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def find_pets_by_status(self, status, **kwargs): - """ - Finds Pets by status - Multiple status values can be provided with comma separated strings + def find_pets_by_status(self, status, **kwargs): # noqa: E501 + """Finds Pets by status # noqa: E501 + + Multiple status values can be provided with comma separated strings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.find_pets_by_status(status, async=True) @@ -248,15 +248,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.find_pets_by_status_with_http_info(status, **kwargs) + return self.find_pets_by_status_with_http_info(status, **kwargs) # noqa: E501 else: - (data) = self.find_pets_by_status_with_http_info(status, **kwargs) + (data) = self.find_pets_by_status_with_http_info(status, **kwargs) # noqa: E501 return data - def find_pets_by_status_with_http_info(self, status, **kwargs): - """ - Finds Pets by status - Multiple status values can be provided with comma separated strings + def find_pets_by_status_with_http_info(self, status, **kwargs): # noqa: E501 + """Finds Pets by status # noqa: E501 + + Multiple status values can be provided with comma separated strings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.find_pets_by_status_with_http_info(status, async=True) @@ -269,14 +269,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['status'] + all_params = ['status'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -285,9 +285,9 @@ 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`") - + if ('status' not in params or + params['status'] is None): + raise ValueError("Missing the required parameter `status` when calling `find_pets_by_status`") # noqa: E501 collection_formats = {} @@ -295,8 +295,8 @@ class PetApi(object): query_params = [] if 'status' in params: - query_params.append(('status', params['status'])) - collection_formats['status'] = 'csv' + query_params.append(('status', params['status'])) # noqa: E501 + collection_formats['status'] = 'csv' # noqa: E501 header_params = {} @@ -305,31 +305,32 @@ class PetApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet/findByStatus', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[Pet]', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/findByStatus', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='list[Pet]', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def find_pets_by_tags(self, tags, **kwargs): - """ - Finds Pets by tags - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + def find_pets_by_tags(self, tags, **kwargs): # noqa: E501 + """Finds Pets by tags # noqa: E501 + + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.find_pets_by_tags(tags, async=True) @@ -343,15 +344,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.find_pets_by_tags_with_http_info(tags, **kwargs) + return self.find_pets_by_tags_with_http_info(tags, **kwargs) # noqa: E501 else: - (data) = self.find_pets_by_tags_with_http_info(tags, **kwargs) + (data) = self.find_pets_by_tags_with_http_info(tags, **kwargs) # noqa: E501 return data - def find_pets_by_tags_with_http_info(self, tags, **kwargs): - """ - Finds Pets by tags - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + def find_pets_by_tags_with_http_info(self, tags, **kwargs): # noqa: E501 + """Finds Pets by tags # noqa: E501 + + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.find_pets_by_tags_with_http_info(tags, async=True) @@ -364,14 +365,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['tags'] + all_params = ['tags'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -380,9 +381,9 @@ 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`") - + if ('tags' not in params or + params['tags'] is None): + raise ValueError("Missing the required parameter `tags` when calling `find_pets_by_tags`") # noqa: E501 collection_formats = {} @@ -390,8 +391,8 @@ class PetApi(object): query_params = [] if 'tags' in params: - query_params.append(('tags', params['tags'])) - collection_formats['tags'] = 'csv' + query_params.append(('tags', params['tags'])) # noqa: E501 + collection_formats['tags'] = 'csv' # noqa: E501 header_params = {} @@ -400,31 +401,32 @@ class PetApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet/findByTags', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[Pet]', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/findByTags', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='list[Pet]', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def get_pet_by_id(self, pet_id, **kwargs): - """ - Find pet by ID - Returns a single pet + def get_pet_by_id(self, pet_id, **kwargs): # noqa: E501 + """Find pet by ID # noqa: E501 + + Returns a single pet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_pet_by_id(pet_id, async=True) @@ -438,15 +440,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.get_pet_by_id_with_http_info(pet_id, **kwargs) + return self.get_pet_by_id_with_http_info(pet_id, **kwargs) # noqa: E501 else: - (data) = self.get_pet_by_id_with_http_info(pet_id, **kwargs) + (data) = self.get_pet_by_id_with_http_info(pet_id, **kwargs) # noqa: E501 return data - def get_pet_by_id_with_http_info(self, pet_id, **kwargs): - """ - Find pet by ID - Returns a single pet + def get_pet_by_id_with_http_info(self, pet_id, **kwargs): # noqa: E501 + """Find pet by ID # noqa: E501 + + Returns a single pet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_pet_by_id_with_http_info(pet_id, async=True) @@ -459,14 +461,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['pet_id'] + all_params = ['pet_id'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -475,15 +477,15 @@ 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`") - + 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`") # noqa: E501 collection_formats = {} path_params = {} if 'pet_id' in params: - path_params['petId'] = params['pet_id'] + path_params['petId'] = params['pet_id'] # noqa: E501 query_params = [] @@ -494,31 +496,32 @@ class PetApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = ['api_key'] + auth_settings = ['api_key'] # noqa: E501 - return self.api_client.call_api('/pet/{petId}', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Pet', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/{petId}', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Pet', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def update_pet(self, body, **kwargs): - """ - Update an existing pet - + def update_pet(self, body, **kwargs): # noqa: E501 + """Update an existing pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_pet(body, async=True) @@ -532,15 +535,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.update_pet_with_http_info(body, **kwargs) + return self.update_pet_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.update_pet_with_http_info(body, **kwargs) + (data) = self.update_pet_with_http_info(body, **kwargs) # noqa: E501 return data - def update_pet_with_http_info(self, body, **kwargs): - """ - Update an existing pet - + def update_pet_with_http_info(self, body, **kwargs): # noqa: E501 + """Update an existing pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_pet_with_http_info(body, async=True) @@ -553,14 +556,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -569,9 +572,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `update_pet`") # noqa: E501 collection_formats = {} @@ -588,35 +591,36 @@ class PetApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json', 'application/xml']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json', 'application/xml']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet', 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet', 'PUT', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def update_pet_with_form(self, pet_id, **kwargs): - """ - Updates a pet in the store with form data - + def update_pet_with_form(self, pet_id, **kwargs): # noqa: E501 + """Updates a pet in the store with form data # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_pet_with_form(pet_id, async=True) @@ -632,15 +636,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.update_pet_with_form_with_http_info(pet_id, **kwargs) + return self.update_pet_with_form_with_http_info(pet_id, **kwargs) # noqa: E501 else: - (data) = self.update_pet_with_form_with_http_info(pet_id, **kwargs) + (data) = self.update_pet_with_form_with_http_info(pet_id, **kwargs) # noqa: E501 return data - def update_pet_with_form_with_http_info(self, pet_id, **kwargs): - """ - Updates a pet in the store with form data - + def update_pet_with_form_with_http_info(self, pet_id, **kwargs): # noqa: E501 + """Updates a pet in the store with form data # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_pet_with_form_with_http_info(pet_id, async=True) @@ -655,14 +659,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['pet_id', 'name', 'status'] + all_params = ['pet_id', 'name', 'status'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -671,15 +675,15 @@ 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`") - + 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`") # noqa: E501 collection_formats = {} path_params = {} if 'pet_id' in params: - path_params['petId'] = params['pet_id'] + path_params['petId'] = params['pet_id'] # noqa: E501 query_params = [] @@ -688,41 +692,42 @@ class PetApi(object): form_params = [] local_var_files = {} if 'name' in params: - form_params.append(('name', params['name'])) + form_params.append(('name', params['name'])) # noqa: E501 if 'status' in params: - form_params.append(('status', params['status'])) + form_params.append(('status', params['status'])) # noqa: E501 body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/x-www-form-urlencoded']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/x-www-form-urlencoded']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet/{petId}', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/{petId}', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def upload_file(self, pet_id, **kwargs): - """ - uploads an image - + def upload_file(self, pet_id, **kwargs): # noqa: E501 + """uploads an image # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.upload_file(pet_id, async=True) @@ -738,15 +743,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.upload_file_with_http_info(pet_id, **kwargs) + return self.upload_file_with_http_info(pet_id, **kwargs) # noqa: E501 else: - (data) = self.upload_file_with_http_info(pet_id, **kwargs) + (data) = self.upload_file_with_http_info(pet_id, **kwargs) # noqa: E501 return data - def upload_file_with_http_info(self, pet_id, **kwargs): - """ - uploads an image - + def upload_file_with_http_info(self, pet_id, **kwargs): # noqa: E501 + """uploads an image # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.upload_file_with_http_info(pet_id, async=True) @@ -761,14 +766,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['pet_id', 'additional_metadata', 'file'] + all_params = ['pet_id', 'additional_metadata', 'file'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -777,15 +782,15 @@ 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`") - + if ('pet_id' not in params or + params['pet_id'] is None): + raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") # noqa: E501 collection_formats = {} path_params = {} if 'pet_id' in params: - path_params['petId'] = params['pet_id'] + path_params['petId'] = params['pet_id'] # noqa: E501 query_params = [] @@ -794,33 +799,34 @@ class PetApi(object): form_params = [] local_var_files = {} if 'additional_metadata' in params: - form_params.append(('additionalMetadata', params['additional_metadata'])) + form_params.append(('additionalMetadata', params['additional_metadata'])) # noqa: E501 if 'file' in params: - local_var_files['file'] = params['file'] + local_var_files['file'] = params['file'] # noqa: E501 body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['multipart/form-data']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['multipart/form-data']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet/{petId}/uploadImage', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='ApiResponse', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/{petId}/uploadImage', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='ApiResponse', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python-tornado/petstore_api/apis/store_api.py b/samples/client/petstore/python-tornado/petstore_api/api/store_api.py similarity index 57% rename from samples/client/petstore/python-tornado/petstore_api/apis/store_api.py rename to samples/client/petstore/python-tornado/petstore_api/api/store_api.py index e9d9599c363..ebb9a4eb27a 100644 --- a/samples/client/petstore/python-tornado/petstore_api/apis/store_api.py +++ b/samples/client/petstore/python-tornado/petstore_api/api/store_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class StoreApi(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,10 +33,10 @@ class StoreApi(object): api_client = ApiClient() self.api_client = api_client - def delete_order(self, order_id, **kwargs): - """ - Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + def delete_order(self, order_id, **kwargs): # noqa: E501 + """Delete purchase order by ID # noqa: E501 + + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_order(order_id, async=True) @@ -52,15 +50,15 @@ class StoreApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.delete_order_with_http_info(order_id, **kwargs) + return self.delete_order_with_http_info(order_id, **kwargs) # noqa: E501 else: - (data) = self.delete_order_with_http_info(order_id, **kwargs) + (data) = self.delete_order_with_http_info(order_id, **kwargs) # noqa: E501 return data - def delete_order_with_http_info(self, order_id, **kwargs): - """ - Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + def delete_order_with_http_info(self, order_id, **kwargs): # noqa: E501 + """Delete purchase order by ID # noqa: E501 + + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_order_with_http_info(order_id, async=True) @@ -73,14 +71,14 @@ class StoreApi(object): returns the request thread. """ - all_params = ['order_id'] + all_params = ['order_id'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -89,15 +87,15 @@ 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' not in params or + params['order_id'] is None): + raise ValueError("Missing the required parameter `order_id` when calling `delete_order`") # noqa: E501 collection_formats = {} path_params = {} if 'order_id' in params: - path_params['order_id'] = params['order_id'] + path_params['order_id'] = params['order_id'] # noqa: E501 query_params = [] @@ -108,31 +106,32 @@ class StoreApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/store/order/{order_id}', 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/store/order/{order_id}', 'DELETE', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def get_inventory(self, **kwargs): - """ - Returns pet inventories by status - Returns a map of status codes to quantities + def get_inventory(self, **kwargs): # noqa: E501 + """Returns pet inventories by status # noqa: E501 + + Returns a map of status codes to quantities # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_inventory(async=True) @@ -145,15 +144,15 @@ class StoreApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.get_inventory_with_http_info(**kwargs) + return self.get_inventory_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.get_inventory_with_http_info(**kwargs) + (data) = self.get_inventory_with_http_info(**kwargs) # noqa: E501 return data - def get_inventory_with_http_info(self, **kwargs): - """ - Returns pet inventories by status - Returns a map of status codes to quantities + def get_inventory_with_http_info(self, **kwargs): # noqa: E501 + """Returns pet inventories by status # noqa: E501 + + Returns a map of status codes to quantities # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_inventory_with_http_info(async=True) @@ -165,14 +164,14 @@ class StoreApi(object): returns the request thread. """ - all_params = [] + all_params = [] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -194,31 +193,32 @@ class StoreApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 # Authentication setting - auth_settings = ['api_key'] + auth_settings = ['api_key'] # noqa: E501 - return self.api_client.call_api('/store/inventory', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='dict(str, int)', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/store/inventory', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='dict(str, int)', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def get_order_by_id(self, order_id, **kwargs): - """ - Find purchase order by ID - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + def get_order_by_id(self, order_id, **kwargs): # noqa: E501 + """Find purchase order by ID # noqa: E501 + + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_order_by_id(order_id, async=True) @@ -232,15 +232,15 @@ class StoreApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.get_order_by_id_with_http_info(order_id, **kwargs) + return self.get_order_by_id_with_http_info(order_id, **kwargs) # noqa: E501 else: - (data) = self.get_order_by_id_with_http_info(order_id, **kwargs) + (data) = self.get_order_by_id_with_http_info(order_id, **kwargs) # noqa: E501 return data - def get_order_by_id_with_http_info(self, order_id, **kwargs): - """ - Find purchase order by ID - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + def get_order_by_id_with_http_info(self, order_id, **kwargs): # noqa: E501 + """Find purchase order by ID # noqa: E501 + + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_order_by_id_with_http_info(order_id, async=True) @@ -253,14 +253,14 @@ class StoreApi(object): returns the request thread. """ - all_params = ['order_id'] + all_params = ['order_id'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -269,19 +269,19 @@ 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: - raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5`") - if 'order_id' in params and params['order_id'] < 1: - raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value greater than or equal to `1`") + 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`") # noqa: E501 + if 'order_id' in params and params['order_id'] > 5: # noqa: E501 + raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5`") # noqa: E501 + if 'order_id' in params and params['order_id'] < 1: # noqa: E501 + raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value greater than or equal to `1`") # noqa: E501 collection_formats = {} path_params = {} if 'order_id' in params: - path_params['order_id'] = params['order_id'] + path_params['order_id'] = params['order_id'] # noqa: E501 query_params = [] @@ -292,31 +292,32 @@ class StoreApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/store/order/{order_id}', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Order', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/store/order/{order_id}', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Order', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def place_order(self, body, **kwargs): - """ - Place an order for a pet - + def place_order(self, body, **kwargs): # noqa: E501 + """Place an order for a pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.place_order(body, async=True) @@ -330,15 +331,15 @@ class StoreApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.place_order_with_http_info(body, **kwargs) + return self.place_order_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.place_order_with_http_info(body, **kwargs) + (data) = self.place_order_with_http_info(body, **kwargs) # noqa: E501 return data - def place_order_with_http_info(self, body, **kwargs): - """ - Place an order for a pet - + def place_order_with_http_info(self, body, **kwargs): # noqa: E501 + """Place an order for a pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.place_order_with_http_info(body, async=True) @@ -351,14 +352,14 @@ class StoreApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -367,9 +368,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `place_order`") # noqa: E501 collection_formats = {} @@ -386,23 +387,24 @@ class StoreApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/store/order', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Order', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/store/order', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Order', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python-tornado/petstore_api/apis/user_api.py b/samples/client/petstore/python-tornado/petstore_api/api/user_api.py similarity index 57% rename from samples/client/petstore/python-tornado/petstore_api/apis/user_api.py rename to samples/client/petstore/python-tornado/petstore_api/api/user_api.py index ffdad2dd60f..89949844aa1 100644 --- a/samples/client/petstore/python-tornado/petstore_api/apis/user_api.py +++ b/samples/client/petstore/python-tornado/petstore_api/api/user_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class UserApi(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,10 +33,10 @@ class UserApi(object): api_client = ApiClient() self.api_client = api_client - def create_user(self, body, **kwargs): - """ - Create user - This can only be done by the logged in user. + def create_user(self, body, **kwargs): # noqa: E501 + """Create user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_user(body, async=True) @@ -52,15 +50,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.create_user_with_http_info(body, **kwargs) + return self.create_user_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.create_user_with_http_info(body, **kwargs) + (data) = self.create_user_with_http_info(body, **kwargs) # noqa: E501 return data - def create_user_with_http_info(self, body, **kwargs): - """ - Create user - This can only be done by the logged in user. + def create_user_with_http_info(self, body, **kwargs): # noqa: E501 + """Create user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_user_with_http_info(body, async=True) @@ -73,14 +71,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -89,9 +87,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `create_user`") # noqa: E501 collection_formats = {} @@ -108,31 +106,32 @@ class UserApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def create_users_with_array_input(self, body, **kwargs): - """ - Creates list of users with given input array - + def create_users_with_array_input(self, body, **kwargs): # noqa: E501 + """Creates list of users with given input array # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_users_with_array_input(body, async=True) @@ -146,15 +145,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.create_users_with_array_input_with_http_info(body, **kwargs) + return self.create_users_with_array_input_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.create_users_with_array_input_with_http_info(body, **kwargs) + (data) = self.create_users_with_array_input_with_http_info(body, **kwargs) # noqa: E501 return data - def create_users_with_array_input_with_http_info(self, body, **kwargs): - """ - Creates list of users with given input array - + def create_users_with_array_input_with_http_info(self, body, **kwargs): # noqa: E501 + """Creates list of users with given input array # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_users_with_array_input_with_http_info(body, async=True) @@ -167,14 +166,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -183,9 +182,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `create_users_with_array_input`") # noqa: E501 collection_formats = {} @@ -202,31 +201,32 @@ class UserApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/createWithArray', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/createWithArray', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def create_users_with_list_input(self, body, **kwargs): - """ - Creates list of users with given input array - + def create_users_with_list_input(self, body, **kwargs): # noqa: E501 + """Creates list of users with given input array # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_users_with_list_input(body, async=True) @@ -240,15 +240,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.create_users_with_list_input_with_http_info(body, **kwargs) + return self.create_users_with_list_input_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.create_users_with_list_input_with_http_info(body, **kwargs) + (data) = self.create_users_with_list_input_with_http_info(body, **kwargs) # noqa: E501 return data - def create_users_with_list_input_with_http_info(self, body, **kwargs): - """ - Creates list of users with given input array - + def create_users_with_list_input_with_http_info(self, body, **kwargs): # noqa: E501 + """Creates list of users with given input array # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_users_with_list_input_with_http_info(body, async=True) @@ -261,14 +261,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -277,9 +277,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `create_users_with_list_input`") # noqa: E501 collection_formats = {} @@ -296,31 +296,32 @@ class UserApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/createWithList', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/createWithList', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def delete_user(self, username, **kwargs): - """ - Delete user - This can only be done by the logged in user. + def delete_user(self, username, **kwargs): # noqa: E501 + """Delete user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_user(username, async=True) @@ -334,15 +335,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.delete_user_with_http_info(username, **kwargs) + return self.delete_user_with_http_info(username, **kwargs) # noqa: E501 else: - (data) = self.delete_user_with_http_info(username, **kwargs) + (data) = self.delete_user_with_http_info(username, **kwargs) # noqa: E501 return data - def delete_user_with_http_info(self, username, **kwargs): - """ - Delete user - This can only be done by the logged in user. + def delete_user_with_http_info(self, username, **kwargs): # noqa: E501 + """Delete user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_user_with_http_info(username, async=True) @@ -355,14 +356,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['username'] + all_params = ['username'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -371,15 +372,15 @@ 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`") - + if ('username' not in params or + params['username'] is None): + raise ValueError("Missing the required parameter `username` when calling `delete_user`") # noqa: E501 collection_formats = {} path_params = {} if 'username' in params: - path_params['username'] = params['username'] + path_params['username'] = params['username'] # noqa: E501 query_params = [] @@ -390,31 +391,32 @@ class UserApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/{username}', 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/{username}', 'DELETE', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def get_user_by_name(self, username, **kwargs): - """ - Get user by user name - + def get_user_by_name(self, username, **kwargs): # noqa: E501 + """Get user by user name # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_user_by_name(username, async=True) @@ -428,15 +430,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.get_user_by_name_with_http_info(username, **kwargs) + return self.get_user_by_name_with_http_info(username, **kwargs) # noqa: E501 else: - (data) = self.get_user_by_name_with_http_info(username, **kwargs) + (data) = self.get_user_by_name_with_http_info(username, **kwargs) # noqa: E501 return data - def get_user_by_name_with_http_info(self, username, **kwargs): - """ - Get user by user name - + def get_user_by_name_with_http_info(self, username, **kwargs): # noqa: E501 + """Get user by user name # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_user_by_name_with_http_info(username, async=True) @@ -449,14 +451,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['username'] + all_params = ['username'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -465,15 +467,15 @@ 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`") - + if ('username' not in params or + params['username'] is None): + raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") # noqa: E501 collection_formats = {} path_params = {} if 'username' in params: - path_params['username'] = params['username'] + path_params['username'] = params['username'] # noqa: E501 query_params = [] @@ -484,31 +486,32 @@ class UserApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/{username}', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='User', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/{username}', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='User', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def login_user(self, username, password, **kwargs): - """ - Logs user into the system - + def login_user(self, username, password, **kwargs): # noqa: E501 + """Logs user into the system # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.login_user(username, password, async=True) @@ -523,15 +526,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.login_user_with_http_info(username, password, **kwargs) + return self.login_user_with_http_info(username, password, **kwargs) # noqa: E501 else: - (data) = self.login_user_with_http_info(username, password, **kwargs) + (data) = self.login_user_with_http_info(username, password, **kwargs) # noqa: E501 return data - def login_user_with_http_info(self, username, password, **kwargs): - """ - Logs user into the system - + def login_user_with_http_info(self, username, password, **kwargs): # noqa: E501 + """Logs user into the system # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.login_user_with_http_info(username, password, async=True) @@ -545,14 +548,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['username', 'password'] + all_params = ['username', 'password'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -561,12 +564,13 @@ 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`") + if ('username' not in params or + params['username'] is None): + raise ValueError("Missing the required parameter `username` when calling `login_user`") # noqa: E501 # verify the required parameter 'password' is set - if ('password' not in params) or (params['password'] is None): - raise ValueError("Missing the required parameter `password` when calling `login_user`") - + if ('password' not in params or + params['password'] is None): + raise ValueError("Missing the required parameter `password` when calling `login_user`") # noqa: E501 collection_formats = {} @@ -574,9 +578,9 @@ class UserApi(object): query_params = [] if 'username' in params: - query_params.append(('username', params['username'])) + query_params.append(('username', params['username'])) # noqa: E501 if 'password' in params: - query_params.append(('password', params['password'])) + query_params.append(('password', params['password'])) # noqa: E501 header_params = {} @@ -585,31 +589,32 @@ class UserApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/login', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='str', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/login', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='str', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def logout_user(self, **kwargs): - """ - Logs out current logged in user session - + def logout_user(self, **kwargs): # noqa: E501 + """Logs out current logged in user session # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.logout_user(async=True) @@ -622,15 +627,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.logout_user_with_http_info(**kwargs) + return self.logout_user_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.logout_user_with_http_info(**kwargs) + (data) = self.logout_user_with_http_info(**kwargs) # noqa: E501 return data - def logout_user_with_http_info(self, **kwargs): - """ - Logs out current logged in user session - + def logout_user_with_http_info(self, **kwargs): # noqa: E501 + """Logs out current logged in user session # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.logout_user_with_http_info(async=True) @@ -642,14 +647,14 @@ class UserApi(object): returns the request thread. """ - all_params = [] + all_params = [] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -671,31 +676,32 @@ class UserApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/logout', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/logout', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def update_user(self, username, body, **kwargs): - """ - Updated user - This can only be done by the logged in user. + def update_user(self, username, body, **kwargs): # noqa: E501 + """Updated user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_user(username, body, async=True) @@ -710,15 +716,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.update_user_with_http_info(username, body, **kwargs) + return self.update_user_with_http_info(username, body, **kwargs) # noqa: E501 else: - (data) = self.update_user_with_http_info(username, body, **kwargs) + (data) = self.update_user_with_http_info(username, body, **kwargs) # noqa: E501 return data - def update_user_with_http_info(self, username, body, **kwargs): - """ - Updated user - This can only be done by the logged in user. + def update_user_with_http_info(self, username, body, **kwargs): # noqa: E501 + """Updated user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_user_with_http_info(username, body, async=True) @@ -732,14 +738,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['username', 'body'] + all_params = ['username', 'body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -748,18 +754,19 @@ 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`") + if ('username' not in params or + params['username'] is None): + raise ValueError("Missing the required parameter `username` when calling `update_user`") # noqa: E501 # 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_user`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `update_user`") # noqa: E501 collection_formats = {} path_params = {} if 'username' in params: - path_params['username'] = params['username'] + path_params['username'] = params['username'] # noqa: E501 query_params = [] @@ -772,23 +779,24 @@ class UserApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/{username}', 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/{username}', 'PUT', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python-tornado/petstore_api/api_client.py b/samples/client/petstore/python-tornado/petstore_api/api_client.py index c30b14130a9..222812fdb73 100644 --- a/samples/client/petstore/python-tornado/petstore_api/api_client.py +++ b/samples/client/petstore/python-tornado/petstore_api/api_client.py @@ -2,7 +2,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,28 +11,26 @@ from __future__ import absolute_import -import os -import re +import datetime import json import mimetypes -import tempfile -import tornado.gen from multiprocessing.pool import ThreadPool - -from datetime import date, datetime +import os +import re +import tempfile # python 2 and python 3 compatibility library -from six import PY3, integer_types, iteritems, text_type +import six from six.moves.urllib.parse import quote +import tornado.gen -from . import models -from .configuration import Configuration -from .rest import ApiException, RESTClientObject +from petstore_api.configuration import Configuration +import petstore_api.models +from petstore_api import rest class ApiClient(object): - """ - Generic API client for Swagger client library builds. + """Generic API client for Swagger client library builds. Swagger generic API client. This client handles the client- server communication, and is invariant across implementations. Specifics of @@ -43,65 +41,64 @@ class ApiClient(object): Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. - :param host: The base path for the server to call. + :param configuration: .Configuration object for this client :param header_name: a header to pass when making calls to the API. - :param header_value: a header value to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API """ - PRIMITIVE_TYPES = (float, bool, bytes, text_type) + integer_types + PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types NATIVE_TYPES_MAPPING = { 'int': int, - 'long': int if PY3 else long, + 'long': int if six.PY3 else long, # noqa: F821 'float': float, 'str': str, 'bool': bool, - 'date': date, - 'datetime': datetime, + 'date': datetime.date, + 'datetime': datetime.datetime, 'object': object, } - def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None): + def __init__(self, configuration=None, header_name=None, header_value=None, + cookie=None): if configuration is None: configuration = Configuration() self.configuration = configuration self.pool = ThreadPool() - self.rest_client = RESTClientObject(configuration) + self.rest_client = rest.RESTClientObject(configuration) self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value self.cookie = cookie # Set default User-Agent. self.user_agent = 'Swagger-Codegen/1.0.0/python' - + def __del__(self): self.pool.close() self.pool.join() @property def user_agent(self): - """ - Gets user agent. - """ + """User agent for this API client""" return self.default_headers['User-Agent'] @user_agent.setter def user_agent(self, value): - """ - Sets user agent. - """ self.default_headers['User-Agent'] = value def set_default_header(self, header_name, header_value): self.default_headers[header_name] = header_value @tornado.gen.coroutine - def __call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_type=None, auth_settings=None, - _return_http_data_only=None, collection_formats=None, _preload_content=True, - _request_timeout=None): + def __call_api( + self, resource_path, method, path_params=None, + query_params=None, header_params=None, body=None, post_params=None, + files=None, response_type=None, auth_settings=None, + _return_http_data_only=None, collection_formats=None, + _preload_content=True, _request_timeout=None): config = self.configuration @@ -123,7 +120,9 @@ class ApiClient(object): for k, v in path_params: # specified safe chars, encode everything resource_path = resource_path.replace( - '{%s}' % k, quote(str(v), safe=config.safe_chars_for_path_param)) + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) # query parameters if query_params: @@ -149,12 +148,11 @@ class ApiClient(object): url = self.configuration.host + resource_path # perform request and return response - response_data = yield self.request(method, url, - query_params=query_params, - headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) + response_data = yield self.request( + method, url, query_params=query_params, headers=header_params, + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout) self.last_response = response_data @@ -167,13 +165,13 @@ class ApiClient(object): return_data = None if _return_http_data_only: - return (return_data) + raise tornado.gen.Return(return_data) else: - return (return_data, response_data.status, response_data.getheaders()) + raise tornado.gen.Return((return_data, response_data.status, + response_data.getheaders())) def sanitize_for_serialization(self, obj): - """ - Builds a JSON POST object. + """Builds a JSON POST object. If obj is None, return None. If obj is str, int, long, float, bool, return directly. @@ -196,7 +194,7 @@ class ApiClient(object): elif isinstance(obj, tuple): return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj) - elif isinstance(obj, (datetime, date)): + elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() if isinstance(obj, dict): @@ -208,15 +206,14 @@ class ApiClient(object): # Convert attribute name to json key in # model definition for request. obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in iteritems(obj.swagger_types) + for attr, _ in six.iteritems(obj.swagger_types) if getattr(obj, attr) is not None} return {key: self.sanitize_for_serialization(val) - for key, val in iteritems(obj_dict)} + for key, val in six.iteritems(obj_dict)} def deserialize(self, response, response_type): - """ - Deserializes response into an object. + """Deserializes response into an object. :param response: RESTResponse object to be deserialized. :param response_type: class literal for @@ -238,8 +235,7 @@ class ApiClient(object): return self.__deserialize(data, response_type) def __deserialize(self, data, klass): - """ - Deserializes dict, list, str into an object. + """Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. @@ -258,21 +254,21 @@ class ApiClient(object): if klass.startswith('dict('): sub_kls = re.match('dict\(([^,]*), (.*)\)', klass).group(2) return {k: self.__deserialize(v, sub_kls) - for k, v in iteritems(data)} + for k, v in six.iteritems(data)} # convert str to class if klass in self.NATIVE_TYPES_MAPPING: klass = self.NATIVE_TYPES_MAPPING[klass] else: - klass = getattr(models, klass) + klass = getattr(petstore_api.models, klass) if klass in self.PRIMITIVE_TYPES: return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) - elif klass == date: + elif klass == datetime.date: return self.__deserialize_date(data) - elif klass == datetime: + elif klass == datetime.datetime: return self.__deserialize_datatime(data) else: return self.__deserialize_model(data, klass) @@ -281,10 +277,10 @@ class ApiClient(object): path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, async=None, - _return_http_data_only=None, collection_formats=None, _preload_content=True, - _request_timeout=None): - """ - Makes the HTTP request (synchronous) and return the deserialized data. + _return_http_data_only=None, collection_formats=None, + _preload_content=True, _request_timeout=None): + """Makes the HTTP request (synchronous) and returns deserialized data. + To make an async request, set the async parameter. :param resource_path: Path to method endpoint. @@ -301,13 +297,17 @@ class ApiClient(object): :param files dict: key -> filename, value -> filepath, for `multipart/form-data`. :param async bool: execute request asynchronously - :param _return_http_data_only: response data without head status code and headers + :param _return_http_data_only: response data without head status code + and headers :param collection_formats: dict of collection formats for path, query, header, and post parameters. - :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without - reading/decoding response data. Default is True. - :param _request_timeout: timeout setting for this request. If one number provided, it will be total request - timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: If async parameter is True, the request will be called asynchronously. @@ -320,22 +320,23 @@ class ApiClient(object): path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, - _return_http_data_only, collection_formats, _preload_content, _request_timeout) + _return_http_data_only, collection_formats, + _preload_content, _request_timeout) else: - thread = self.pool.apply_async(self.__call_api, (resource_path, method, - path_params, query_params, + thread = self.pool.apply_async(self.__call_api, (resource_path, + method, path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, _return_http_data_only, - collection_formats, _preload_content, _request_timeout)) + collection_formats, + _preload_content, _request_timeout)) return thread def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, _request_timeout=None): - """ - Makes the HTTP request using RESTClient. - """ + post_params=None, body=None, _preload_content=True, + _request_timeout=None): + """Makes the HTTP request using RESTClient.""" if method == "GET": return self.rest_client.GET(url, query_params=query_params, @@ -394,8 +395,7 @@ class ApiClient(object): ) def parameters_to_tuples(self, params, collection_formats): - """ - Get parameters as list of tuples, formatting collections. + """Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or list of two-tuples :param dict collection_formats: Parameter collection formats @@ -404,7 +404,7 @@ class ApiClient(object): new_params = [] if collection_formats is None: collection_formats = {} - for k, v in iteritems(params) if isinstance(params, dict) else params: + for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501 if k in collection_formats: collection_format = collection_formats[k] if collection_format == 'multi': @@ -425,8 +425,7 @@ class ApiClient(object): return new_params def prepare_post_parameters(self, post_params=None, files=None): - """ - Builds form parameters. + """Builds form parameters. :param post_params: Normal form parameters. :param files: File parameters. @@ -438,7 +437,7 @@ class ApiClient(object): params = post_params if files: - for k, v in iteritems(files): + for k, v in six.iteritems(files): if not v: continue file_names = v if type(v) is list else [v] @@ -446,15 +445,15 @@ class ApiClient(object): with open(n, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() - mimetype = mimetypes.\ - guess_type(filename)[0] or 'application/octet-stream' - params.append(tuple([k, tuple([filename, filedata, mimetype])])) + mimetype = (mimetypes.guess_type(filename)[0] or + 'application/octet-stream') + params.append( + tuple([k, tuple([filename, filedata, mimetype])])) return params def select_header_accept(self, accepts): - """ - Returns `Accept` based on an array of accepts provided. + """Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json). @@ -470,8 +469,7 @@ class ApiClient(object): return ', '.join(accepts) def select_header_content_type(self, content_types): - """ - Returns `Content-Type` based on an array of content_types provided. + """Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. :return: Content-Type (e.g. application/json). @@ -487,8 +485,7 @@ class ApiClient(object): return content_types[0] def update_params_for_auth(self, headers, querys, auth_settings): - """ - Updates header and query params based on authentication setting. + """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. :param querys: Query parameters tuple list to be updated. @@ -512,7 +509,8 @@ class ApiClient(object): ) def __deserialize_file(self, response): - """ + """Deserializes body to file + Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. @@ -525,19 +523,17 @@ class ApiClient(object): content_disposition = response.getheader("Content-Disposition") if content_disposition: - filename = re.\ - search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).\ - group(1) + filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition).group(1) path = os.path.join(os.path.dirname(path), filename) - with open(path, "w") as f: + with open(path, "wb") as f: f.write(response.data) return path def __deserialize_primitive(self, data, klass): - """ - Deserializes string to primitive type. + """Deserializes string to primitive type. :param data: str. :param klass: class literal. @@ -547,21 +543,19 @@ class ApiClient(object): try: return klass(data) except UnicodeEncodeError: - return unicode(data) + return six.u(data) except TypeError: return data def __deserialize_object(self, value): - """ - Return a original value. + """Return a original value. :return: object. """ return value def __deserialize_date(self, string): - """ - Deserializes string to date. + """Deserializes string to date. :param string: str. :return: date. @@ -572,14 +566,13 @@ class ApiClient(object): except ImportError: return string except ValueError: - raise ApiException( + raise rest.ApiException( status=0, - reason="Failed to parse `{0}` into a date object".format(string) + reason="Failed to parse `{0}` as date object".format(string) ) def __deserialize_datatime(self, string): - """ - Deserializes string to datetime. + """Deserializes string to datetime. The string should be in iso8601 datetime format. @@ -592,32 +585,32 @@ class ApiClient(object): except ImportError: return string except ValueError: - raise ApiException( + raise rest.ApiException( status=0, reason=( - "Failed to parse `{0}` into a datetime object" + "Failed to parse `{0}` as datetime object" .format(string) ) ) def __deserialize_model(self, data, klass): - """ - Deserializes list or dict to model. + """Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object. """ - if not klass.swagger_types and not hasattr(klass, 'get_real_child_model'): + if not klass.swagger_types and not hasattr(klass, + 'get_real_child_model'): return data kwargs = {} if klass.swagger_types is not None: - for attr, attr_type in iteritems(klass.swagger_types): - if data is not None \ - and klass.attribute_map[attr] in data \ - and isinstance(data, (list, dict)): + for attr, attr_type in six.iteritems(klass.swagger_types): + if (data is not None and + klass.attribute_map[attr] in data and + isinstance(data, (list, dict))): value = data[klass.attribute_map[attr]] kwargs[attr] = self.__deserialize(value, attr_type) diff --git a/samples/client/petstore/python-tornado/petstore_api/apis/__init__.py b/samples/client/petstore/python-tornado/petstore_api/apis/__init__.py deleted file mode 100644 index b4b975ca8e0..00000000000 --- a/samples/client/petstore/python-tornado/petstore_api/apis/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -from __future__ import absolute_import - -# import apis into api package -from .another_fake_api import AnotherFakeApi -from .fake_api import FakeApi -from .fake_classname_tags_123_api import FakeClassnameTags123Api -from .pet_api import PetApi -from .store_api import StoreApi -from .user_api import UserApi diff --git a/samples/client/petstore/python-tornado/petstore_api/configuration.py b/samples/client/petstore/python-tornado/petstore_api/configuration.py index 29bf22034aa..f6273cf28cc 100644 --- a/samples/client/petstore/python-tornado/petstore_api/configuration.py +++ b/samples/client/petstore/python-tornado/petstore_api/configuration.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,24 +13,23 @@ from __future__ import absolute_import -import urllib3 - import copy import logging import multiprocessing import sys +import urllib3 -from six import iteritems -from six import with_metaclass +import six from six.moves import http_client as httplib + class TypeWithDefault(type): def __init__(cls, name, bases, dct): super(TypeWithDefault, cls).__init__(name, bases, dct) cls._default = None def __call__(cls): - if cls._default == None: + if cls._default is None: cls._default = type.__call__(cls) return copy.copy(cls._default) @@ -38,17 +37,15 @@ class TypeWithDefault(type): cls._default = copy.copy(default) -class Configuration(with_metaclass(TypeWithDefault, object)): - """ - NOTE: This class is auto generated by the swagger code generator program. +class Configuration(six.with_metaclass(TypeWithDefault, object)): + """NOTE: This class is auto generated by the swagger code generator program. + Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. """ def __init__(self): - """ - Constructor - """ + """Constructor""" # Default Base url self.host = "http://petstore.swagger.io:80/v2" # Temp file folder for downloading files @@ -83,7 +80,8 @@ class Configuration(with_metaclass(TypeWithDefault, object)): self.debug = False # SSL/TLS verification - # Set this to false to skip verifying SSL certificate when calling API from https server. + # Set this to false to skip verifying SSL certificate when calling API + # from https server. self.verify_ssl = True # Set this to customize the certificate file to verify the peer. self.ssl_ca_cert = None @@ -101,7 +99,6 @@ class Configuration(with_metaclass(TypeWithDefault, object)): # cpu_count * 5 is used as default value to increase performance. self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - # Proxy URL self.proxy = None # Safe chars for path_param @@ -109,18 +106,22 @@ class Configuration(with_metaclass(TypeWithDefault, object)): @property def logger_file(self): - """ - Gets the logger_file. + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str """ return self.__logger_file @logger_file.setter def logger_file(self, value): - """ - Sets the logger_file. + """The logger file. - If the logger_file is None, then add stream handler and remove file handler. - Otherwise, add file handler and remove stream handler. + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. :param value: The logger_file path. :type: str @@ -131,7 +132,7 @@ class Configuration(with_metaclass(TypeWithDefault, object)): # then add file handler and remove stream handler. self.logger_file_handler = logging.FileHandler(self.__logger_file) self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.addHandler(self.logger_file_handler) if self.logger_stream_handler: logger.removeHandler(self.logger_stream_handler) @@ -140,22 +141,23 @@ class Configuration(with_metaclass(TypeWithDefault, object)): # then add stream handler and remove file handler. self.logger_stream_handler = logging.StreamHandler() self.logger_stream_handler.setFormatter(self.logger_formatter) - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.addHandler(self.logger_stream_handler) if self.logger_file_handler: logger.removeHandler(self.logger_file_handler) @property def debug(self): - """ - Gets the debug status. + """Debug status + + :param value: The debug status, True or False. + :type: bool """ return self.__debug @debug.setter def debug(self, value): - """ - Sets the debug status. + """Debug status :param value: The debug status, True or False. :type: bool @@ -163,29 +165,32 @@ class Configuration(with_metaclass(TypeWithDefault, object)): self.__debug = value if self.__debug: # if debug status is True, turn on debug logging - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.setLevel(logging.DEBUG) # turn on httplib debug httplib.HTTPConnection.debuglevel = 1 else: # if debug status is False, turn off debug logging, # setting log level to default `logging.WARNING` - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.setLevel(logging.WARNING) # turn off httplib debug httplib.HTTPConnection.debuglevel = 0 @property def logger_format(self): - """ - Gets the logger_format. + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str """ return self.__logger_format @logger_format.setter def logger_format(self, value): - """ - Sets the logger_format. + """The logger format. The logger_formatter will be updated when sets logger_format. @@ -196,29 +201,28 @@ class Configuration(with_metaclass(TypeWithDefault, object)): self.logger_formatter = logging.Formatter(self.__logger_format) def get_api_key_with_prefix(self, identifier): - """ - Gets API key (with prefix if set). + """Gets API key (with prefix if set). :param identifier: The identifier of apiKey. :return: The token for api key authentication. """ - if self.api_key.get(identifier) and self.api_key_prefix.get(identifier): - return self.api_key_prefix[identifier] + ' ' + self.api_key[identifier] + if (self.api_key.get(identifier) and + self.api_key_prefix.get(identifier)): + return self.api_key_prefix[identifier] + ' ' + self.api_key[identifier] # noqa: E501 elif self.api_key.get(identifier): return self.api_key[identifier] def get_basic_auth_token(self): - """ - Gets HTTP basic authentication header (string). + """Gets HTTP basic authentication header (string). :return: The token for basic HTTP authentication. """ - return urllib3.util.make_headers(basic_auth=self.username + ':' + self.password)\ - .get('authorization') + return urllib3.util.make_headers( + basic_auth=self.username + ':' + self.password + ).get('authorization') def auth_settings(self): - """ - Gets Auth Settings dict for api client. + """Gets Auth Settings dict for api client. :return: The Auth Settings information dict. """ @@ -256,8 +260,7 @@ class Configuration(with_metaclass(TypeWithDefault, object)): } def to_debug_report(self): - """ - Gets the essential information for debugging. + """Gets the essential information for debugging. :return: The report for debugging. """ diff --git a/samples/client/petstore/python-tornado/petstore_api/models/__init__.py b/samples/client/petstore/python-tornado/petstore_api/models/__init__.py index 21b5d20fa3c..7b339102f9b 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/__init__.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/__init__.py @@ -1,9 +1,10 @@ # coding: utf-8 +# flake8: noqa """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -14,39 +15,39 @@ 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_of_array_of_number_only import ArrayOfArrayOfNumberOnly -from .array_of_number_only import ArrayOfNumberOnly -from .array_test import ArrayTest -from .capitalization import Capitalization -from .category import Category -from .class_model import ClassModel -from .client import Client -from .enum_arrays import EnumArrays -from .enum_class import EnumClass -from .enum_test import EnumTest -from .format_test import FormatTest -from .has_only_read_only import HasOnlyReadOnly -from .list import List -from .map_test import MapTest -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 .number_only import NumberOnly -from .order import Order -from .outer_boolean import OuterBoolean -from .outer_composite import OuterComposite -from .outer_enum import OuterEnum -from .outer_number import OuterNumber -from .outer_string import OuterString -from .pet import Pet -from .read_only_first import ReadOnlyFirst -from .special_model_name import SpecialModelName -from .tag import Tag -from .user import User -from .cat import Cat -from .dog import Dog +from petstore_api.models.additional_properties_class import AdditionalPropertiesClass +from petstore_api.models.animal import Animal +from petstore_api.models.animal_farm import AnimalFarm +from petstore_api.models.api_response import ApiResponse +from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly +from petstore_api.models.array_of_number_only import ArrayOfNumberOnly +from petstore_api.models.array_test import ArrayTest +from petstore_api.models.capitalization import Capitalization +from petstore_api.models.category import Category +from petstore_api.models.class_model import ClassModel +from petstore_api.models.client import Client +from petstore_api.models.enum_arrays import EnumArrays +from petstore_api.models.enum_class import EnumClass +from petstore_api.models.enum_test import EnumTest +from petstore_api.models.format_test import FormatTest +from petstore_api.models.has_only_read_only import HasOnlyReadOnly +from petstore_api.models.list import List +from petstore_api.models.map_test import MapTest +from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass +from petstore_api.models.model_200_response import Model200Response +from petstore_api.models.model_return import ModelReturn +from petstore_api.models.name import Name +from petstore_api.models.number_only import NumberOnly +from petstore_api.models.order import Order +from petstore_api.models.outer_boolean import OuterBoolean +from petstore_api.models.outer_composite import OuterComposite +from petstore_api.models.outer_enum import OuterEnum +from petstore_api.models.outer_number import OuterNumber +from petstore_api.models.outer_string import OuterString +from petstore_api.models.pet import Pet +from petstore_api.models.read_only_first import ReadOnlyFirst +from petstore_api.models.special_model_name import SpecialModelName +from petstore_api.models.tag import Tag +from petstore_api.models.user import User +from petstore_api.models.cat import Cat +from petstore_api.models.dog import Dog diff --git a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_class.py b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_class.py index a5329b411cd..03dbe975f1b 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_class.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_class.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class AdditionalPropertiesClass(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class AdditionalPropertiesClass(object): 'map_of_map_property': 'map_of_map_property' } - def __init__(self, map_property=None, map_of_map_property=None): - """ - AdditionalPropertiesClass - a model defined in Swagger - """ + def __init__(self, map_property=None, map_of_map_property=None): # noqa: E501 + """AdditionalPropertiesClass - a model defined in Swagger""" # noqa: E501 self._map_property = None self._map_of_map_property = None self.discriminator = None if map_property is not None: - self.map_property = map_property + self.map_property = map_property if map_of_map_property is not None: - self.map_of_map_property = map_of_map_property + self.map_of_map_property = map_of_map_property @property def map_property(self): - """ - Gets the map_property of this AdditionalPropertiesClass. + """Gets the map_property of this AdditionalPropertiesClass. # noqa: E501 - :return: The map_property of this AdditionalPropertiesClass. + + :return: The map_property of this AdditionalPropertiesClass. # noqa: E501 :rtype: dict(str, str) """ return self._map_property @map_property.setter def map_property(self, map_property): - """ - Sets the map_property of this AdditionalPropertiesClass. + """Sets the map_property of this AdditionalPropertiesClass. - :param map_property: The map_property of this AdditionalPropertiesClass. + + :param map_property: The map_property of this AdditionalPropertiesClass. # noqa: E501 :type: dict(str, str) """ @@ -77,32 +75,30 @@ class AdditionalPropertiesClass(object): @property def map_of_map_property(self): - """ - Gets the map_of_map_property of this AdditionalPropertiesClass. + """Gets the map_of_map_property of this AdditionalPropertiesClass. # noqa: E501 - :return: The map_of_map_property of this AdditionalPropertiesClass. + + :return: The map_of_map_property of this AdditionalPropertiesClass. # noqa: E501 :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. + """Sets the map_of_map_property of this AdditionalPropertiesClass. - :param map_of_map_property: The map_of_map_property of this AdditionalPropertiesClass. + + :param map_of_map_property: The map_of_map_property of this AdditionalPropertiesClass. # noqa: E501 :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 - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class AdditionalPropertiesClass(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, AdditionalPropertiesClass): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/animal.py b/samples/client/petstore/python-tornado/petstore_api/models/animal.py index 13d8276713d..390ac83905e 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/animal.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/animal.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Animal(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -41,14 +41,12 @@ class Animal(object): } discriminator_value_class_map = { - '': 'Dog', - '': 'Cat' + 'Dog': 'Dog', + 'Cat': 'Cat' } - def __init__(self, class_name=None, color='red'): - """ - Animal - a model defined in Swagger - """ + def __init__(self, class_name=None, color='red'): # noqa: E501 + """Animal - a model defined in Swagger""" # noqa: E501 self._class_name = None self._color = None @@ -56,69 +54,62 @@ class Animal(object): self.class_name = class_name if color is not None: - self.color = color + self.color = color @property def class_name(self): - """ - Gets the class_name of this Animal. + """Gets the class_name of this Animal. # noqa: E501 - :return: The class_name of this Animal. + + :return: The class_name of this Animal. # noqa: E501 :rtype: str """ return self._class_name @class_name.setter def class_name(self, class_name): - """ - Sets the class_name of this Animal. + """Sets the class_name of this Animal. - :param class_name: The class_name of this Animal. + + :param class_name: The class_name of this Animal. # noqa: E501 :type: str """ if class_name is None: - raise ValueError("Invalid value for `class_name`, must not be `None`") + raise ValueError("Invalid value for `class_name`, must not be `None`") # noqa: E501 self._class_name = class_name @property def color(self): - """ - Gets the color of this Animal. + """Gets the color of this Animal. # noqa: E501 - :return: The color of this Animal. + + :return: The color of this Animal. # noqa: E501 :rtype: str """ return self._color @color.setter def color(self, color): - """ - Sets the color of this Animal. + """Sets the color of this Animal. - :param color: The color of this Animal. + + :param color: The color of this Animal. # noqa: E501 :type: str """ self._color = color def get_real_child_model(self, data): - """ - Returns the real base class specified by the discriminator - """ + """Returns the real base class specified by the discriminator""" discriminator_value = data[self.discriminator].lower() - if self.discriminator_value_class_map.has_key(discriminator_value): - return self.discriminator_value_class_map[discriminator_value] - else: - return None + return self.discriminator_value_class_map.get(discriminator_value) def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -139,28 +130,20 @@ class Animal(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Animal): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/animal_farm.py b/samples/client/petstore/python-tornado/petstore_api/models/animal_farm.py index fa47d63f881..6371257286e 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/animal_farm.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/animal_farm.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.animal import Animal # noqa: F401,E501 class AnimalFarm(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -31,28 +33,20 @@ class AnimalFarm(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - AnimalFarm - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """AnimalFarm - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -73,28 +67,20 @@ class AnimalFarm(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, AnimalFarm): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/api_response.py b/samples/client/petstore/python-tornado/petstore_api/models/api_response.py index b2d784d8020..45c4831bb10 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/api_response.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/api_response.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ApiResponse(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -42,10 +42,8 @@ class ApiResponse(object): 'message': 'message' } - def __init__(self, code=None, type=None, message=None): - """ - ApiResponse - a model defined in Swagger - """ + def __init__(self, code=None, type=None, message=None): # noqa: E501 + """ApiResponse - a model defined in Swagger""" # noqa: E501 self._code = None self._type = None @@ -53,28 +51,28 @@ class ApiResponse(object): self.discriminator = None if code is not None: - self.code = code + self.code = code if type is not None: - self.type = type + self.type = type if message is not None: - self.message = message + self.message = message @property def code(self): - """ - Gets the code of this ApiResponse. + """Gets the code of this ApiResponse. # noqa: E501 - :return: The code of this ApiResponse. + + :return: The code of this ApiResponse. # noqa: E501 :rtype: int """ return self._code @code.setter def code(self, code): - """ - Sets the code of this ApiResponse. + """Sets the code of this ApiResponse. - :param code: The code of this ApiResponse. + + :param code: The code of this ApiResponse. # noqa: E501 :type: int """ @@ -82,20 +80,20 @@ class ApiResponse(object): @property def type(self): - """ - Gets the type of this ApiResponse. + """Gets the type of this ApiResponse. # noqa: E501 - :return: The type of this ApiResponse. + + :return: The type of this ApiResponse. # noqa: E501 :rtype: str """ return self._type @type.setter def type(self, type): - """ - Sets the type of this ApiResponse. + """Sets the type of this ApiResponse. - :param type: The type of this ApiResponse. + + :param type: The type of this ApiResponse. # noqa: E501 :type: str """ @@ -103,32 +101,30 @@ class ApiResponse(object): @property def message(self): - """ - Gets the message of this ApiResponse. + """Gets the message of this ApiResponse. # noqa: E501 - :return: The message of this ApiResponse. + + :return: The message of this ApiResponse. # noqa: E501 :rtype: str """ return self._message @message.setter def message(self, message): - """ - Sets the message of this ApiResponse. + """Sets the message of this ApiResponse. - :param message: The message of this ApiResponse. + + :param message: The message of this ApiResponse. # noqa: E501 :type: str """ self._message = message def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -149,28 +145,20 @@ class ApiResponse(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ApiResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/array_of_array_of_number_only.py b/samples/client/petstore/python-tornado/petstore_api/models/array_of_array_of_number_only.py index 0792f5a8a23..c6b363f19d8 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/array_of_array_of_number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ArrayOfArrayOfNumberOnly(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class ArrayOfArrayOfNumberOnly(object): 'array_array_number': 'ArrayArrayNumber' } - def __init__(self, array_array_number=None): - """ - ArrayOfArrayOfNumberOnly - a model defined in Swagger - """ + def __init__(self, array_array_number=None): # noqa: E501 + """ArrayOfArrayOfNumberOnly - a model defined in Swagger""" # noqa: E501 self._array_array_number = None self.discriminator = None if array_array_number is not None: - self.array_array_number = array_array_number + self.array_array_number = array_array_number @property def array_array_number(self): - """ - Gets the array_array_number of this ArrayOfArrayOfNumberOnly. + """Gets the array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501 - :return: The array_array_number of this ArrayOfArrayOfNumberOnly. + + :return: The array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501 :rtype: list[list[float]] """ return self._array_array_number @array_array_number.setter def array_array_number(self, array_array_number): - """ - Sets the array_array_number of this ArrayOfArrayOfNumberOnly. + """Sets the array_array_number of this ArrayOfArrayOfNumberOnly. - :param array_array_number: The array_array_number of this ArrayOfArrayOfNumberOnly. + + :param array_array_number: The array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501 :type: list[list[float]] """ self._array_array_number = array_array_number def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class ArrayOfArrayOfNumberOnly(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ArrayOfArrayOfNumberOnly): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/array_of_number_only.py b/samples/client/petstore/python-tornado/petstore_api/models/array_of_number_only.py index 9d00e1b37a2..240362696cd 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/array_of_number_only.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/array_of_number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ArrayOfNumberOnly(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class ArrayOfNumberOnly(object): 'array_number': 'ArrayNumber' } - def __init__(self, array_number=None): - """ - ArrayOfNumberOnly - a model defined in Swagger - """ + def __init__(self, array_number=None): # noqa: E501 + """ArrayOfNumberOnly - a model defined in Swagger""" # noqa: E501 self._array_number = None self.discriminator = None if array_number is not None: - self.array_number = array_number + self.array_number = array_number @property def array_number(self): - """ - Gets the array_number of this ArrayOfNumberOnly. + """Gets the array_number of this ArrayOfNumberOnly. # noqa: E501 - :return: The array_number of this ArrayOfNumberOnly. + + :return: The array_number of this ArrayOfNumberOnly. # noqa: E501 :rtype: list[float] """ return self._array_number @array_number.setter def array_number(self, array_number): - """ - Sets the array_number of this ArrayOfNumberOnly. + """Sets the array_number of this ArrayOfNumberOnly. - :param array_number: The array_number of this ArrayOfNumberOnly. + + :param array_number: The array_number of this ArrayOfNumberOnly. # noqa: E501 :type: list[float] """ self._array_number = array_number def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class ArrayOfNumberOnly(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ArrayOfNumberOnly): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/array_test.py b/samples/client/petstore/python-tornado/petstore_api/models/array_test.py index ac3079087c8..c5cd6bfe159 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/array_test.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/array_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.read_only_first import ReadOnlyFirst # noqa: F401,E501 class ArrayTest(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -42,10 +44,8 @@ class ArrayTest(object): 'array_array_of_model': 'array_array_of_model' } - def __init__(self, array_of_string=None, array_array_of_integer=None, array_array_of_model=None): - """ - ArrayTest - a model defined in Swagger - """ + def __init__(self, array_of_string=None, array_array_of_integer=None, array_array_of_model=None): # noqa: E501 + """ArrayTest - a model defined in Swagger""" # noqa: E501 self._array_of_string = None self._array_array_of_integer = None @@ -53,28 +53,28 @@ class ArrayTest(object): self.discriminator = None if array_of_string is not None: - self.array_of_string = array_of_string + self.array_of_string = array_of_string if array_array_of_integer is not None: - self.array_array_of_integer = array_array_of_integer + self.array_array_of_integer = array_array_of_integer if array_array_of_model is not None: - self.array_array_of_model = array_array_of_model + self.array_array_of_model = array_array_of_model @property def array_of_string(self): - """ - Gets the array_of_string of this ArrayTest. + """Gets the array_of_string of this ArrayTest. # noqa: E501 - :return: The array_of_string of this ArrayTest. + + :return: The array_of_string of this ArrayTest. # noqa: E501 :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. + """Sets the array_of_string of this ArrayTest. - :param array_of_string: The array_of_string of this ArrayTest. + + :param array_of_string: The array_of_string of this ArrayTest. # noqa: E501 :type: list[str] """ @@ -82,20 +82,20 @@ class ArrayTest(object): @property def array_array_of_integer(self): - """ - Gets the array_array_of_integer of this ArrayTest. + """Gets the array_array_of_integer of this ArrayTest. # noqa: E501 - :return: The array_array_of_integer of this ArrayTest. + + :return: The array_array_of_integer of this ArrayTest. # noqa: E501 :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. + """Sets the array_array_of_integer of this ArrayTest. - :param array_array_of_integer: The array_array_of_integer of this ArrayTest. + + :param array_array_of_integer: The array_array_of_integer of this ArrayTest. # noqa: E501 :type: list[list[int]] """ @@ -103,32 +103,30 @@ class ArrayTest(object): @property def array_array_of_model(self): - """ - Gets the array_array_of_model of this ArrayTest. + """Gets the array_array_of_model of this ArrayTest. # noqa: E501 - :return: The array_array_of_model of this ArrayTest. + + :return: The array_array_of_model of this ArrayTest. # noqa: E501 :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. + """Sets the array_array_of_model of this ArrayTest. - :param array_array_of_model: The array_array_of_model of this ArrayTest. + + :param array_array_of_model: The array_array_of_model of this ArrayTest. # noqa: E501 :type: list[list[ReadOnlyFirst]] """ self._array_array_of_model = array_array_of_model def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -149,28 +147,20 @@ class ArrayTest(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ArrayTest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/capitalization.py b/samples/client/petstore/python-tornado/petstore_api/models/capitalization.py index c9be6ed4d15..309642bdeff 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/capitalization.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/capitalization.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Capitalization(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -48,10 +48,8 @@ class Capitalization(object): 'att_name': 'ATT_NAME' } - def __init__(self, small_camel=None, capital_camel=None, small_snake=None, capital_snake=None, sca_eth_flow_points=None, att_name=None): - """ - Capitalization - a model defined in Swagger - """ + def __init__(self, small_camel=None, capital_camel=None, small_snake=None, capital_snake=None, sca_eth_flow_points=None, att_name=None): # noqa: E501 + """Capitalization - a model defined in Swagger""" # noqa: E501 self._small_camel = None self._capital_camel = None @@ -62,34 +60,34 @@ class Capitalization(object): self.discriminator = None if small_camel is not None: - self.small_camel = small_camel + self.small_camel = small_camel if capital_camel is not None: - self.capital_camel = capital_camel + self.capital_camel = capital_camel if small_snake is not None: - self.small_snake = small_snake + self.small_snake = small_snake if capital_snake is not None: - self.capital_snake = capital_snake + self.capital_snake = capital_snake if sca_eth_flow_points is not None: - self.sca_eth_flow_points = sca_eth_flow_points + self.sca_eth_flow_points = sca_eth_flow_points if att_name is not None: - self.att_name = att_name + self.att_name = att_name @property def small_camel(self): - """ - Gets the small_camel of this Capitalization. + """Gets the small_camel of this Capitalization. # noqa: E501 - :return: The small_camel of this Capitalization. + + :return: The small_camel of this Capitalization. # noqa: E501 :rtype: str """ return self._small_camel @small_camel.setter def small_camel(self, small_camel): - """ - Sets the small_camel of this Capitalization. + """Sets the small_camel of this Capitalization. - :param small_camel: The small_camel of this Capitalization. + + :param small_camel: The small_camel of this Capitalization. # noqa: E501 :type: str """ @@ -97,20 +95,20 @@ class Capitalization(object): @property def capital_camel(self): - """ - Gets the capital_camel of this Capitalization. + """Gets the capital_camel of this Capitalization. # noqa: E501 - :return: The capital_camel of this Capitalization. + + :return: The capital_camel of this Capitalization. # noqa: E501 :rtype: str """ return self._capital_camel @capital_camel.setter def capital_camel(self, capital_camel): - """ - Sets the capital_camel of this Capitalization. + """Sets the capital_camel of this Capitalization. - :param capital_camel: The capital_camel of this Capitalization. + + :param capital_camel: The capital_camel of this Capitalization. # noqa: E501 :type: str """ @@ -118,20 +116,20 @@ class Capitalization(object): @property def small_snake(self): - """ - Gets the small_snake of this Capitalization. + """Gets the small_snake of this Capitalization. # noqa: E501 - :return: The small_snake of this Capitalization. + + :return: The small_snake of this Capitalization. # noqa: E501 :rtype: str """ return self._small_snake @small_snake.setter def small_snake(self, small_snake): - """ - Sets the small_snake of this Capitalization. + """Sets the small_snake of this Capitalization. - :param small_snake: The small_snake of this Capitalization. + + :param small_snake: The small_snake of this Capitalization. # noqa: E501 :type: str """ @@ -139,20 +137,20 @@ class Capitalization(object): @property def capital_snake(self): - """ - Gets the capital_snake of this Capitalization. + """Gets the capital_snake of this Capitalization. # noqa: E501 - :return: The capital_snake of this Capitalization. + + :return: The capital_snake of this Capitalization. # noqa: E501 :rtype: str """ return self._capital_snake @capital_snake.setter def capital_snake(self, capital_snake): - """ - Sets the capital_snake of this Capitalization. + """Sets the capital_snake of this Capitalization. - :param capital_snake: The capital_snake of this Capitalization. + + :param capital_snake: The capital_snake of this Capitalization. # noqa: E501 :type: str """ @@ -160,20 +158,20 @@ class Capitalization(object): @property def sca_eth_flow_points(self): - """ - Gets the sca_eth_flow_points of this Capitalization. + """Gets the sca_eth_flow_points of this Capitalization. # noqa: E501 - :return: The sca_eth_flow_points of this Capitalization. + + :return: The sca_eth_flow_points of this Capitalization. # noqa: E501 :rtype: str """ return self._sca_eth_flow_points @sca_eth_flow_points.setter def sca_eth_flow_points(self, sca_eth_flow_points): - """ - Sets the sca_eth_flow_points of this Capitalization. + """Sets the sca_eth_flow_points of this Capitalization. - :param sca_eth_flow_points: The sca_eth_flow_points of this Capitalization. + + :param sca_eth_flow_points: The sca_eth_flow_points of this Capitalization. # noqa: E501 :type: str """ @@ -181,34 +179,32 @@ class Capitalization(object): @property def att_name(self): - """ - Gets the att_name of this Capitalization. - Name of the pet + """Gets the att_name of this Capitalization. # noqa: E501 - :return: The att_name of this Capitalization. + Name of the pet # noqa: E501 + + :return: The att_name of this Capitalization. # noqa: E501 :rtype: str """ return self._att_name @att_name.setter def att_name(self, att_name): - """ - Sets the att_name of this Capitalization. - Name of the pet + """Sets the att_name of this Capitalization. - :param att_name: The att_name of this Capitalization. + Name of the pet # noqa: E501 + + :param att_name: The att_name of this Capitalization. # noqa: E501 :type: str """ self._att_name = att_name def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -229,28 +225,20 @@ class Capitalization(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Capitalization): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/cat.py b/samples/client/petstore/python-tornado/petstore_api/models/cat.py index 76dfdc0e5b1..526d3e2aaf5 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/cat.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/cat.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.animal import Animal # noqa: F401,E501 class Cat(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +40,41 @@ class Cat(object): 'declawed': 'declawed' } - def __init__(self, declawed=None): - """ - Cat - a model defined in Swagger - """ + def __init__(self, declawed=None): # noqa: E501 + """Cat - a model defined in Swagger""" # noqa: E501 self._declawed = None self.discriminator = None if declawed is not None: - self.declawed = declawed + self.declawed = declawed @property def declawed(self): - """ - Gets the declawed of this Cat. + """Gets the declawed of this Cat. # noqa: E501 - :return: The declawed of this Cat. + + :return: The declawed of this Cat. # noqa: E501 :rtype: bool """ return self._declawed @declawed.setter def declawed(self, declawed): - """ - Sets the declawed of this Cat. + """Sets the declawed of this Cat. - :param declawed: The declawed of this Cat. + + :param declawed: The declawed of this Cat. # noqa: E501 :type: bool """ self._declawed = declawed def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +95,20 @@ class Cat(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Cat): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/category.py b/samples/client/petstore/python-tornado/petstore_api/models/category.py index 859283a3f77..02d393af888 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/category.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/category.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Category(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class Category(object): 'name': 'name' } - def __init__(self, id=None, name=None): - """ - Category - a model defined in Swagger - """ + def __init__(self, id=None, name=None): # noqa: E501 + """Category - a model defined in Swagger""" # noqa: E501 self._id = None self._name = None self.discriminator = None if id is not None: - self.id = id + self.id = id if name is not None: - self.name = name + self.name = name @property def id(self): - """ - Gets the id of this Category. + """Gets the id of this Category. # noqa: E501 - :return: The id of this Category. + + :return: The id of this Category. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): - """ - Sets the id of this Category. + """Sets the id of this Category. - :param id: The id of this Category. + + :param id: The id of this Category. # noqa: E501 :type: int """ @@ -77,32 +75,30 @@ class Category(object): @property def name(self): - """ - Gets the name of this Category. + """Gets the name of this Category. # noqa: E501 - :return: The name of this Category. + + :return: The name of this Category. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): - """ - Sets the name of this Category. + """Sets the name of this Category. - :param name: The name of this Category. + + :param name: The name of this Category. # noqa: E501 :type: str """ self._name = name def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class Category(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Category): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/class_model.py b/samples/client/petstore/python-tornado/petstore_api/models/class_model.py index 7b39d38abe9..4bcb19b8dc2 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/class_model.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/class_model.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ClassModel(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class ClassModel(object): '_class': '_class' } - def __init__(self, _class=None): - """ - ClassModel - a model defined in Swagger - """ + def __init__(self, _class=None): # noqa: E501 + """ClassModel - a model defined in Swagger""" # noqa: E501 self.__class = None self.discriminator = None if _class is not None: - self._class = _class + self._class = _class @property def _class(self): - """ - Gets the _class of this ClassModel. + """Gets the _class of this ClassModel. # noqa: E501 - :return: The _class of this ClassModel. + + :return: The _class of this ClassModel. # noqa: E501 :rtype: str """ return self.__class @_class.setter def _class(self, _class): - """ - Sets the _class of this ClassModel. + """Sets the _class of this ClassModel. - :param _class: The _class of this ClassModel. + + :param _class: The _class of this ClassModel. # noqa: E501 :type: str """ self.__class = _class def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class ClassModel(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ClassModel): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/client.py b/samples/client/petstore/python-tornado/petstore_api/models/client.py index 395f77913cc..e267fed6d8c 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/client.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/client.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Client(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class Client(object): 'client': 'client' } - def __init__(self, client=None): - """ - Client - a model defined in Swagger - """ + def __init__(self, client=None): # noqa: E501 + """Client - a model defined in Swagger""" # noqa: E501 self._client = None self.discriminator = None if client is not None: - self.client = client + self.client = client @property def client(self): - """ - Gets the client of this Client. + """Gets the client of this Client. # noqa: E501 - :return: The client of this Client. + + :return: The client of this Client. # noqa: E501 :rtype: str """ return self._client @client.setter def client(self, client): - """ - Sets the client of this Client. + """Sets the client of this Client. - :param client: The client of this Client. + + :param client: The client of this Client. # noqa: E501 :type: str """ self._client = client def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class Client(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Client): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/dog.py b/samples/client/petstore/python-tornado/petstore_api/models/dog.py index 3c159ad0d6f..34aac6aaad4 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/dog.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/dog.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.animal import Animal # noqa: F401,E501 class Dog(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +40,41 @@ class Dog(object): 'breed': 'breed' } - def __init__(self, breed=None): - """ - Dog - a model defined in Swagger - """ + def __init__(self, breed=None): # noqa: E501 + """Dog - a model defined in Swagger""" # noqa: E501 self._breed = None self.discriminator = None if breed is not None: - self.breed = breed + self.breed = breed @property def breed(self): - """ - Gets the breed of this Dog. + """Gets the breed of this Dog. # noqa: E501 - :return: The breed of this Dog. + + :return: The breed of this Dog. # noqa: E501 :rtype: str """ return self._breed @breed.setter def breed(self, breed): - """ - Sets the breed of this Dog. + """Sets the breed of this Dog. - :param breed: The breed of this Dog. + + :param breed: The breed of this Dog. # noqa: E501 :type: str """ self._breed = breed def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +95,20 @@ class Dog(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Dog): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/enum_arrays.py b/samples/client/petstore/python-tornado/petstore_api/models/enum_arrays.py index 893085ea235..d02be298d2f 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/enum_arrays.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/enum_arrays.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class EnumArrays(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,42 +40,40 @@ class EnumArrays(object): 'array_enum': 'array_enum' } - def __init__(self, just_symbol=None, array_enum=None): - """ - EnumArrays - a model defined in Swagger - """ + def __init__(self, just_symbol=None, array_enum=None): # noqa: E501 + """EnumArrays - a model defined in Swagger""" # noqa: E501 self._just_symbol = None self._array_enum = None self.discriminator = None if just_symbol is not None: - self.just_symbol = just_symbol + self.just_symbol = just_symbol if array_enum is not None: - self.array_enum = array_enum + self.array_enum = array_enum @property def just_symbol(self): - """ - Gets the just_symbol of this EnumArrays. + """Gets the just_symbol of this EnumArrays. # noqa: E501 - :return: The just_symbol of this EnumArrays. + + :return: The just_symbol of this EnumArrays. # noqa: E501 :rtype: str """ return self._just_symbol @just_symbol.setter def just_symbol(self, just_symbol): - """ - Sets the just_symbol of this EnumArrays. + """Sets the just_symbol of this EnumArrays. - :param just_symbol: The just_symbol of this EnumArrays. + + :param just_symbol: The just_symbol of this EnumArrays. # noqa: E501 :type: str """ - allowed_values = [">=", "$"] + allowed_values = [">=", "$"] # noqa: E501 if just_symbol not in allowed_values: raise ValueError( - "Invalid value for `just_symbol` ({0}), must be one of {1}" + "Invalid value for `just_symbol` ({0}), must be one of {1}" # noqa: E501 .format(just_symbol, allowed_values) ) @@ -83,39 +81,37 @@ class EnumArrays(object): @property def array_enum(self): - """ - Gets the array_enum of this EnumArrays. + """Gets the array_enum of this EnumArrays. # noqa: E501 - :return: The array_enum of this EnumArrays. + + :return: The array_enum of this EnumArrays. # noqa: E501 :rtype: list[str] """ return self._array_enum @array_enum.setter def array_enum(self, array_enum): - """ - Sets the array_enum of this EnumArrays. + """Sets the array_enum of this EnumArrays. - :param array_enum: The array_enum of this EnumArrays. + + :param array_enum: The array_enum of this EnumArrays. # noqa: E501 :type: list[str] """ - allowed_values = ["fish", "crab"] + allowed_values = ["fish", "crab"] # noqa: E501 if not set(array_enum).issubset(set(allowed_values)): raise ValueError( - "Invalid values for `array_enum` [{0}], must be a subset of [{1}]" - .format(", ".join(map(str, set(array_enum)-set(allowed_values))), + "Invalid values for `array_enum` [{0}], must be a subset of [{1}]" # noqa: E501 + .format(", ".join(map(str, set(array_enum) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._array_enum = array_enum def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -136,28 +132,20 @@ class EnumArrays(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, EnumArrays): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/enum_class.py b/samples/client/petstore/python-tornado/petstore_api/models/enum_class.py index d9e0b771a7d..e4721545e83 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/enum_class.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/enum_class.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,14 +11,15 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class EnumClass(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ @@ -37,28 +38,20 @@ class EnumClass(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - EnumClass - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """EnumClass - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -79,28 +72,20 @@ class EnumClass(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, EnumClass): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/enum_test.py b/samples/client/petstore/python-tornado/petstore_api/models/enum_test.py index 6d7caa1f4bc..1bb234764ab 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/enum_test.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/enum_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.outer_enum import OuterEnum # noqa: F401,E501 class EnumTest(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -44,10 +46,8 @@ class EnumTest(object): 'outer_enum': 'outerEnum' } - def __init__(self, enum_string=None, enum_integer=None, enum_number=None, outer_enum=None): - """ - EnumTest - a model defined in Swagger - """ + def __init__(self, enum_string=None, enum_integer=None, enum_number=None, outer_enum=None): # noqa: E501 + """EnumTest - a model defined in Swagger""" # noqa: E501 self._enum_string = None self._enum_integer = None @@ -56,36 +56,36 @@ class EnumTest(object): self.discriminator = None if enum_string is not None: - self.enum_string = enum_string + self.enum_string = enum_string if enum_integer is not None: - self.enum_integer = enum_integer + self.enum_integer = enum_integer if enum_number is not None: - self.enum_number = enum_number + self.enum_number = enum_number if outer_enum is not None: - self.outer_enum = outer_enum + self.outer_enum = outer_enum @property def enum_string(self): - """ - Gets the enum_string of this EnumTest. + """Gets the enum_string of this EnumTest. # noqa: E501 - :return: The enum_string of this EnumTest. + + :return: The enum_string of this EnumTest. # noqa: E501 :rtype: str """ return self._enum_string @enum_string.setter def enum_string(self, enum_string): - """ - Sets the enum_string of this EnumTest. + """Sets the enum_string of this EnumTest. - :param enum_string: The enum_string of this EnumTest. + + :param enum_string: The enum_string of this EnumTest. # noqa: E501 :type: str """ - allowed_values = ["UPPER", "lower", ""] + allowed_values = ["UPPER", "lower", ""] # noqa: E501 if enum_string not in allowed_values: raise ValueError( - "Invalid value for `enum_string` ({0}), must be one of {1}" + "Invalid value for `enum_string` ({0}), must be one of {1}" # noqa: E501 .format(enum_string, allowed_values) ) @@ -93,26 +93,26 @@ class EnumTest(object): @property def enum_integer(self): - """ - Gets the enum_integer of this EnumTest. + """Gets the enum_integer of this EnumTest. # noqa: E501 - :return: The enum_integer of this EnumTest. + + :return: The enum_integer of this EnumTest. # noqa: E501 :rtype: int """ return self._enum_integer @enum_integer.setter def enum_integer(self, enum_integer): - """ - Sets the enum_integer of this EnumTest. + """Sets the enum_integer of this EnumTest. - :param enum_integer: The enum_integer of this EnumTest. + + :param enum_integer: The enum_integer of this EnumTest. # noqa: E501 :type: int """ - allowed_values = [1, -1] + allowed_values = [1, -1] # noqa: E501 if enum_integer not in allowed_values: raise ValueError( - "Invalid value for `enum_integer` ({0}), must be one of {1}" + "Invalid value for `enum_integer` ({0}), must be one of {1}" # noqa: E501 .format(enum_integer, allowed_values) ) @@ -120,26 +120,26 @@ class EnumTest(object): @property def enum_number(self): - """ - Gets the enum_number of this EnumTest. + """Gets the enum_number of this EnumTest. # noqa: E501 - :return: The enum_number of this EnumTest. + + :return: The enum_number of this EnumTest. # noqa: E501 :rtype: float """ return self._enum_number @enum_number.setter def enum_number(self, enum_number): - """ - Sets the enum_number of this EnumTest. + """Sets the enum_number of this EnumTest. - :param enum_number: The enum_number of this EnumTest. + + :param enum_number: The enum_number of this EnumTest. # noqa: E501 :type: float """ - allowed_values = [1.1, -1.2] + allowed_values = [1.1, -1.2] # noqa: E501 if enum_number not in allowed_values: raise ValueError( - "Invalid value for `enum_number` ({0}), must be one of {1}" + "Invalid value for `enum_number` ({0}), must be one of {1}" # noqa: E501 .format(enum_number, allowed_values) ) @@ -147,32 +147,30 @@ class EnumTest(object): @property def outer_enum(self): - """ - Gets the outer_enum of this EnumTest. + """Gets the outer_enum of this EnumTest. # noqa: E501 - :return: The outer_enum of this EnumTest. + + :return: The outer_enum of this EnumTest. # noqa: E501 :rtype: OuterEnum """ return self._outer_enum @outer_enum.setter def outer_enum(self, outer_enum): - """ - Sets the outer_enum of this EnumTest. + """Sets the outer_enum of this EnumTest. - :param outer_enum: The outer_enum of this EnumTest. + + :param outer_enum: The outer_enum of this EnumTest. # noqa: E501 :type: OuterEnum """ self._outer_enum = outer_enum def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -193,28 +191,20 @@ class EnumTest(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, EnumTest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/format_test.py b/samples/client/petstore/python-tornado/petstore_api/models/format_test.py index 139d1733b35..7974d732fda 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/format_test.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/format_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class FormatTest(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -62,10 +62,8 @@ class FormatTest(object): 'password': 'password' } - 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 - """ + 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): # noqa: E501 + """FormatTest - a model defined in Swagger""" # noqa: E501 self._integer = None self._int32 = None @@ -83,94 +81,94 @@ class FormatTest(object): self.discriminator = None if integer is not None: - self.integer = integer + self.integer = integer if int32 is not None: - self.int32 = int32 + self.int32 = int32 if int64 is not None: - self.int64 = int64 + self.int64 = int64 self.number = number if float is not None: - self.float = float + self.float = float if double is not None: - self.double = double + self.double = double if string is not None: - self.string = string + self.string = string self.byte = byte if binary is not None: - self.binary = binary + self.binary = binary self.date = date if date_time is not None: - self.date_time = date_time + self.date_time = date_time if uuid is not None: - self.uuid = uuid + self.uuid = uuid self.password = password @property def integer(self): - """ - Gets the integer of this FormatTest. + """Gets the integer of this FormatTest. # noqa: E501 - :return: The integer of this FormatTest. + + :return: The integer of this FormatTest. # noqa: E501 :rtype: int """ return self._integer @integer.setter def integer(self, integer): - """ - Sets the integer of this FormatTest. + """Sets the integer of this FormatTest. - :param integer: The integer of this FormatTest. + + :param integer: The integer of this FormatTest. # noqa: E501 :type: int """ - if integer is not None and integer > 100: - raise ValueError("Invalid value for `integer`, must be a value less than or equal to `100`") - if integer is not None and integer < 10: - raise ValueError("Invalid value for `integer`, must be a value greater than or equal to `10`") + if integer is not None and integer > 100: # noqa: E501 + raise ValueError("Invalid value for `integer`, must be a value less than or equal to `100`") # noqa: E501 + if integer is not None and integer < 10: # noqa: E501 + raise ValueError("Invalid value for `integer`, must be a value greater than or equal to `10`") # noqa: E501 self._integer = integer @property def int32(self): - """ - Gets the int32 of this FormatTest. + """Gets the int32 of this FormatTest. # noqa: E501 - :return: The int32 of this FormatTest. + + :return: The int32 of this FormatTest. # noqa: E501 :rtype: int """ return self._int32 @int32.setter def int32(self, int32): - """ - Sets the int32 of this FormatTest. + """Sets the int32 of this FormatTest. - :param int32: The int32 of this FormatTest. + + :param int32: The int32 of this FormatTest. # noqa: E501 :type: int """ - if int32 is not None and int32 > 200: - raise ValueError("Invalid value for `int32`, must be a value less than or equal to `200`") - if int32 is not None and int32 < 20: - raise ValueError("Invalid value for `int32`, must be a value greater than or equal to `20`") + if int32 is not None and int32 > 200: # noqa: E501 + raise ValueError("Invalid value for `int32`, must be a value less than or equal to `200`") # noqa: E501 + if int32 is not None and int32 < 20: # noqa: E501 + raise ValueError("Invalid value for `int32`, must be a value greater than or equal to `20`") # noqa: E501 self._int32 = int32 @property def int64(self): - """ - Gets the int64 of this FormatTest. + """Gets the int64 of this FormatTest. # noqa: E501 - :return: The int64 of this FormatTest. + + :return: The int64 of this FormatTest. # noqa: E501 :rtype: int """ return self._int64 @int64.setter def int64(self, int64): - """ - Sets the int64 of this FormatTest. + """Sets the int64 of this FormatTest. - :param int64: The int64 of this FormatTest. + + :param int64: The int64 of this FormatTest. # noqa: E501 :type: int """ @@ -178,145 +176,145 @@ class FormatTest(object): @property def number(self): - """ - Gets the number of this FormatTest. + """Gets the number of this FormatTest. # noqa: E501 - :return: The number of this FormatTest. + + :return: The number of this FormatTest. # noqa: E501 :rtype: float """ return self._number @number.setter def number(self, number): - """ - Sets the number of this FormatTest. + """Sets the number of this FormatTest. - :param number: The number of this FormatTest. + + :param number: The number of this FormatTest. # noqa: E501 :type: float """ if number is None: - raise ValueError("Invalid value for `number`, must not be `None`") - if number is not None and number > 543.2: - raise ValueError("Invalid value for `number`, must be a value less than or equal to `543.2`") - if number is not None and number < 32.1: - raise ValueError("Invalid value for `number`, must be a value greater than or equal to `32.1`") + raise ValueError("Invalid value for `number`, must not be `None`") # noqa: E501 + if number is not None and number > 543.2: # noqa: E501 + raise ValueError("Invalid value for `number`, must be a value less than or equal to `543.2`") # noqa: E501 + if number is not None and number < 32.1: # noqa: E501 + raise ValueError("Invalid value for `number`, must be a value greater than or equal to `32.1`") # noqa: E501 self._number = number @property def float(self): - """ - Gets the float of this FormatTest. + """Gets the float of this FormatTest. # noqa: E501 - :return: The float of this FormatTest. + + :return: The float of this FormatTest. # noqa: E501 :rtype: float """ return self._float @float.setter def float(self, float): - """ - Sets the float of this FormatTest. + """Sets the float of this FormatTest. - :param float: The float of this FormatTest. + + :param float: The float of this FormatTest. # noqa: E501 :type: float """ - if float is not None and float > 987.6: - raise ValueError("Invalid value for `float`, must be a value less than or equal to `987.6`") - if float is not None and float < 54.3: - raise ValueError("Invalid value for `float`, must be a value greater than or equal to `54.3`") + if float is not None and float > 987.6: # noqa: E501 + raise ValueError("Invalid value for `float`, must be a value less than or equal to `987.6`") # noqa: E501 + if float is not None and float < 54.3: # noqa: E501 + raise ValueError("Invalid value for `float`, must be a value greater than or equal to `54.3`") # noqa: E501 self._float = float @property def double(self): - """ - Gets the double of this FormatTest. + """Gets the double of this FormatTest. # noqa: E501 - :return: The double of this FormatTest. + + :return: The double of this FormatTest. # noqa: E501 :rtype: float """ return self._double @double.setter def double(self, double): - """ - Sets the double of this FormatTest. + """Sets the double of this FormatTest. - :param double: The double of this FormatTest. + + :param double: The double of this FormatTest. # noqa: E501 :type: float """ - if double is not None and double > 123.4: - raise ValueError("Invalid value for `double`, must be a value less than or equal to `123.4`") - if double is not None and double < 67.8: - raise ValueError("Invalid value for `double`, must be a value greater than or equal to `67.8`") + if double is not None and double > 123.4: # noqa: E501 + raise ValueError("Invalid value for `double`, must be a value less than or equal to `123.4`") # noqa: E501 + if double is not None and double < 67.8: # noqa: E501 + raise ValueError("Invalid value for `double`, must be a value greater than or equal to `67.8`") # noqa: E501 self._double = double @property def string(self): - """ - Gets the string of this FormatTest. + """Gets the string of this FormatTest. # noqa: E501 - :return: The string of this FormatTest. + + :return: The string of this FormatTest. # noqa: E501 :rtype: str """ return self._string @string.setter def string(self, string): - """ - Sets the string of this FormatTest. + """Sets the string of this FormatTest. - :param string: The string of this FormatTest. + + :param string: The string of this FormatTest. # noqa: E501 :type: str """ - if string is not None and 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`") + if string is not None and not re.search('[a-z]', string, flags=re.IGNORECASE): # noqa: E501 + raise ValueError("Invalid value for `string`, must be a follow pattern or equal to `/[a-z]/i`") # noqa: E501 self._string = string @property def byte(self): - """ - Gets the byte of this FormatTest. + """Gets the byte of this FormatTest. # noqa: E501 - :return: The byte of this FormatTest. + + :return: The byte of this FormatTest. # noqa: E501 :rtype: str """ return self._byte @byte.setter def byte(self, byte): - """ - Sets the byte of this FormatTest. + """Sets the byte of this FormatTest. - :param byte: The byte of this FormatTest. + + :param byte: The byte of this FormatTest. # noqa: E501 :type: str """ if byte is None: - raise ValueError("Invalid value for `byte`, must not be `None`") - if byte is not None and not re.search('^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', byte): - raise ValueError("Invalid value for `byte`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") + raise ValueError("Invalid value for `byte`, must not be `None`") # noqa: E501 + if byte is not None and not re.search('^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', byte): # noqa: E501 + raise ValueError("Invalid value for `byte`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501 self._byte = byte @property def binary(self): - """ - Gets the binary of this FormatTest. + """Gets the binary of this FormatTest. # noqa: E501 - :return: The binary of this FormatTest. + + :return: The binary of this FormatTest. # noqa: E501 :rtype: str """ return self._binary @binary.setter def binary(self, binary): - """ - Sets the binary of this FormatTest. + """Sets the binary of this FormatTest. - :param binary: The binary of this FormatTest. + + :param binary: The binary of this FormatTest. # noqa: E501 :type: str """ @@ -324,43 +322,43 @@ class FormatTest(object): @property def date(self): - """ - Gets the date of this FormatTest. + """Gets the date of this FormatTest. # noqa: E501 - :return: The date of this FormatTest. + + :return: The date of this FormatTest. # noqa: E501 :rtype: date """ return self._date @date.setter def date(self, date): - """ - Sets the date of this FormatTest. + """Sets the date of this FormatTest. - :param date: The date of this FormatTest. + + :param date: The date of this FormatTest. # noqa: E501 :type: date """ if date is None: - raise ValueError("Invalid value for `date`, must not be `None`") + raise ValueError("Invalid value for `date`, must not be `None`") # noqa: E501 self._date = date @property def date_time(self): - """ - Gets the date_time of this FormatTest. + """Gets the date_time of this FormatTest. # noqa: E501 - :return: The date_time of this FormatTest. + + :return: The date_time of this FormatTest. # noqa: E501 :rtype: datetime """ return self._date_time @date_time.setter def date_time(self, date_time): - """ - Sets the date_time of this FormatTest. + """Sets the date_time of this FormatTest. - :param date_time: The date_time of this FormatTest. + + :param date_time: The date_time of this FormatTest. # noqa: E501 :type: datetime """ @@ -368,20 +366,20 @@ class FormatTest(object): @property def uuid(self): - """ - Gets the uuid of this FormatTest. + """Gets the uuid of this FormatTest. # noqa: E501 - :return: The uuid of this FormatTest. + + :return: The uuid of this FormatTest. # noqa: E501 :rtype: str """ return self._uuid @uuid.setter def uuid(self, uuid): - """ - Sets the uuid of this FormatTest. + """Sets the uuid of this FormatTest. - :param uuid: The uuid of this FormatTest. + + :param uuid: The uuid of this FormatTest. # noqa: E501 :type: str """ @@ -389,38 +387,36 @@ class FormatTest(object): @property def password(self): - """ - Gets the password of this FormatTest. + """Gets the password of this FormatTest. # noqa: E501 - :return: The password of this FormatTest. + + :return: The password of this FormatTest. # noqa: E501 :rtype: str """ return self._password @password.setter def password(self, password): - """ - Sets the password of this FormatTest. + """Sets the password of this FormatTest. - :param password: The password of this FormatTest. + + :param password: The password of this FormatTest. # noqa: E501 :type: str """ if password is None: - raise ValueError("Invalid value for `password`, must not be `None`") + raise ValueError("Invalid value for `password`, must not be `None`") # noqa: E501 if password is not None and len(password) > 64: - raise ValueError("Invalid value for `password`, length must be less than or equal to `64`") + raise ValueError("Invalid value for `password`, length must be less than or equal to `64`") # noqa: E501 if password is not None and len(password) < 10: - raise ValueError("Invalid value for `password`, length must be greater than or equal to `10`") + raise ValueError("Invalid value for `password`, length must be greater than or equal to `10`") # noqa: E501 self._password = password def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -441,28 +437,20 @@ class FormatTest(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, FormatTest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/has_only_read_only.py b/samples/client/petstore/python-tornado/petstore_api/models/has_only_read_only.py index da0c14ec5b1..3c93eb30996 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/has_only_read_only.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/has_only_read_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class HasOnlyReadOnly(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class HasOnlyReadOnly(object): 'foo': 'foo' } - def __init__(self, bar=None, foo=None): - """ - HasOnlyReadOnly - a model defined in Swagger - """ + def __init__(self, bar=None, foo=None): # noqa: E501 + """HasOnlyReadOnly - a model defined in Swagger""" # noqa: E501 self._bar = None self._foo = None self.discriminator = None if bar is not None: - self.bar = bar + self.bar = bar if foo is not None: - self.foo = foo + self.foo = foo @property def bar(self): - """ - Gets the bar of this HasOnlyReadOnly. + """Gets the bar of this HasOnlyReadOnly. # noqa: E501 - :return: The bar of this HasOnlyReadOnly. + + :return: The bar of this HasOnlyReadOnly. # noqa: E501 :rtype: str """ return self._bar @bar.setter def bar(self, bar): - """ - Sets the bar of this HasOnlyReadOnly. + """Sets the bar of this HasOnlyReadOnly. - :param bar: The bar of this HasOnlyReadOnly. + + :param bar: The bar of this HasOnlyReadOnly. # noqa: E501 :type: str """ @@ -77,32 +75,30 @@ class HasOnlyReadOnly(object): @property def foo(self): - """ - Gets the foo of this HasOnlyReadOnly. + """Gets the foo of this HasOnlyReadOnly. # noqa: E501 - :return: The foo of this HasOnlyReadOnly. + + :return: The foo of this HasOnlyReadOnly. # noqa: E501 :rtype: str """ return self._foo @foo.setter def foo(self, foo): - """ - Sets the foo of this HasOnlyReadOnly. + """Sets the foo of this HasOnlyReadOnly. - :param foo: The foo of this HasOnlyReadOnly. + + :param foo: The foo of this HasOnlyReadOnly. # noqa: E501 :type: str """ self._foo = foo def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class HasOnlyReadOnly(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, HasOnlyReadOnly): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/list.py b/samples/client/petstore/python-tornado/petstore_api/models/list.py index 2ac0e51fb12..fbe30e6d01e 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/list.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/list.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class List(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class List(object): '_123_list': '123-list' } - def __init__(self, _123_list=None): - """ - List - a model defined in Swagger - """ + def __init__(self, _123_list=None): # noqa: E501 + """List - a model defined in Swagger""" # noqa: E501 self.__123_list = None self.discriminator = None if _123_list is not None: - self._123_list = _123_list + self._123_list = _123_list @property def _123_list(self): - """ - Gets the _123_list of this List. + """Gets the _123_list of this List. # noqa: E501 - :return: The _123_list of this List. + + :return: The _123_list of this List. # noqa: E501 :rtype: str """ return self.__123_list @_123_list.setter def _123_list(self, _123_list): - """ - Sets the _123_list of this List. + """Sets the _123_list of this List. - :param _123_list: The _123_list of this List. + + :param _123_list: The _123_list of this List. # noqa: E501 :type: str """ self.__123_list = _123_list def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class List(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, List): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/map_test.py b/samples/client/petstore/python-tornado/petstore_api/models/map_test.py index 3cb936e0db8..374c0661ba5 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/map_test.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/map_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class MapTest(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class MapTest(object): 'map_of_enum_string': 'map_of_enum_string' } - def __init__(self, map_map_of_string=None, map_of_enum_string=None): - """ - MapTest - a model defined in Swagger - """ + def __init__(self, map_map_of_string=None, map_of_enum_string=None): # noqa: E501 + """MapTest - a model defined in Swagger""" # noqa: E501 self._map_map_of_string = None self._map_of_enum_string = None self.discriminator = None if map_map_of_string is not None: - self.map_map_of_string = map_map_of_string + self.map_map_of_string = map_map_of_string if map_of_enum_string is not None: - self.map_of_enum_string = map_of_enum_string + self.map_of_enum_string = map_of_enum_string @property def map_map_of_string(self): - """ - Gets the map_map_of_string of this MapTest. + """Gets the map_map_of_string of this MapTest. # noqa: E501 - :return: The map_map_of_string of this MapTest. + + :return: The map_map_of_string of this MapTest. # noqa: E501 :rtype: dict(str, dict(str, str)) """ return self._map_map_of_string @map_map_of_string.setter def map_map_of_string(self, map_map_of_string): - """ - Sets the map_map_of_string of this MapTest. + """Sets the map_map_of_string of this MapTest. - :param map_map_of_string: The map_map_of_string of this MapTest. + + :param map_map_of_string: The map_map_of_string of this MapTest. # noqa: E501 :type: dict(str, dict(str, str)) """ @@ -77,39 +75,37 @@ class MapTest(object): @property def map_of_enum_string(self): - """ - Gets the map_of_enum_string of this MapTest. + """Gets the map_of_enum_string of this MapTest. # noqa: E501 - :return: The map_of_enum_string of this MapTest. + + :return: The map_of_enum_string of this MapTest. # noqa: E501 :rtype: dict(str, str) """ return self._map_of_enum_string @map_of_enum_string.setter def map_of_enum_string(self, map_of_enum_string): - """ - Sets the map_of_enum_string of this MapTest. + """Sets the map_of_enum_string of this MapTest. - :param map_of_enum_string: The map_of_enum_string of this MapTest. + + :param map_of_enum_string: The map_of_enum_string of this MapTest. # noqa: E501 :type: dict(str, str) """ - allowed_values = ["UPPER", "lower"] + allowed_values = ["UPPER", "lower"] # noqa: E501 if not set(map_of_enum_string.keys()).issubset(set(allowed_values)): raise ValueError( - "Invalid keys in `map_of_enum_string` [{0}], must be a subset of [{1}]" - .format(", ".join(map(str, set(map_of_enum_string.keys())-set(allowed_values))), + "Invalid keys in `map_of_enum_string` [{0}], must be a subset of [{1}]" # noqa: E501 + .format(", ".join(map(str, set(map_of_enum_string.keys()) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._map_of_enum_string = map_of_enum_string def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -130,28 +126,20 @@ class MapTest(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, MapTest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python-tornado/petstore_api/models/mixed_properties_and_additional_properties_class.py index 4b773deacef..dba1f261352 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.animal import Animal # noqa: F401,E501 class MixedPropertiesAndAdditionalPropertiesClass(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -42,10 +44,8 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): 'map': 'map' } - def __init__(self, uuid=None, date_time=None, map=None): - """ - MixedPropertiesAndAdditionalPropertiesClass - a model defined in Swagger - """ + def __init__(self, uuid=None, date_time=None, map=None): # noqa: E501 + """MixedPropertiesAndAdditionalPropertiesClass - a model defined in Swagger""" # noqa: E501 self._uuid = None self._date_time = None @@ -53,28 +53,28 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): self.discriminator = None if uuid is not None: - self.uuid = uuid + self.uuid = uuid if date_time is not None: - self.date_time = date_time + self.date_time = date_time if map is not None: - self.map = map + self.map = map @property def uuid(self): - """ - Gets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. + """Gets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - :return: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. + + :return: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :rtype: str """ return self._uuid @uuid.setter def uuid(self, uuid): - """ - Sets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. + """Sets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. - :param uuid: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. + + :param uuid: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :type: str """ @@ -82,20 +82,20 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): @property def date_time(self): - """ - Gets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. + """Gets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - :return: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. + + :return: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :rtype: datetime """ return self._date_time @date_time.setter def date_time(self, date_time): - """ - Sets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. + """Sets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. - :param date_time: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. + + :param date_time: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :type: datetime """ @@ -103,32 +103,30 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): @property def map(self): - """ - Gets the map of this MixedPropertiesAndAdditionalPropertiesClass. + """Gets the map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - :return: The map of this MixedPropertiesAndAdditionalPropertiesClass. + + :return: The map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :rtype: dict(str, Animal) """ return self._map @map.setter def map(self, map): - """ - Sets the map of this MixedPropertiesAndAdditionalPropertiesClass. + """Sets the map of this MixedPropertiesAndAdditionalPropertiesClass. - :param map: The map of this MixedPropertiesAndAdditionalPropertiesClass. + + :param map: The map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :type: dict(str, Animal) """ self._map = map def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -149,28 +147,20 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, MixedPropertiesAndAdditionalPropertiesClass): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/model_200_response.py b/samples/client/petstore/python-tornado/petstore_api/models/model_200_response.py index 2b6aeb090c0..60f9c96a676 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/model_200_response.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/model_200_response.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Model200Response(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class Model200Response(object): '_class': 'class' } - def __init__(self, name=None, _class=None): - """ - Model200Response - a model defined in Swagger - """ + def __init__(self, name=None, _class=None): # noqa: E501 + """Model200Response - a model defined in Swagger""" # noqa: E501 self._name = None self.__class = None self.discriminator = None if name is not None: - self.name = name + self.name = name if _class is not None: - self._class = _class + self._class = _class @property def name(self): - """ - Gets the name of this Model200Response. + """Gets the name of this Model200Response. # noqa: E501 - :return: The name of this Model200Response. + + :return: The name of this Model200Response. # noqa: E501 :rtype: int """ return self._name @name.setter def name(self, name): - """ - Sets the name of this Model200Response. + """Sets the name of this Model200Response. - :param name: The name of this Model200Response. + + :param name: The name of this Model200Response. # noqa: E501 :type: int """ @@ -77,32 +75,30 @@ class Model200Response(object): @property def _class(self): - """ - Gets the _class of this Model200Response. + """Gets the _class of this Model200Response. # noqa: E501 - :return: The _class of this Model200Response. + + :return: The _class of this Model200Response. # noqa: E501 :rtype: str """ return self.__class @_class.setter def _class(self, _class): - """ - Sets the _class of this Model200Response. + """Sets the _class of this Model200Response. - :param _class: The _class of this Model200Response. + + :param _class: The _class of this Model200Response. # noqa: E501 :type: str """ self.__class = _class def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class Model200Response(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Model200Response): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/model_return.py b/samples/client/petstore/python-tornado/petstore_api/models/model_return.py index a2160d21dd1..c9d8b5682aa 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/model_return.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/model_return.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ModelReturn(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class ModelReturn(object): '_return': 'return' } - def __init__(self, _return=None): - """ - ModelReturn - a model defined in Swagger - """ + def __init__(self, _return=None): # noqa: E501 + """ModelReturn - a model defined in Swagger""" # noqa: E501 self.__return = None self.discriminator = None if _return is not None: - self._return = _return + self._return = _return @property def _return(self): - """ - Gets the _return of this ModelReturn. + """Gets the _return of this ModelReturn. # noqa: E501 - :return: The _return of this ModelReturn. + + :return: The _return of this ModelReturn. # noqa: E501 :rtype: int """ return self.__return @_return.setter def _return(self, _return): - """ - Sets the _return of this ModelReturn. + """Sets the _return of this ModelReturn. - :param _return: The _return of this ModelReturn. + + :param _return: The _return of this ModelReturn. # noqa: E501 :type: int """ self.__return = _return def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class ModelReturn(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ModelReturn): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/name.py b/samples/client/petstore/python-tornado/petstore_api/models/name.py index 52b51890dde..cbfbddeb1ab 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/name.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/name.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Name(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -44,10 +44,8 @@ class Name(object): '_123_number': '123Number' } - def __init__(self, name=None, snake_case=None, _property=None, _123_number=None): - """ - Name - a model defined in Swagger - """ + def __init__(self, name=None, snake_case=None, _property=None, _123_number=None): # noqa: E501 + """Name - a model defined in Swagger""" # noqa: E501 self._name = None self._snake_case = None @@ -57,51 +55,51 @@ class Name(object): self.name = name if snake_case is not None: - self.snake_case = snake_case + self.snake_case = snake_case if _property is not None: - self._property = _property + self._property = _property if _123_number is not None: - self._123_number = _123_number + self._123_number = _123_number @property def name(self): - """ - Gets the name of this Name. + """Gets the name of this Name. # noqa: E501 - :return: The name of this Name. + + :return: The name of this Name. # noqa: E501 :rtype: int """ return self._name @name.setter def name(self, name): - """ - Sets the name of this Name. + """Sets the name of this Name. - :param name: The name of this Name. + + :param name: The name of this Name. # noqa: E501 :type: int """ if name is None: - raise ValueError("Invalid value for `name`, must not be `None`") + raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name @property def snake_case(self): - """ - Gets the snake_case of this Name. + """Gets the snake_case of this Name. # noqa: E501 - :return: The snake_case of this Name. + + :return: The snake_case of this Name. # noqa: E501 :rtype: int """ return self._snake_case @snake_case.setter def snake_case(self, snake_case): - """ - Sets the snake_case of this Name. + """Sets the snake_case of this Name. - :param snake_case: The snake_case of this Name. + + :param snake_case: The snake_case of this Name. # noqa: E501 :type: int """ @@ -109,20 +107,20 @@ class Name(object): @property def _property(self): - """ - Gets the _property of this Name. + """Gets the _property of this Name. # noqa: E501 - :return: The _property of this Name. + + :return: The _property of this Name. # noqa: E501 :rtype: str """ return self.__property @_property.setter def _property(self, _property): - """ - Sets the _property of this Name. + """Sets the _property of this Name. - :param _property: The _property of this Name. + + :param _property: The _property of this Name. # noqa: E501 :type: str """ @@ -130,32 +128,30 @@ class Name(object): @property def _123_number(self): - """ - Gets the _123_number of this Name. + """Gets the _123_number of this Name. # noqa: E501 - :return: The _123_number of this Name. + + :return: The _123_number of this Name. # noqa: E501 :rtype: int """ return self.__123_number @_123_number.setter def _123_number(self, _123_number): - """ - Sets the _123_number of this Name. + """Sets the _123_number of this Name. - :param _123_number: The _123_number of this Name. + + :param _123_number: The _123_number of this Name. # noqa: E501 :type: int """ self.__123_number = _123_number def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -176,28 +172,20 @@ class Name(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Name): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/number_only.py b/samples/client/petstore/python-tornado/petstore_api/models/number_only.py index b0e279b53a5..b96321109b9 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/number_only.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class NumberOnly(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class NumberOnly(object): 'just_number': 'JustNumber' } - def __init__(self, just_number=None): - """ - NumberOnly - a model defined in Swagger - """ + def __init__(self, just_number=None): # noqa: E501 + """NumberOnly - a model defined in Swagger""" # noqa: E501 self._just_number = None self.discriminator = None if just_number is not None: - self.just_number = just_number + self.just_number = just_number @property def just_number(self): - """ - Gets the just_number of this NumberOnly. + """Gets the just_number of this NumberOnly. # noqa: E501 - :return: The just_number of this NumberOnly. + + :return: The just_number of this NumberOnly. # noqa: E501 :rtype: float """ return self._just_number @just_number.setter def just_number(self, just_number): - """ - Sets the just_number of this NumberOnly. + """Sets the just_number of this NumberOnly. - :param just_number: The just_number of this NumberOnly. + + :param just_number: The just_number of this NumberOnly. # noqa: E501 :type: float """ self._just_number = just_number def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class NumberOnly(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, NumberOnly): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/order.py b/samples/client/petstore/python-tornado/petstore_api/models/order.py index 52c7b6c227e..6636542e941 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/order.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/order.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Order(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -48,10 +48,8 @@ class Order(object): 'complete': 'complete' } - def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=None, complete=False): - """ - Order - a model defined in Swagger - """ + def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=None, complete=False): # noqa: E501 + """Order - a model defined in Swagger""" # noqa: E501 self._id = None self._pet_id = None @@ -62,34 +60,34 @@ class Order(object): self.discriminator = None if id is not None: - self.id = id + self.id = id if pet_id is not None: - self.pet_id = pet_id + self.pet_id = pet_id if quantity is not None: - self.quantity = quantity + self.quantity = quantity if ship_date is not None: - self.ship_date = ship_date + self.ship_date = ship_date if status is not None: - self.status = status + self.status = status if complete is not None: - self.complete = complete + self.complete = complete @property def id(self): - """ - Gets the id of this Order. + """Gets the id of this Order. # noqa: E501 - :return: The id of this Order. + + :return: The id of this Order. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): - """ - Sets the id of this Order. + """Sets the id of this Order. - :param id: The id of this Order. + + :param id: The id of this Order. # noqa: E501 :type: int """ @@ -97,20 +95,20 @@ class Order(object): @property def pet_id(self): - """ - Gets the pet_id of this Order. + """Gets the pet_id of this Order. # noqa: E501 - :return: The pet_id of this Order. + + :return: The pet_id of this Order. # noqa: E501 :rtype: int """ return self._pet_id @pet_id.setter def pet_id(self, pet_id): - """ - Sets the pet_id of this Order. + """Sets the pet_id of this Order. - :param pet_id: The pet_id of this Order. + + :param pet_id: The pet_id of this Order. # noqa: E501 :type: int """ @@ -118,20 +116,20 @@ class Order(object): @property def quantity(self): - """ - Gets the quantity of this Order. + """Gets the quantity of this Order. # noqa: E501 - :return: The quantity of this Order. + + :return: The quantity of this Order. # noqa: E501 :rtype: int """ return self._quantity @quantity.setter def quantity(self, quantity): - """ - Sets the quantity of this Order. + """Sets the quantity of this Order. - :param quantity: The quantity of this Order. + + :param quantity: The quantity of this Order. # noqa: E501 :type: int """ @@ -139,20 +137,20 @@ class Order(object): @property def ship_date(self): - """ - Gets the ship_date of this Order. + """Gets the ship_date of this Order. # noqa: E501 - :return: The ship_date of this Order. + + :return: The ship_date of this Order. # noqa: E501 :rtype: datetime """ return self._ship_date @ship_date.setter def ship_date(self, ship_date): - """ - Sets the ship_date of this Order. + """Sets the ship_date of this Order. - :param ship_date: The ship_date of this Order. + + :param ship_date: The ship_date of this Order. # noqa: E501 :type: datetime """ @@ -160,28 +158,28 @@ class Order(object): @property def status(self): - """ - Gets the status of this Order. - Order Status + """Gets the status of this Order. # noqa: E501 - :return: The status of this Order. + Order Status # noqa: E501 + + :return: The status of this Order. # noqa: E501 :rtype: str """ return self._status @status.setter def status(self, status): - """ - Sets the status of this Order. - Order Status + """Sets the status of this Order. - :param status: The status of this Order. + Order Status # noqa: E501 + + :param status: The status of this Order. # noqa: E501 :type: str """ - allowed_values = ["placed", "approved", "delivered"] + allowed_values = ["placed", "approved", "delivered"] # noqa: E501 if status not in allowed_values: raise ValueError( - "Invalid value for `status` ({0}), must be one of {1}" + "Invalid value for `status` ({0}), must be one of {1}" # noqa: E501 .format(status, allowed_values) ) @@ -189,32 +187,30 @@ class Order(object): @property def complete(self): - """ - Gets the complete of this Order. + """Gets the complete of this Order. # noqa: E501 - :return: The complete of this Order. + + :return: The complete of this Order. # noqa: E501 :rtype: bool """ return self._complete @complete.setter def complete(self, complete): - """ - Sets the complete of this Order. + """Sets the complete of this Order. - :param complete: The complete of this Order. + + :param complete: The complete of this Order. # noqa: E501 :type: bool """ self._complete = complete def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -235,28 +231,20 @@ class Order(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Order): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/outer_boolean.py b/samples/client/petstore/python-tornado/petstore_api/models/outer_boolean.py index aa9aee11973..9b3aebd3608 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/outer_boolean.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/outer_boolean.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class OuterBoolean(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -31,28 +31,20 @@ class OuterBoolean(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - OuterBoolean - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """OuterBoolean - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -73,28 +65,20 @@ class OuterBoolean(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, OuterBoolean): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/outer_composite.py b/samples/client/petstore/python-tornado/petstore_api/models/outer_composite.py index 81611c17688..19775255e4e 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/outer_composite.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/outer_composite.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,22 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.outer_boolean import OuterBoolean # noqa: F401,E501 +from petstore_api.models.outer_number import OuterNumber # noqa: F401,E501 +from petstore_api.models.outer_string import OuterString # noqa: F401,E501 class OuterComposite(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -42,10 +46,8 @@ class OuterComposite(object): 'my_boolean': 'my_boolean' } - def __init__(self, my_number=None, my_string=None, my_boolean=None): - """ - OuterComposite - a model defined in Swagger - """ + def __init__(self, my_number=None, my_string=None, my_boolean=None): # noqa: E501 + """OuterComposite - a model defined in Swagger""" # noqa: E501 self._my_number = None self._my_string = None @@ -53,28 +55,28 @@ class OuterComposite(object): self.discriminator = None if my_number is not None: - self.my_number = my_number + self.my_number = my_number if my_string is not None: - self.my_string = my_string + self.my_string = my_string if my_boolean is not None: - self.my_boolean = my_boolean + self.my_boolean = my_boolean @property def my_number(self): - """ - Gets the my_number of this OuterComposite. + """Gets the my_number of this OuterComposite. # noqa: E501 - :return: The my_number of this OuterComposite. + + :return: The my_number of this OuterComposite. # noqa: E501 :rtype: OuterNumber """ return self._my_number @my_number.setter def my_number(self, my_number): - """ - Sets the my_number of this OuterComposite. + """Sets the my_number of this OuterComposite. - :param my_number: The my_number of this OuterComposite. + + :param my_number: The my_number of this OuterComposite. # noqa: E501 :type: OuterNumber """ @@ -82,20 +84,20 @@ class OuterComposite(object): @property def my_string(self): - """ - Gets the my_string of this OuterComposite. + """Gets the my_string of this OuterComposite. # noqa: E501 - :return: The my_string of this OuterComposite. + + :return: The my_string of this OuterComposite. # noqa: E501 :rtype: OuterString """ return self._my_string @my_string.setter def my_string(self, my_string): - """ - Sets the my_string of this OuterComposite. + """Sets the my_string of this OuterComposite. - :param my_string: The my_string of this OuterComposite. + + :param my_string: The my_string of this OuterComposite. # noqa: E501 :type: OuterString """ @@ -103,32 +105,30 @@ class OuterComposite(object): @property def my_boolean(self): - """ - Gets the my_boolean of this OuterComposite. + """Gets the my_boolean of this OuterComposite. # noqa: E501 - :return: The my_boolean of this OuterComposite. + + :return: The my_boolean of this OuterComposite. # noqa: E501 :rtype: OuterBoolean """ return self._my_boolean @my_boolean.setter def my_boolean(self, my_boolean): - """ - Sets the my_boolean of this OuterComposite. + """Sets the my_boolean of this OuterComposite. - :param my_boolean: The my_boolean of this OuterComposite. + + :param my_boolean: The my_boolean of this OuterComposite. # noqa: E501 :type: OuterBoolean """ self._my_boolean = my_boolean def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -149,28 +149,20 @@ class OuterComposite(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, OuterComposite): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/outer_enum.py b/samples/client/petstore/python-tornado/petstore_api/models/outer_enum.py index 8772472c655..5ee1e49a587 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/outer_enum.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/outer_enum.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,14 +11,15 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class OuterEnum(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ @@ -37,28 +38,20 @@ class OuterEnum(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - OuterEnum - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """OuterEnum - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -79,28 +72,20 @@ class OuterEnum(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, OuterEnum): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/outer_number.py b/samples/client/petstore/python-tornado/petstore_api/models/outer_number.py index 04c44923fb0..a35587be65e 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/outer_number.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/outer_number.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class OuterNumber(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -31,28 +31,20 @@ class OuterNumber(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - OuterNumber - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """OuterNumber - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -73,28 +65,20 @@ class OuterNumber(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, OuterNumber): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/outer_string.py b/samples/client/petstore/python-tornado/petstore_api/models/outer_string.py index fd2d7c7623e..736edacd1bc 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/outer_string.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/outer_string.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class OuterString(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -31,28 +31,20 @@ class OuterString(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - OuterString - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """OuterString - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -73,28 +65,20 @@ class OuterString(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, OuterString): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/pet.py b/samples/client/petstore/python-tornado/petstore_api/models/pet.py index e1afa26f785..81b2bb617f9 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/pet.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/pet.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,21 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.category import Category # noqa: F401,E501 +from petstore_api.models.tag import Tag # noqa: F401,E501 class Pet(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -48,10 +51,8 @@ class Pet(object): 'status': 'status' } - def __init__(self, id=None, category=None, name=None, photo_urls=None, tags=None, status=None): - """ - Pet - a model defined in Swagger - """ + def __init__(self, id=None, category=None, name=None, photo_urls=None, tags=None, status=None): # noqa: E501 + """Pet - a model defined in Swagger""" # noqa: E501 self._id = None self._category = None @@ -62,32 +63,32 @@ class Pet(object): self.discriminator = None if id is not None: - self.id = id + self.id = id if category is not None: - self.category = category + self.category = category self.name = name self.photo_urls = photo_urls if tags is not None: - self.tags = tags + self.tags = tags if status is not None: - self.status = status + self.status = status @property def id(self): - """ - Gets the id of this Pet. + """Gets the id of this Pet. # noqa: E501 - :return: The id of this Pet. + + :return: The id of this Pet. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): - """ - Sets the id of this Pet. + """Sets the id of this Pet. - :param id: The id of this Pet. + + :param id: The id of this Pet. # noqa: E501 :type: int """ @@ -95,20 +96,20 @@ class Pet(object): @property def category(self): - """ - Gets the category of this Pet. + """Gets the category of this Pet. # noqa: E501 - :return: The category of this Pet. + + :return: The category of this Pet. # noqa: E501 :rtype: Category """ return self._category @category.setter def category(self, category): - """ - Sets the category of this Pet. + """Sets the category of this Pet. - :param category: The category of this Pet. + + :param category: The category of this Pet. # noqa: E501 :type: Category """ @@ -116,66 +117,66 @@ class Pet(object): @property def name(self): - """ - Gets the name of this Pet. + """Gets the name of this Pet. # noqa: E501 - :return: The name of this Pet. + + :return: The name of this Pet. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): - """ - Sets the name of this Pet. + """Sets the name of this Pet. - :param name: The name of this Pet. + + :param name: The name of this Pet. # noqa: E501 :type: str """ if name is None: - raise ValueError("Invalid value for `name`, must not be `None`") + raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name @property def photo_urls(self): - """ - Gets the photo_urls of this Pet. + """Gets the photo_urls of this Pet. # noqa: E501 - :return: The photo_urls of this Pet. + + :return: The photo_urls of this Pet. # noqa: E501 :rtype: list[str] """ return self._photo_urls @photo_urls.setter def photo_urls(self, photo_urls): - """ - Sets the photo_urls of this Pet. + """Sets the photo_urls of this Pet. - :param photo_urls: The photo_urls of this Pet. + + :param photo_urls: The photo_urls of this Pet. # noqa: E501 :type: list[str] """ if photo_urls is None: - raise ValueError("Invalid value for `photo_urls`, must not be `None`") + raise ValueError("Invalid value for `photo_urls`, must not be `None`") # noqa: E501 self._photo_urls = photo_urls @property def tags(self): - """ - Gets the tags of this Pet. + """Gets the tags of this Pet. # noqa: E501 - :return: The tags of this Pet. + + :return: The tags of this Pet. # noqa: E501 :rtype: list[Tag] """ return self._tags @tags.setter def tags(self, tags): - """ - Sets the tags of this Pet. + """Sets the tags of this Pet. - :param tags: The tags of this Pet. + + :param tags: The tags of this Pet. # noqa: E501 :type: list[Tag] """ @@ -183,40 +184,38 @@ class Pet(object): @property def status(self): - """ - Gets the status of this Pet. - pet status in the store + """Gets the status of this Pet. # noqa: E501 - :return: The status of this Pet. + pet status in the store # noqa: E501 + + :return: The status of this Pet. # noqa: E501 :rtype: str """ return self._status @status.setter def status(self, status): - """ - Sets the status of this Pet. - pet status in the store + """Sets the status of this Pet. - :param status: The status of this Pet. + pet status in the store # noqa: E501 + + :param status: The status of this Pet. # noqa: E501 :type: str """ - allowed_values = ["available", "pending", "sold"] + allowed_values = ["available", "pending", "sold"] # noqa: E501 if status not in allowed_values: raise ValueError( - "Invalid value for `status` ({0}), must be one of {1}" + "Invalid value for `status` ({0}), must be one of {1}" # noqa: E501 .format(status, allowed_values) ) self._status = status def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -237,28 +236,20 @@ class Pet(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Pet): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/read_only_first.py b/samples/client/petstore/python-tornado/petstore_api/models/read_only_first.py index a26d1f33c87..106463077e8 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/read_only_first.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/read_only_first.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ReadOnlyFirst(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class ReadOnlyFirst(object): 'baz': 'baz' } - def __init__(self, bar=None, baz=None): - """ - ReadOnlyFirst - a model defined in Swagger - """ + def __init__(self, bar=None, baz=None): # noqa: E501 + """ReadOnlyFirst - a model defined in Swagger""" # noqa: E501 self._bar = None self._baz = None self.discriminator = None if bar is not None: - self.bar = bar + self.bar = bar if baz is not None: - self.baz = baz + self.baz = baz @property def bar(self): - """ - Gets the bar of this ReadOnlyFirst. + """Gets the bar of this ReadOnlyFirst. # noqa: E501 - :return: The bar of this ReadOnlyFirst. + + :return: The bar of this ReadOnlyFirst. # noqa: E501 :rtype: str """ return self._bar @bar.setter def bar(self, bar): - """ - Sets the bar of this ReadOnlyFirst. + """Sets the bar of this ReadOnlyFirst. - :param bar: The bar of this ReadOnlyFirst. + + :param bar: The bar of this ReadOnlyFirst. # noqa: E501 :type: str """ @@ -77,32 +75,30 @@ class ReadOnlyFirst(object): @property def baz(self): - """ - Gets the baz of this ReadOnlyFirst. + """Gets the baz of this ReadOnlyFirst. # noqa: E501 - :return: The baz of this ReadOnlyFirst. + + :return: The baz of this ReadOnlyFirst. # noqa: E501 :rtype: str """ return self._baz @baz.setter def baz(self, baz): - """ - Sets the baz of this ReadOnlyFirst. + """Sets the baz of this ReadOnlyFirst. - :param baz: The baz of this ReadOnlyFirst. + + :param baz: The baz of this ReadOnlyFirst. # noqa: E501 :type: str """ self._baz = baz def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class ReadOnlyFirst(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ReadOnlyFirst): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/special_model_name.py b/samples/client/petstore/python-tornado/petstore_api/models/special_model_name.py index 6be888fb9e3..a31b8db66e2 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/special_model_name.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/special_model_name.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class SpecialModelName(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class SpecialModelName(object): 'special_property_name': '$special[property.name]' } - def __init__(self, special_property_name=None): - """ - SpecialModelName - a model defined in Swagger - """ + def __init__(self, special_property_name=None): # noqa: E501 + """SpecialModelName - a model defined in Swagger""" # noqa: E501 self._special_property_name = None self.discriminator = None if special_property_name is not None: - self.special_property_name = special_property_name + self.special_property_name = special_property_name @property def special_property_name(self): - """ - Gets the special_property_name of this SpecialModelName. + """Gets the special_property_name of this SpecialModelName. # noqa: E501 - :return: The special_property_name of this SpecialModelName. + + :return: The special_property_name of this SpecialModelName. # noqa: E501 :rtype: int """ return self._special_property_name @special_property_name.setter def special_property_name(self, special_property_name): - """ - Sets the special_property_name of this SpecialModelName. + """Sets the special_property_name of this SpecialModelName. - :param special_property_name: The special_property_name of this SpecialModelName. + + :param special_property_name: The special_property_name of this SpecialModelName. # noqa: E501 :type: int """ self._special_property_name = special_property_name def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class SpecialModelName(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, SpecialModelName): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/tag.py b/samples/client/petstore/python-tornado/petstore_api/models/tag.py index d59a490a07d..b486a672b88 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/tag.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/tag.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Tag(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class Tag(object): 'name': 'name' } - def __init__(self, id=None, name=None): - """ - Tag - a model defined in Swagger - """ + def __init__(self, id=None, name=None): # noqa: E501 + """Tag - a model defined in Swagger""" # noqa: E501 self._id = None self._name = None self.discriminator = None if id is not None: - self.id = id + self.id = id if name is not None: - self.name = name + self.name = name @property def id(self): - """ - Gets the id of this Tag. + """Gets the id of this Tag. # noqa: E501 - :return: The id of this Tag. + + :return: The id of this Tag. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): - """ - Sets the id of this Tag. + """Sets the id of this Tag. - :param id: The id of this Tag. + + :param id: The id of this Tag. # noqa: E501 :type: int """ @@ -77,32 +75,30 @@ class Tag(object): @property def name(self): - """ - Gets the name of this Tag. + """Gets the name of this Tag. # noqa: E501 - :return: The name of this Tag. + + :return: The name of this Tag. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): - """ - Sets the name of this Tag. + """Sets the name of this Tag. - :param name: The name of this Tag. + + :param name: The name of this Tag. # noqa: E501 :type: str """ self._name = name def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class Tag(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Tag): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/models/user.py b/samples/client/petstore/python-tornado/petstore_api/models/user.py index 21993e90521..c9fe0072a9c 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/user.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/user.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class User(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -52,10 +52,8 @@ class User(object): 'user_status': 'userStatus' } - 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 - """ + def __init__(self, id=None, username=None, first_name=None, last_name=None, email=None, password=None, phone=None, user_status=None): # noqa: E501 + """User - a model defined in Swagger""" # noqa: E501 self._id = None self._username = None @@ -68,38 +66,38 @@ class User(object): self.discriminator = None if id is not None: - self.id = id + self.id = id if username is not None: - self.username = username + self.username = username if first_name is not None: - self.first_name = first_name + self.first_name = first_name if last_name is not None: - self.last_name = last_name + self.last_name = last_name if email is not None: - self.email = email + self.email = email if password is not None: - self.password = password + self.password = password if phone is not None: - self.phone = phone + self.phone = phone if user_status is not None: - self.user_status = user_status + self.user_status = user_status @property def id(self): - """ - Gets the id of this User. + """Gets the id of this User. # noqa: E501 - :return: The id of this User. + + :return: The id of this User. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): - """ - Sets the id of this User. + """Sets the id of this User. - :param id: The id of this User. + + :param id: The id of this User. # noqa: E501 :type: int """ @@ -107,20 +105,20 @@ class User(object): @property def username(self): - """ - Gets the username of this User. + """Gets the username of this User. # noqa: E501 - :return: The username of this User. + + :return: The username of this User. # noqa: E501 :rtype: str """ return self._username @username.setter def username(self, username): - """ - Sets the username of this User. + """Sets the username of this User. - :param username: The username of this User. + + :param username: The username of this User. # noqa: E501 :type: str """ @@ -128,20 +126,20 @@ class User(object): @property def first_name(self): - """ - Gets the first_name of this User. + """Gets the first_name of this User. # noqa: E501 - :return: The first_name of this User. + + :return: The first_name of this User. # noqa: E501 :rtype: str """ return self._first_name @first_name.setter def first_name(self, first_name): - """ - Sets the first_name of this User. + """Sets the first_name of this User. - :param first_name: The first_name of this User. + + :param first_name: The first_name of this User. # noqa: E501 :type: str """ @@ -149,20 +147,20 @@ class User(object): @property def last_name(self): - """ - Gets the last_name of this User. + """Gets the last_name of this User. # noqa: E501 - :return: The last_name of this User. + + :return: The last_name of this User. # noqa: E501 :rtype: str """ return self._last_name @last_name.setter def last_name(self, last_name): - """ - Sets the last_name of this User. + """Sets the last_name of this User. - :param last_name: The last_name of this User. + + :param last_name: The last_name of this User. # noqa: E501 :type: str """ @@ -170,20 +168,20 @@ class User(object): @property def email(self): - """ - Gets the email of this User. + """Gets the email of this User. # noqa: E501 - :return: The email of this User. + + :return: The email of this User. # noqa: E501 :rtype: str """ return self._email @email.setter def email(self, email): - """ - Sets the email of this User. + """Sets the email of this User. - :param email: The email of this User. + + :param email: The email of this User. # noqa: E501 :type: str """ @@ -191,20 +189,20 @@ class User(object): @property def password(self): - """ - Gets the password of this User. + """Gets the password of this User. # noqa: E501 - :return: The password of this User. + + :return: The password of this User. # noqa: E501 :rtype: str """ return self._password @password.setter def password(self, password): - """ - Sets the password of this User. + """Sets the password of this User. - :param password: The password of this User. + + :param password: The password of this User. # noqa: E501 :type: str """ @@ -212,20 +210,20 @@ class User(object): @property def phone(self): - """ - Gets the phone of this User. + """Gets the phone of this User. # noqa: E501 - :return: The phone of this User. + + :return: The phone of this User. # noqa: E501 :rtype: str """ return self._phone @phone.setter def phone(self, phone): - """ - Sets the phone of this User. + """Sets the phone of this User. - :param phone: The phone of this User. + + :param phone: The phone of this User. # noqa: E501 :type: str """ @@ -233,34 +231,32 @@ class User(object): @property def user_status(self): - """ - Gets the user_status of this User. - User Status + """Gets the user_status of this User. # noqa: E501 - :return: The user_status of this User. + User Status # noqa: E501 + + :return: The user_status of this User. # noqa: E501 :rtype: int """ return self._user_status @user_status.setter def user_status(self, user_status): - """ - Sets the user_status of this User. - User Status + """Sets the user_status of this User. - :param user_status: The user_status of this User. + User Status # noqa: E501 + + :param user_status: The user_status of this User. # noqa: E501 :type: int """ self._user_status = user_status def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -281,28 +277,20 @@ class User(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, User): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python-tornado/petstore_api/rest.py b/samples/client/petstore/python-tornado/petstore_api/rest.py index dc76fcdb917..2186454a352 100644 --- a/samples/client/petstore/python-tornado/petstore_api/rest.py +++ b/samples/client/petstore/python-tornado/petstore_api/rest.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,17 @@ import io import json -import ssl -import certifi import logging import re +import ssl + +import certifi +# python 2 and python 3 compatibility library +import six +from six.moves.urllib.parse import urlencode import tornado import tornado.gen -from tornado.httpclient import AsyncHTTPClient, HTTPRequest - -# python 2 and python 3 compatibility library -from six import PY3 -from six.moves.urllib.parse import urlencode +from tornado import httpclient from urllib3.filepost import encode_multipart_formdata logger = logging.getLogger(__name__) @@ -38,22 +38,18 @@ class RESTResponse(io.IOBase): self.data = data def getheaders(self): - """ - Returns a CIMultiDictProxy of the response headers. - """ + """Returns a CIMultiDictProxy of the response headers.""" return self.tornado_response.headers def getheader(self, name, default=None): - """ - Returns a given response header. - """ + """Returns a given response header.""" return self.tornado_response.headers.get(name, default) -class RESTClientObject: +class RESTClientObject(object): def __init__(self, configuration, pools_size=4, maxsize=4): - # maxsize is the number of requests to host that are allowed in parallel + # maxsize is number of requests to host that are allowed in parallel # ca_certs vs cert_file vs key_file # http://stackoverflow.com/a/23957365/2985775 @@ -64,9 +60,10 @@ class RESTClientObject: # if not set certificate file, use Mozilla's root certificates. ca_certs = certifi.where() - self.ssl_context = ssl_context = ssl.SSLContext() + self.ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) + self.ssl_context.load_verify_locations(cafile=ca_certs) if configuration.cert_file: - ssl_context.load_cert_chain( + self.ssl_context.load_cert_chain( configuration.cert_file, keyfile=configuration.key_file ) @@ -77,12 +74,14 @@ class RESTClientObject: self.proxy_port = 80 self.proxy_host = configuration.proxy - self.pool_manager = AsyncHTTPClient() + self.pool_manager = httpclient.AsyncHTTPClient() @tornado.gen.coroutine - def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, _request_timeout=None): - """ + def request(self, method, url, query_params=None, headers=None, body=None, + post_params=None, _preload_content=True, + _request_timeout=None): + """Execute Request + :param method: http request method :param url: http request url :param query_params: query parameters in the url @@ -91,19 +90,23 @@ class RESTClientObject: :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` - :param _preload_content: this is a non-applicable field for the AiohttpClient. - :param _request_timeout: timeout setting for this request. If one number provided, it will be total request - timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :param _preload_content: this is a non-applicable field for + the AiohttpClient. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', + 'PATCH', 'OPTIONS'] if post_params and body: raise ValueError( "body parameter cannot be used with post_params parameter." ) - request = HTTPRequest(url) + request = httpclient.HTTPRequest(url) request.ssl_context = self.ssl_context request.proxy_host = self.proxy_host request.proxy_port = self.proxy_port @@ -114,7 +117,6 @@ class RESTClientObject: request.headers['Content-Type'] = 'application/json' request.request_timeout = _request_timeout or 5 * 60 - post_params = post_params or {} if query_params: @@ -126,11 +128,11 @@ class RESTClientObject: if body: body = json.dumps(body) request.body = body - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 request.body = urlencode(post_params) - # TODO: transform to multipart form elif headers['Content-Type'] == 'multipart/form-data': - request.body = encode_multipart_formdata(post_params) + multipart = encode_multipart_formdata(post_params) + request.body, headers['Content-Type'] = multipart # Pass a `bytes` parameter directly in the body to support # other content types than Json when `body` argument is provided # in serialized form @@ -138,53 +140,64 @@ class RESTClientObject: request.body = body else: # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided arguments. - Please check that your arguments match declared content type.""" + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" raise ApiException(status=0, reason=msg) - r = yield self.pool_manager.fetch(request) - r = RESTResponse(r, r.body) + r = yield self.pool_manager.fetch(request, raise_error=False) - # log response body - logger.debug("response body: %s", r.data) + if _preload_content: + + r = RESTResponse(r, r.body) + # In the python 3, the response.data is bytes. + # we need to decode it to string. + if six.PY3: + r.data = r.data.decode('utf8') + + # log response body + logger.debug("response body: %s", r.data) if not 200 <= r.status <= 299: raise ApiException(http_resp=r) - return r + raise tornado.gen.Return(r) @tornado.gen.coroutine - def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): + def GET(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): result = yield self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) raise tornado.gen.Return(result) @tornado.gen.coroutine - def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): + def HEAD(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): result = yield self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) raise tornado.gen.Return(result) @tornado.gen.coroutine - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): result = yield self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) raise tornado.gen.Return(result) @tornado.gen.coroutine - def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None): + def DELETE(self, url, headers=None, query_params=None, body=None, + _preload_content=True, _request_timeout=None): result = yield self.request("DELETE", url, headers=headers, query_params=query_params, @@ -194,39 +207,39 @@ class RESTClientObject: raise tornado.gen.Return(result) @tornado.gen.coroutine - def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def POST(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): result = yield self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) raise tornado.gen.Return(result) @tornado.gen.coroutine - def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def PUT(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): result = yield self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) raise tornado.gen.Return(result) @tornado.gen.coroutine - def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def PATCH(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): result = yield self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) raise tornado.gen.Return(result) @@ -245,13 +258,12 @@ class ApiException(Exception): self.headers = None def __str__(self): - """ - Custom error messages for exception - """ - error_message = "({0})\n"\ - "Reason: {1}\n".format(self.status, self.reason) + """Custom error messages for exception""" + error_message = "({0})\nReason: {1}\n".format( + self.status, self.reason) if self.headers: - error_message += "HTTP response headers: {0}\n".format(self.headers) + error_message += "HTTP response headers: {0}\n".format( + self.headers) if self.body: error_message += "HTTP response body: {0}\n".format(self.body) diff --git a/samples/client/petstore/python-tornado/pom.xml b/samples/client/petstore/python-tornado/pom.xml new file mode 100644 index 00000000000..57ceaeaa8dc --- /dev/null +++ b/samples/client/petstore/python-tornado/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + io.swagger + PythonTornadoClientTests + pom + 1.0-SNAPSHOT + Python Tornado Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + nose-test + integration-test + + exec + + + make + + test-all + + + + + + + + diff --git a/samples/client/petstore/python-tornado/setup.py b/samples/client/petstore/python-tornado/setup.py index 7373560db31..ea0a40a1b06 100644 --- a/samples/client/petstore/python-tornado/setup.py +++ b/samples/client/petstore/python-tornado/setup.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,8 +11,7 @@ """ -import sys -from setuptools import setup, find_packages +from setuptools import setup, find_packages # noqa: H301 NAME = "petstore-api" VERSION = "1.0.0" @@ -37,6 +36,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. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 """ ) diff --git a/samples/client/petstore/python-tornado/test/test_additional_properties_class.py b/samples/client/petstore/python-tornado/test/test_additional_properties_class.py index e90e5f92efc..77ccb73b028 100644 --- a/samples/client/petstore/python-tornado/test/test_additional_properties_class.py +++ b/samples/client/petstore/python-tornado/test/test_additional_properties_class.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.additional_properties_class import AdditionalPropertiesClass # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.additional_properties_class import AdditionalPropertiesClass class TestAdditionalPropertiesClass(unittest.TestCase): - """ AdditionalPropertiesClass unit test stubs """ + """AdditionalPropertiesClass unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestAdditionalPropertiesClass(unittest.TestCase): pass def testAdditionalPropertiesClass(self): - """ - Test AdditionalPropertiesClass - """ + """Test AdditionalPropertiesClass""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.additional_properties_class.AdditionalPropertiesClass() + # model = petstore_api.models.additional_properties_class.AdditionalPropertiesClass() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_animal.py b/samples/client/petstore/python-tornado/test/test_animal.py index c675d583ccc..eb5f7cb930e 100644 --- a/samples/client/petstore/python-tornado/test/test_animal.py +++ b/samples/client/petstore/python-tornado/test/test_animal.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.animal import Animal # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.animal import Animal class TestAnimal(unittest.TestCase): - """ Animal unit test stubs """ + """Animal unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestAnimal(unittest.TestCase): pass def testAnimal(self): - """ - Test Animal - """ + """Test Animal""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.animal.Animal() + # model = petstore_api.models.animal.Animal() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_animal_farm.py b/samples/client/petstore/python-tornado/test/test_animal_farm.py index e459318a948..8f79946fa73 100644 --- a/samples/client/petstore/python-tornado/test/test_animal_farm.py +++ b/samples/client/petstore/python-tornado/test/test_animal_farm.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.animal_farm import AnimalFarm # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.animal_farm import AnimalFarm class TestAnimalFarm(unittest.TestCase): - """ AnimalFarm unit test stubs """ + """AnimalFarm unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestAnimalFarm(unittest.TestCase): pass def testAnimalFarm(self): - """ - Test AnimalFarm - """ + """Test AnimalFarm""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.animal_farm.AnimalFarm() + # model = petstore_api.models.animal_farm.AnimalFarm() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_another_fake_api.py b/samples/client/petstore/python-tornado/test/test_another_fake_api.py index 9f562fe1134..c294aa90359 100644 --- a/samples/client/petstore/python-tornado/test/test_another_fake_api.py +++ b/samples/client/petstore/python-tornado/test/test_another_fake_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,29 +13,26 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.another_fake_api import AnotherFakeApi # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.another_fake_api import AnotherFakeApi class TestAnotherFakeApi(unittest.TestCase): - """ AnotherFakeApi unit test stubs """ + """AnotherFakeApi unit test stubs""" def setUp(self): - self.api = petstore_api.apis.another_fake_api.AnotherFakeApi() + self.api = petstore_api.api.another_fake_api.AnotherFakeApi() # noqa: E501 def tearDown(self): pass def test_test_special_tags(self): - """ - Test case for test_special_tags + """Test case for test_special_tags - To test special tags + To test special tags # noqa: E501 """ pass diff --git a/samples/client/petstore/python-tornado/test/test_api_response.py b/samples/client/petstore/python-tornado/test/test_api_response.py index 928af048b43..97ed978a5f6 100644 --- a/samples/client/petstore/python-tornado/test/test_api_response.py +++ b/samples/client/petstore/python-tornado/test/test_api_response.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.api_response import ApiResponse # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.api_response import ApiResponse class TestApiResponse(unittest.TestCase): - """ ApiResponse unit test stubs """ + """ApiResponse unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestApiResponse(unittest.TestCase): pass def testApiResponse(self): - """ - Test ApiResponse - """ + """Test ApiResponse""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.api_response.ApiResponse() + # model = petstore_api.models.api_response.ApiResponse() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_array_of_array_of_number_only.py b/samples/client/petstore/python-tornado/test/test_array_of_array_of_number_only.py index 740e45cbafd..b617ed2cd3e 100644 --- a/samples/client/petstore/python-tornado/test/test_array_of_array_of_number_only.py +++ b/samples/client/petstore/python-tornado/test/test_array_of_array_of_number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly class TestArrayOfArrayOfNumberOnly(unittest.TestCase): - """ ArrayOfArrayOfNumberOnly unit test stubs """ + """ArrayOfArrayOfNumberOnly unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestArrayOfArrayOfNumberOnly(unittest.TestCase): pass def testArrayOfArrayOfNumberOnly(self): - """ - Test ArrayOfArrayOfNumberOnly - """ + """Test ArrayOfArrayOfNumberOnly""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.array_of_array_of_number_only.ArrayOfArrayOfNumberOnly() + # model = petstore_api.models.array_of_array_of_number_only.ArrayOfArrayOfNumberOnly() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_array_of_number_only.py b/samples/client/petstore/python-tornado/test/test_array_of_number_only.py index 6da67a490b6..7439364c7b1 100644 --- a/samples/client/petstore/python-tornado/test/test_array_of_number_only.py +++ b/samples/client/petstore/python-tornado/test/test_array_of_number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.array_of_number_only import ArrayOfNumberOnly # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.array_of_number_only import ArrayOfNumberOnly class TestArrayOfNumberOnly(unittest.TestCase): - """ ArrayOfNumberOnly unit test stubs """ + """ArrayOfNumberOnly unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestArrayOfNumberOnly(unittest.TestCase): pass def testArrayOfNumberOnly(self): - """ - Test ArrayOfNumberOnly - """ + """Test ArrayOfNumberOnly""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.array_of_number_only.ArrayOfNumberOnly() + # model = petstore_api.models.array_of_number_only.ArrayOfNumberOnly() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_array_test.py b/samples/client/petstore/python-tornado/test/test_array_test.py index dcf8cc111c0..d7feb2ac8f4 100644 --- a/samples/client/petstore/python-tornado/test/test_array_test.py +++ b/samples/client/petstore/python-tornado/test/test_array_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.array_test import ArrayTest # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.array_test import ArrayTest class TestArrayTest(unittest.TestCase): - """ ArrayTest unit test stubs """ + """ArrayTest unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestArrayTest(unittest.TestCase): pass def testArrayTest(self): - """ - Test ArrayTest - """ + """Test ArrayTest""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.array_test.ArrayTest() + # model = petstore_api.models.array_test.ArrayTest() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_capitalization.py b/samples/client/petstore/python-tornado/test/test_capitalization.py index 4ea6d2e3fd0..4ac874e817c 100644 --- a/samples/client/petstore/python-tornado/test/test_capitalization.py +++ b/samples/client/petstore/python-tornado/test/test_capitalization.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.capitalization import Capitalization # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.capitalization import Capitalization class TestCapitalization(unittest.TestCase): - """ Capitalization unit test stubs """ + """Capitalization unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestCapitalization(unittest.TestCase): pass def testCapitalization(self): - """ - Test Capitalization - """ + """Test Capitalization""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.capitalization.Capitalization() + # model = petstore_api.models.capitalization.Capitalization() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_cat.py b/samples/client/petstore/python-tornado/test/test_cat.py index 9d9fbc50ab3..370f1081383 100644 --- a/samples/client/petstore/python-tornado/test/test_cat.py +++ b/samples/client/petstore/python-tornado/test/test_cat.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.cat import Cat # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.cat import Cat class TestCat(unittest.TestCase): - """ Cat unit test stubs """ + """Cat unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestCat(unittest.TestCase): pass def testCat(self): - """ - Test Cat - """ + """Test Cat""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.cat.Cat() + # model = petstore_api.models.cat.Cat() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_category.py b/samples/client/petstore/python-tornado/test/test_category.py index 6ded8f0f1ac..7a9e40a1f65 100644 --- a/samples/client/petstore/python-tornado/test/test_category.py +++ b/samples/client/petstore/python-tornado/test/test_category.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.category import Category # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.category import Category class TestCategory(unittest.TestCase): - """ Category unit test stubs """ + """Category unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestCategory(unittest.TestCase): pass def testCategory(self): - """ - Test Category - """ + """Test Category""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.category.Category() + # model = petstore_api.models.category.Category() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_class_model.py b/samples/client/petstore/python-tornado/test/test_class_model.py index 85d56bbe52a..a42127abf50 100644 --- a/samples/client/petstore/python-tornado/test/test_class_model.py +++ b/samples/client/petstore/python-tornado/test/test_class_model.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.class_model import ClassModel # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.class_model import ClassModel class TestClassModel(unittest.TestCase): - """ ClassModel unit test stubs """ + """ClassModel unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestClassModel(unittest.TestCase): pass def testClassModel(self): - """ - Test ClassModel - """ + """Test ClassModel""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.class_model.ClassModel() + # model = petstore_api.models.class_model.ClassModel() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_client.py b/samples/client/petstore/python-tornado/test/test_client.py index 363ced2923c..81df726dbfc 100644 --- a/samples/client/petstore/python-tornado/test/test_client.py +++ b/samples/client/petstore/python-tornado/test/test_client.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.client import Client # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.client import Client class TestClient(unittest.TestCase): - """ Client unit test stubs """ + """Client unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestClient(unittest.TestCase): pass def testClient(self): - """ - Test Client - """ + """Test Client""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.client.Client() + # model = petstore_api.models.client.Client() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_dog.py b/samples/client/petstore/python-tornado/test/test_dog.py index b0428646591..ae13869b99f 100644 --- a/samples/client/petstore/python-tornado/test/test_dog.py +++ b/samples/client/petstore/python-tornado/test/test_dog.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.dog import Dog # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.dog import Dog class TestDog(unittest.TestCase): - """ Dog unit test stubs """ + """Dog unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestDog(unittest.TestCase): pass def testDog(self): - """ - Test Dog - """ + """Test Dog""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.dog.Dog() + # model = petstore_api.models.dog.Dog() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_enum_arrays.py b/samples/client/petstore/python-tornado/test/test_enum_arrays.py index 2803f17aede..144e48883e5 100644 --- a/samples/client/petstore/python-tornado/test/test_enum_arrays.py +++ b/samples/client/petstore/python-tornado/test/test_enum_arrays.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.enum_arrays import EnumArrays # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.enum_arrays import EnumArrays class TestEnumArrays(unittest.TestCase): - """ EnumArrays unit test stubs """ + """EnumArrays unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestEnumArrays(unittest.TestCase): pass def testEnumArrays(self): - """ - Test EnumArrays - """ + """Test EnumArrays""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.enum_arrays.EnumArrays() + # model = petstore_api.models.enum_arrays.EnumArrays() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_enum_class.py b/samples/client/petstore/python-tornado/test/test_enum_class.py index f673e741f84..a47581d2820 100644 --- a/samples/client/petstore/python-tornado/test/test_enum_class.py +++ b/samples/client/petstore/python-tornado/test/test_enum_class.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.enum_class import EnumClass # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.enum_class import EnumClass class TestEnumClass(unittest.TestCase): - """ EnumClass unit test stubs """ + """EnumClass unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestEnumClass(unittest.TestCase): pass def testEnumClass(self): - """ - Test EnumClass - """ + """Test EnumClass""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.enum_class.EnumClass() + # model = petstore_api.models.enum_class.EnumClass() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_enum_test.py b/samples/client/petstore/python-tornado/test/test_enum_test.py index e27c0107fd2..7487efe9fa1 100644 --- a/samples/client/petstore/python-tornado/test/test_enum_test.py +++ b/samples/client/petstore/python-tornado/test/test_enum_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.enum_test import EnumTest # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.enum_test import EnumTest class TestEnumTest(unittest.TestCase): - """ EnumTest unit test stubs """ + """EnumTest unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestEnumTest(unittest.TestCase): pass def testEnumTest(self): - """ - Test EnumTest - """ + """Test EnumTest""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.enum_test.EnumTest() + # model = petstore_api.models.enum_test.EnumTest() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_fake_api.py b/samples/client/petstore/python-tornado/test/test_fake_api.py index 55a02cf899c..00473d4a13b 100644 --- a/samples/client/petstore/python-tornado/test/test_fake_api.py +++ b/samples/client/petstore/python-tornado/test/test_fake_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,85 +13,78 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.fake_api import FakeApi # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.fake_api import FakeApi class TestFakeApi(unittest.TestCase): - """ FakeApi unit test stubs """ + """FakeApi unit test stubs""" def setUp(self): - self.api = petstore_api.apis.fake_api.FakeApi() + self.api = petstore_api.api.fake_api.FakeApi() # noqa: E501 def tearDown(self): pass def test_fake_outer_boolean_serialize(self): - """ - Test case for fake_outer_boolean_serialize + """Test case for fake_outer_boolean_serialize - """ pass def test_fake_outer_composite_serialize(self): - """ - Test case for fake_outer_composite_serialize + """Test case for fake_outer_composite_serialize - """ pass def test_fake_outer_number_serialize(self): - """ - Test case for fake_outer_number_serialize + """Test case for fake_outer_number_serialize - """ pass def test_fake_outer_string_serialize(self): - """ - Test case for fake_outer_string_serialize + """Test case for fake_outer_string_serialize - """ pass def test_test_client_model(self): - """ - Test case for test_client_model + """Test case for test_client_model - To test \"client\" model + To test \"client\" model # noqa: E501 """ pass def test_test_endpoint_parameters(self): - """ - Test case for test_endpoint_parameters + """Test case for test_endpoint_parameters - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 """ pass def test_test_enum_parameters(self): - """ - Test case for test_enum_parameters + """Test case for test_enum_parameters - To test enum parameters + To test enum parameters # noqa: E501 + """ + pass + + def test_test_inline_additional_properties(self): + """Test case for test_inline_additional_properties + + test inline additionalProperties # noqa: E501 """ pass def test_test_json_form_data(self): - """ - Test case for test_json_form_data + """Test case for test_json_form_data - test json serialization of form data + test json serialization of form data # noqa: E501 """ pass diff --git a/samples/client/petstore/python-tornado/test/test_fake_classname_tags_123_api.py b/samples/client/petstore/python-tornado/test/test_fake_classname_tags_123_api.py index 7a11a2378bf..8f40062a929 100644 --- a/samples/client/petstore/python-tornado/test/test_fake_classname_tags_123_api.py +++ b/samples/client/petstore/python-tornado/test/test_fake_classname_tags_123_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,29 +13,26 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.fake_classname_tags_123_api import FakeClassnameTags123Api # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.fake_classname_tags_123_api import FakeClassnameTags123Api class TestFakeClassnameTags123Api(unittest.TestCase): - """ FakeClassnameTags123Api unit test stubs """ + """FakeClassnameTags123Api unit test stubs""" def setUp(self): - self.api = petstore_api.apis.fake_classname_tags_123_api.FakeClassnameTags123Api() + self.api = petstore_api.api.fake_classname_tags_123_api.FakeClassnameTags123Api() # noqa: E501 def tearDown(self): pass def test_test_classname(self): - """ - Test case for test_classname + """Test case for test_classname - To test class name in snake case + To test class name in snake case # noqa: E501 """ pass diff --git a/samples/client/petstore/python-tornado/test/test_format_test.py b/samples/client/petstore/python-tornado/test/test_format_test.py index ad028c0b431..59809b9f442 100644 --- a/samples/client/petstore/python-tornado/test/test_format_test.py +++ b/samples/client/petstore/python-tornado/test/test_format_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.format_test import FormatTest # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.format_test import FormatTest class TestFormatTest(unittest.TestCase): - """ FormatTest unit test stubs """ + """FormatTest unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestFormatTest(unittest.TestCase): pass def testFormatTest(self): - """ - Test FormatTest - """ + """Test FormatTest""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.format_test.FormatTest() + # model = petstore_api.models.format_test.FormatTest() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_has_only_read_only.py b/samples/client/petstore/python-tornado/test/test_has_only_read_only.py index af029f26814..26d14aef1f8 100644 --- a/samples/client/petstore/python-tornado/test/test_has_only_read_only.py +++ b/samples/client/petstore/python-tornado/test/test_has_only_read_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.has_only_read_only import HasOnlyReadOnly # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.has_only_read_only import HasOnlyReadOnly class TestHasOnlyReadOnly(unittest.TestCase): - """ HasOnlyReadOnly unit test stubs """ + """HasOnlyReadOnly unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestHasOnlyReadOnly(unittest.TestCase): pass def testHasOnlyReadOnly(self): - """ - Test HasOnlyReadOnly - """ + """Test HasOnlyReadOnly""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.has_only_read_only.HasOnlyReadOnly() + # model = petstore_api.models.has_only_read_only.HasOnlyReadOnly() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_list.py b/samples/client/petstore/python-tornado/test/test_list.py index 14400e35281..c2cca419f37 100644 --- a/samples/client/petstore/python-tornado/test/test_list.py +++ b/samples/client/petstore/python-tornado/test/test_list.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.list import List # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.list import List class TestList(unittest.TestCase): - """ List unit test stubs """ + """List unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestList(unittest.TestCase): pass def testList(self): - """ - Test List - """ + """Test List""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.list.List() + # model = petstore_api.models.list.List() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_map_test.py b/samples/client/petstore/python-tornado/test/test_map_test.py index c4b2092f0ce..155797d9b2d 100644 --- a/samples/client/petstore/python-tornado/test/test_map_test.py +++ b/samples/client/petstore/python-tornado/test/test_map_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.map_test import MapTest # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.map_test import MapTest class TestMapTest(unittest.TestCase): - """ MapTest unit test stubs """ + """MapTest unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestMapTest(unittest.TestCase): pass def testMapTest(self): - """ - Test MapTest - """ + """Test MapTest""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.map_test.MapTest() + # model = petstore_api.models.map_test.MapTest() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python-tornado/test/test_mixed_properties_and_additional_properties_class.py index f614d36da8a..12a56764080 100644 --- a/samples/client/petstore/python-tornado/test/test_mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python-tornado/test/test_mixed_properties_and_additional_properties_class.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass # noqa: E501 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 """ + """MixedPropertiesAndAdditionalPropertiesClass unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestMixedPropertiesAndAdditionalPropertiesClass(unittest.TestCase): pass def testMixedPropertiesAndAdditionalPropertiesClass(self): - """ - Test MixedPropertiesAndAdditionalPropertiesClass - """ + """Test MixedPropertiesAndAdditionalPropertiesClass""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.mixed_properties_and_additional_properties_class.MixedPropertiesAndAdditionalPropertiesClass() + # model = petstore_api.models.mixed_properties_and_additional_properties_class.MixedPropertiesAndAdditionalPropertiesClass() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_model_200_response.py b/samples/client/petstore/python-tornado/test/test_model_200_response.py index f202a2d454f..f577dd42144 100644 --- a/samples/client/petstore/python-tornado/test/test_model_200_response.py +++ b/samples/client/petstore/python-tornado/test/test_model_200_response.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.model_200_response import Model200Response # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.model_200_response import Model200Response class TestModel200Response(unittest.TestCase): - """ Model200Response unit test stubs """ + """Model200Response unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestModel200Response(unittest.TestCase): pass def testModel200Response(self): - """ - Test Model200Response - """ + """Test Model200Response""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.model_200_response.Model200Response() + # model = petstore_api.models.model_200_response.Model200Response() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_model_return.py b/samples/client/petstore/python-tornado/test/test_model_return.py index 347c8e4d7cb..64cf27f63ab 100644 --- a/samples/client/petstore/python-tornado/test/test_model_return.py +++ b/samples/client/petstore/python-tornado/test/test_model_return.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.model_return import ModelReturn # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.model_return import ModelReturn class TestModelReturn(unittest.TestCase): - """ ModelReturn unit test stubs """ + """ModelReturn unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestModelReturn(unittest.TestCase): pass def testModelReturn(self): - """ - Test ModelReturn - """ + """Test ModelReturn""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.model_return.ModelReturn() + # model = petstore_api.models.model_return.ModelReturn() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_name.py b/samples/client/petstore/python-tornado/test/test_name.py index c06e35427f6..beba143f39c 100644 --- a/samples/client/petstore/python-tornado/test/test_name.py +++ b/samples/client/petstore/python-tornado/test/test_name.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.name import Name # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.name import Name class TestName(unittest.TestCase): - """ Name unit test stubs """ + """Name unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestName(unittest.TestCase): pass def testName(self): - """ - Test Name - """ + """Test Name""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.name.Name() + # model = petstore_api.models.name.Name() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_number_only.py b/samples/client/petstore/python-tornado/test/test_number_only.py index db3197a9e5b..f2600c79526 100644 --- a/samples/client/petstore/python-tornado/test/test_number_only.py +++ b/samples/client/petstore/python-tornado/test/test_number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.number_only import NumberOnly # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.number_only import NumberOnly class TestNumberOnly(unittest.TestCase): - """ NumberOnly unit test stubs """ + """NumberOnly unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestNumberOnly(unittest.TestCase): pass def testNumberOnly(self): - """ - Test NumberOnly - """ + """Test NumberOnly""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.number_only.NumberOnly() + # model = petstore_api.models.number_only.NumberOnly() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_order.py b/samples/client/petstore/python-tornado/test/test_order.py index d911487ce97..ed4f8c7d161 100644 --- a/samples/client/petstore/python-tornado/test/test_order.py +++ b/samples/client/petstore/python-tornado/test/test_order.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.order import Order # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.order import Order class TestOrder(unittest.TestCase): - """ Order unit test stubs """ + """Order unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestOrder(unittest.TestCase): pass def testOrder(self): - """ - Test Order - """ + """Test Order""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.order.Order() + # model = petstore_api.models.order.Order() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_outer_boolean.py b/samples/client/petstore/python-tornado/test/test_outer_boolean.py index 9474ab76968..4a7e446693e 100644 --- a/samples/client/petstore/python-tornado/test/test_outer_boolean.py +++ b/samples/client/petstore/python-tornado/test/test_outer_boolean.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.outer_boolean import OuterBoolean # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.outer_boolean import OuterBoolean class TestOuterBoolean(unittest.TestCase): - """ OuterBoolean unit test stubs """ + """OuterBoolean unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestOuterBoolean(unittest.TestCase): pass def testOuterBoolean(self): - """ - Test OuterBoolean - """ + """Test OuterBoolean""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.outer_boolean.OuterBoolean() + # model = petstore_api.models.outer_boolean.OuterBoolean() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_outer_composite.py b/samples/client/petstore/python-tornado/test/test_outer_composite.py index ebbd9d03e6f..e444e695fe8 100644 --- a/samples/client/petstore/python-tornado/test/test_outer_composite.py +++ b/samples/client/petstore/python-tornado/test/test_outer_composite.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.outer_composite import OuterComposite # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.outer_composite import OuterComposite class TestOuterComposite(unittest.TestCase): - """ OuterComposite unit test stubs """ + """OuterComposite unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestOuterComposite(unittest.TestCase): pass def testOuterComposite(self): - """ - Test OuterComposite - """ + """Test OuterComposite""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.outer_composite.OuterComposite() + # model = petstore_api.models.outer_composite.OuterComposite() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_outer_enum.py b/samples/client/petstore/python-tornado/test/test_outer_enum.py index c6e1f030ef1..e3fb15e1b6b 100644 --- a/samples/client/petstore/python-tornado/test/test_outer_enum.py +++ b/samples/client/petstore/python-tornado/test/test_outer_enum.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.outer_enum import OuterEnum # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.outer_enum import OuterEnum class TestOuterEnum(unittest.TestCase): - """ OuterEnum unit test stubs """ + """OuterEnum unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestOuterEnum(unittest.TestCase): pass def testOuterEnum(self): - """ - Test OuterEnum - """ + """Test OuterEnum""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.outer_enum.OuterEnum() + # model = petstore_api.models.outer_enum.OuterEnum() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_outer_number.py b/samples/client/petstore/python-tornado/test/test_outer_number.py index 9f97b407047..da5d3ceee61 100644 --- a/samples/client/petstore/python-tornado/test/test_outer_number.py +++ b/samples/client/petstore/python-tornado/test/test_outer_number.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.outer_number import OuterNumber # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.outer_number import OuterNumber class TestOuterNumber(unittest.TestCase): - """ OuterNumber unit test stubs """ + """OuterNumber unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestOuterNumber(unittest.TestCase): pass def testOuterNumber(self): - """ - Test OuterNumber - """ + """Test OuterNumber""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.outer_number.OuterNumber() + # model = petstore_api.models.outer_number.OuterNumber() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_outer_string.py b/samples/client/petstore/python-tornado/test/test_outer_string.py index b0ac85ed934..02b4967e3b9 100644 --- a/samples/client/petstore/python-tornado/test/test_outer_string.py +++ b/samples/client/petstore/python-tornado/test/test_outer_string.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.outer_string import OuterString # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.outer_string import OuterString class TestOuterString(unittest.TestCase): - """ OuterString unit test stubs """ + """OuterString unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestOuterString(unittest.TestCase): pass def testOuterString(self): - """ - Test OuterString - """ + """Test OuterString""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.outer_string.OuterString() + # model = petstore_api.models.outer_string.OuterString() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_pet.py b/samples/client/petstore/python-tornado/test/test_pet.py index c3e8191bec3..d8df24f92b1 100644 --- a/samples/client/petstore/python-tornado/test/test_pet.py +++ b/samples/client/petstore/python-tornado/test/test_pet.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.pet import Pet # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.pet import Pet class TestPet(unittest.TestCase): - """ Pet unit test stubs """ + """Pet unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestPet(unittest.TestCase): pass def testPet(self): - """ - Test Pet - """ + """Test Pet""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.pet.Pet() + # model = petstore_api.models.pet.Pet() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_pet_api.py b/samples/client/petstore/python-tornado/test/test_pet_api.py index 1eafc35b28c..1e2dd1c42b6 100644 --- a/samples/client/petstore/python-tornado/test/test_pet_api.py +++ b/samples/client/petstore/python-tornado/test/test_pet_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,85 +13,75 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.pet_api import PetApi # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.pet_api import PetApi class TestPetApi(unittest.TestCase): - """ PetApi unit test stubs """ + """PetApi unit test stubs""" def setUp(self): - self.api = petstore_api.apis.pet_api.PetApi() + self.api = petstore_api.api.pet_api.PetApi() # noqa: E501 def tearDown(self): pass def test_add_pet(self): - """ - Test case for add_pet + """Test case for add_pet - Add a new pet to the store + Add a new pet to the store # noqa: E501 """ pass def test_delete_pet(self): - """ - Test case for delete_pet + """Test case for delete_pet - Deletes a pet + Deletes a pet # noqa: E501 """ pass def test_find_pets_by_status(self): - """ - Test case for find_pets_by_status + """Test case for find_pets_by_status - Finds Pets by status + Finds Pets by status # noqa: E501 """ pass def test_find_pets_by_tags(self): - """ - Test case for find_pets_by_tags + """Test case for find_pets_by_tags - Finds Pets by tags + Finds Pets by tags # noqa: E501 """ pass def test_get_pet_by_id(self): - """ - Test case for get_pet_by_id + """Test case for get_pet_by_id - Find pet by ID + Find pet by ID # noqa: E501 """ pass def test_update_pet(self): - """ - Test case for update_pet + """Test case for update_pet - Update an existing pet + Update an existing pet # noqa: E501 """ pass def test_update_pet_with_form(self): - """ - Test case for update_pet_with_form + """Test case for update_pet_with_form - Updates a pet in the store with form data + Updates a pet in the store with form data # noqa: E501 """ pass def test_upload_file(self): - """ - Test case for upload_file + """Test case for upload_file - uploads an image + uploads an image # noqa: E501 """ pass diff --git a/samples/client/petstore/python-tornado/test/test_read_only_first.py b/samples/client/petstore/python-tornado/test/test_read_only_first.py index c89d5d3b6a1..94bf3d127de 100644 --- a/samples/client/petstore/python-tornado/test/test_read_only_first.py +++ b/samples/client/petstore/python-tornado/test/test_read_only_first.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.read_only_first import ReadOnlyFirst # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.read_only_first import ReadOnlyFirst class TestReadOnlyFirst(unittest.TestCase): - """ ReadOnlyFirst unit test stubs """ + """ReadOnlyFirst unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestReadOnlyFirst(unittest.TestCase): pass def testReadOnlyFirst(self): - """ - Test ReadOnlyFirst - """ + """Test ReadOnlyFirst""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.read_only_first.ReadOnlyFirst() + # model = petstore_api.models.read_only_first.ReadOnlyFirst() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_special_model_name.py b/samples/client/petstore/python-tornado/test/test_special_model_name.py index d9fa392c36b..002f660cc26 100644 --- a/samples/client/petstore/python-tornado/test/test_special_model_name.py +++ b/samples/client/petstore/python-tornado/test/test_special_model_name.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.special_model_name import SpecialModelName # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.special_model_name import SpecialModelName class TestSpecialModelName(unittest.TestCase): - """ SpecialModelName unit test stubs """ + """SpecialModelName unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestSpecialModelName(unittest.TestCase): pass def testSpecialModelName(self): - """ - Test SpecialModelName - """ + """Test SpecialModelName""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.special_model_name.SpecialModelName() + # model = petstore_api.models.special_model_name.SpecialModelName() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_store_api.py b/samples/client/petstore/python-tornado/test/test_store_api.py index f131b6068b2..537c1bc03f1 100644 --- a/samples/client/petstore/python-tornado/test/test_store_api.py +++ b/samples/client/petstore/python-tornado/test/test_store_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,53 +13,47 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.store_api import StoreApi # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.store_api import StoreApi class TestStoreApi(unittest.TestCase): - """ StoreApi unit test stubs """ + """StoreApi unit test stubs""" def setUp(self): - self.api = petstore_api.apis.store_api.StoreApi() + self.api = petstore_api.api.store_api.StoreApi() # noqa: E501 def tearDown(self): pass def test_delete_order(self): - """ - Test case for delete_order + """Test case for delete_order - Delete purchase order by ID + Delete purchase order by ID # noqa: E501 """ pass def test_get_inventory(self): - """ - Test case for get_inventory + """Test case for get_inventory - Returns pet inventories by status + Returns pet inventories by status # noqa: E501 """ pass def test_get_order_by_id(self): - """ - Test case for get_order_by_id + """Test case for get_order_by_id - Find purchase order by ID + Find purchase order by ID # noqa: E501 """ pass def test_place_order(self): - """ - Test case for place_order + """Test case for place_order - Place an order for a pet + Place an order for a pet # noqa: E501 """ pass diff --git a/samples/client/petstore/python-tornado/test/test_tag.py b/samples/client/petstore/python-tornado/test/test_tag.py index 76f79932c96..e9bc1d471d1 100644 --- a/samples/client/petstore/python-tornado/test/test_tag.py +++ b/samples/client/petstore/python-tornado/test/test_tag.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.tag import Tag # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.tag import Tag class TestTag(unittest.TestCase): - """ Tag unit test stubs """ + """Tag unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestTag(unittest.TestCase): pass def testTag(self): - """ - Test Tag - """ + """Test Tag""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.tag.Tag() + # model = petstore_api.models.tag.Tag() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_user.py b/samples/client/petstore/python-tornado/test/test_user.py index 82f5d9058b0..3575746c00f 100644 --- a/samples/client/petstore/python-tornado/test/test_user.py +++ b/samples/client/petstore/python-tornado/test/test_user.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.user import User # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.user import User class TestUser(unittest.TestCase): - """ User unit test stubs """ + """User unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestUser(unittest.TestCase): pass def testUser(self): - """ - Test User - """ + """Test User""" # FIXME: construct object with mandatory attributes with example values - #model = petstore_api.models.user.User() + # model = petstore_api.models.user.User() # noqa: E501 pass diff --git a/samples/client/petstore/python-tornado/test/test_user_api.py b/samples/client/petstore/python-tornado/test/test_user_api.py index 3e0be964a2d..4ebd90f95e2 100644 --- a/samples/client/petstore/python-tornado/test/test_user_api.py +++ b/samples/client/petstore/python-tornado/test/test_user_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,85 +13,75 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.user_api import UserApi # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.user_api import UserApi class TestUserApi(unittest.TestCase): - """ UserApi unit test stubs """ + """UserApi unit test stubs""" def setUp(self): - self.api = petstore_api.apis.user_api.UserApi() + self.api = petstore_api.api.user_api.UserApi() # noqa: E501 def tearDown(self): pass def test_create_user(self): - """ - Test case for create_user + """Test case for create_user - Create user + Create user # noqa: E501 """ pass def test_create_users_with_array_input(self): - """ - Test case for create_users_with_array_input + """Test case for create_users_with_array_input - Creates list of users with given input array + Creates list of users with given input array # noqa: E501 """ pass def test_create_users_with_list_input(self): - """ - Test case for create_users_with_list_input + """Test case for create_users_with_list_input - Creates list of users with given input array + Creates list of users with given input array # noqa: E501 """ pass def test_delete_user(self): - """ - Test case for delete_user + """Test case for delete_user - Delete user + Delete user # noqa: E501 """ pass def test_get_user_by_name(self): - """ - Test case for get_user_by_name + """Test case for get_user_by_name - Get user by user name + Get user by user name # noqa: E501 """ pass def test_login_user(self): - """ - Test case for login_user + """Test case for login_user - Logs user into the system + Logs user into the system # noqa: E501 """ pass def test_logout_user(self): - """ - Test case for logout_user + """Test case for logout_user - Logs out current logged in user session + Logs out current logged in user session # noqa: E501 """ pass def test_update_user(self): - """ - Test case for update_user + """Test case for update_user - Updated user + Updated user # noqa: E501 """ pass diff --git a/samples/client/petstore/python-tornado/test_python2_and_3.sh b/samples/client/petstore/python-tornado/test_python2_and_3.sh new file mode 100755 index 00000000000..a224ffe75dc --- /dev/null +++ b/samples/client/petstore/python-tornado/test_python2_and_3.sh @@ -0,0 +1,32 @@ +#!/bin/bash + +REQUIREMENTS_FILE=dev-requirements.txt +REQUIREMENTS_OUT=dev-requirements.txt.log +SETUP_OUT=*.egg-info +VENV=.venv +DEACTIVE=false + +export LC_ALL=en_US.UTF-8 +export LANG=en_US.UTF-8 + +### set virtualenv +if [ -z "$VIRTUAL_ENV" ]; then + virtualenv $VENV --no-site-packages --always-copy + source $VENV/bin/activate + DEACTIVE=true +fi + +### install dependencies +pip install -r $REQUIREMENTS_FILE | tee -a $REQUIREMENTS_OUT +python setup.py develop + +### run tests +tox + +### static analysis of code +flake8 --show-source petstore_api/ + +### deactivate virtualenv +#if [ $DEACTIVE == true ]; then +# deactivate +#fi diff --git a/samples/client/petstore/python-tornado/testfiles/foo.png b/samples/client/petstore/python-tornado/testfiles/foo.png new file mode 100644 index 00000000000..a9b12cf5927 Binary files /dev/null and b/samples/client/petstore/python-tornado/testfiles/foo.png differ diff --git a/samples/client/petstore/python/petstore b/samples/client/petstore/python-tornado/tests/__init__.py similarity index 100% rename from samples/client/petstore/python/petstore rename to samples/client/petstore/python-tornado/tests/__init__.py diff --git a/samples/client/petstore/python-tornado/tests/test_pet_api.py b/samples/client/petstore/python-tornado/tests/test_pet_api.py new file mode 100644 index 00000000000..ad4ec29b2bc --- /dev/null +++ b/samples/client/petstore/python-tornado/tests/test_pet_api.py @@ -0,0 +1,221 @@ +# coding: utf-8 + +# flake8: noqa + +""" +Run the tests. +$ pip install nose (optional) +$ cd petstore_api-python +$ nosetests -v +""" + +import os +import unittest + +from tornado.testing import AsyncTestCase, gen_test +from tornado.ioloop import IOLoop + +import petstore_api +from petstore_api import Configuration +from petstore_api.rest import ApiException + +from .util import id_gen + +import json + +import urllib3 + +HOST = 'http://petstore.swagger.io/v2' + + +class PetApiTests(AsyncTestCase): + + def setUp(self): + AsyncTestCase.setUp(self) + config = Configuration() + config.host = HOST + self.api_client = petstore_api.ApiClient(config) + self.pet_api = petstore_api.PetApi(self.api_client) + self.setUpModels() + self.setUpFiles() + + def setUpModels(self): + self.category = petstore_api.Category() + self.category.id = id_gen() + self.category.name = "dog" + self.tag = petstore_api.Tag() + self.tag.id = id_gen() + self.tag.name = "swagger-codegen-python-pet-tag" + self.pet = petstore_api.Pet(name="hello kity", photo_urls=["http://foo.bar.com/1", "http://foo.bar.com/2"]) + self.pet.id = id_gen() + self.pet.status = "sold" + self.pet.category = self.category + self.pet.tags = [self.tag] + + def setUpFiles(self): + self.test_file_dir = os.path.join(os.path.dirname(__file__), "..", "testfiles") + self.test_file_dir = os.path.realpath(self.test_file_dir) + self.foo = os.path.join(self.test_file_dir, "foo.png") + + def get_new_ioloop(self): + return IOLoop.instance() + + @gen_test + def test_separate_default_client_instances(self): + pet_api = petstore_api.PetApi() + pet_api2 = petstore_api.PetApi() + self.assertNotEqual(pet_api.api_client, pet_api2.api_client) + + pet_api.api_client.user_agent = 'api client 3' + pet_api2.api_client.user_agent = 'api client 4' + + self.assertNotEqual(pet_api.api_client.user_agent, pet_api2.api_client.user_agent) + + @gen_test + def test_separate_default_config_instances(self): + pet_api = petstore_api.PetApi() + pet_api2 = petstore_api.PetApi() + self.assertNotEqual(pet_api.api_client.configuration, pet_api2.api_client.configuration) + + pet_api.api_client.configuration.host = 'somehost' + pet_api2.api_client.configuration.host = 'someotherhost' + self.assertNotEqual(pet_api.api_client.configuration.host, pet_api2.api_client.configuration.host) + + @gen_test + def test_async_request(self): + # It works but tornado is async by default and creating threadpool + # to do it looks crazy ;) + thread = self.pet_api.add_pet(body=self.pet, async=True) + response = yield thread.get() + self.assertIsNone(response) + + thread = self.pet_api.get_pet_by_id(self.pet.id, async=True) + result = yield thread.get() + self.assertIsInstance(result, petstore_api.Pet) + + @gen_test + def test_async_with_result(self): + yield self.pet_api.add_pet(body=self.pet) + + thread = self.pet_api.get_pet_by_id(self.pet.id, async=True) + thread2 = self.pet_api.get_pet_by_id(self.pet.id, async=True) + + response = yield thread.get() + response2 = yield thread2.get() + + self.assertEquals(response.id, self.pet.id) + self.assertIsNotNone(response2.id, self.pet.id) + + @gen_test + def test_tornado_async_with_result(self): + yield self.pet_api.add_pet(body=self.pet) + + query1 = self.pet_api.get_pet_by_id(self.pet.id) + query2 = self.pet_api.get_pet_by_id(self.pet.id) + + response1 = yield query1 + response2 = yield query2 + + self.assertEquals(response1.id, self.pet.id) + self.assertIsNotNone(response2.id, self.pet.id) + + @gen_test + def test_add_pet_and_get_pet_by_id(self): + yield self.pet_api.add_pet(body=self.pet) + + fetched = yield self.pet_api.get_pet_by_id(pet_id=self.pet.id) + self.assertIsNotNone(fetched) + self.assertEqual(self.pet.id, fetched.id) + self.assertIsNotNone(fetched.category) + self.assertEqual(self.pet.category.name, fetched.category.name) + + @gen_test + def test_add_pet_and_get_pet_by_id_with_http_info(self): + yield self.pet_api.add_pet(body=self.pet) + + fetched = yield self.pet_api.get_pet_by_id_with_http_info(pet_id=self.pet.id) + self.assertIsNotNone(fetched) + self.assertEqual(self.pet.id, fetched[0].id) + self.assertIsNotNone(fetched[0].category) + self.assertEqual(self.pet.category.name, fetched[0].category.name) + + @gen_test + def test_update_pet(self): + self.pet.name = "hello kity with updated" + yield self.pet_api.update_pet(body=self.pet) + + fetched = yield self.pet_api.get_pet_by_id(pet_id=self.pet.id) + self.assertIsNotNone(fetched) + self.assertEqual(self.pet.id, fetched.id) + self.assertEqual(self.pet.name, fetched.name) + self.assertIsNotNone(fetched.category) + self.assertEqual(fetched.category.name, self.pet.category.name) + + @gen_test + @unittest.skip('skipping the test as the method sometimes invalid Petstore object with incorrect status') + def test_find_pets_by_status(self): + yield self.pet_api.add_pet(body=self.pet) + pets = yield self.pet_api.find_pets_by_status(status=[self.pet.status]) + self.assertIn( + self.pet.id, + list(map(lambda x: getattr(x, 'id'), pets)) + ) + + @gen_test + @unittest.skip("skipping the test as the method sometimes invalid Petstore object with incorrect status") + def test_find_pets_by_tags(self): + yield self.pet_api.add_pet(body=self.pet) + pets = yield self.pet_api.find_pets_by_tags(tags=[self.tag.name]) + self.assertIn( + self.pet.id, + list(map(lambda x: getattr(x, 'id'), pets)) + ) + + @gen_test + def test_update_pet_with_form(self): + yield self.pet_api.add_pet(body=self.pet) + + name = "hello kity with form updated" + status = "pending" + yield self.pet_api.update_pet_with_form(pet_id=self.pet.id, name=name, status=status) + + fetched = yield self.pet_api.get_pet_by_id(pet_id=self.pet.id) + self.assertEqual(self.pet.id, fetched.id) + self.assertEqual(name, fetched.name) + self.assertEqual(status, fetched.status) + + @gen_test(timeout=10) + def test_upload_file(self): + # upload file with form parameter + try: + additional_metadata = "special" + yield self.pet_api.upload_file( + pet_id=self.pet.id, + additional_metadata=additional_metadata, + file=self.foo + ) + except ApiException as e: + self.fail("upload_file() raised {0} unexpectedly".format(type(e))) + + # upload only file + try: + yield self.pet_api.upload_file(pet_id=self.pet.id, file=self.foo) + except ApiException as e: + self.fail("upload_file() raised {0} unexpectedly".format(type(e))) + + @gen_test + def test_delete_pet(self): + yield self.pet_api.add_pet(body=self.pet) + yield self.pet_api.delete_pet(pet_id=self.pet.id, api_key="special-key") + + try: + yield self.pet_api.get_pet_by_id(pet_id=self.pet.id) + raise Exception("expected an error") + except ApiException as e: + self.assertEqual(404, e.status) + + +if __name__ == '__main__': + import logging + logging.basicConfig(level=logging.DEBUG) + unittest.main() diff --git a/samples/client/petstore/python-tornado/tests/util.py b/samples/client/petstore/python-tornado/tests/util.py new file mode 100644 index 00000000000..113d7dcc547 --- /dev/null +++ b/samples/client/petstore/python-tornado/tests/util.py @@ -0,0 +1,8 @@ +# flake8: noqa + +import random + + +def id_gen(bits=32): + """ Returns a n-bit randomly generated int """ + return int(random.getrandbits(bits)) diff --git a/samples/client/petstore/python/Makefile b/samples/client/petstore/python/Makefile index 52033cee703..ba5c5e73c63 100644 --- a/samples/client/petstore/python/Makefile +++ b/samples/client/petstore/python/Makefile @@ -14,8 +14,8 @@ clean: find . -name "*.py[oc]" -delete find . -name "__pycache__" -delete -test: clean +test: clean bash ./test_python2.sh -test-all: clean +test-all: clean bash ./test_python2_and_3.sh diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index 87f80990fc5..a49d99c556c 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -77,6 +77,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model *FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**test_inline_additional_properties**](docs/FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties *FakeApi* | [**test_json_form_data**](docs/FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data *FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store diff --git a/samples/client/petstore/python/dev-requirements.txt b/samples/client/petstore/python/dev-requirements.txt index 01a2e25f1c7..f50c13b5c50 100644 --- a/samples/client/petstore/python/dev-requirements.txt +++ b/samples/client/petstore/python/dev-requirements.txt @@ -2,3 +2,4 @@ nose tox coverage randomize +flake8 diff --git a/samples/client/petstore/python/docs/AdditionalPropertiesClass.md b/samples/client/petstore/python/docs/AdditionalPropertiesClass.md index ea12f270f02..796a789d4c4 100644 --- a/samples/client/petstore/python/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/python/docs/AdditionalPropertiesClass.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **map_property** | **dict(str, str)** | | [optional] -**map_of_map_property** | [**dict(str, dict(str, str))**](dict.md) | | [optional] +**map_of_map_property** | **dict(str, dict(str, 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/AnotherFakeApi.md b/samples/client/petstore/python/docs/AnotherFakeApi.md index b78fcf86f43..3d70f7a2875 100644 --- a/samples/client/petstore/python/docs/AnotherFakeApi.md +++ b/samples/client/petstore/python/docs/AnotherFakeApi.md @@ -14,7 +14,7 @@ To test special tags To test special tags -### Example +### Example ```python from __future__ import print_function import time @@ -26,7 +26,7 @@ from pprint import pprint api_instance = petstore_api.AnotherFakeApi() body = petstore_api.Client() # Client | client model -try: +try: # To test special tags api_response = api_instance.test_special_tags(body) pprint(api_response) diff --git a/samples/client/petstore/python/docs/FakeApi.md b/samples/client/petstore/python/docs/FakeApi.md index eb669540e53..1da84500bfe 100644 --- a/samples/client/petstore/python/docs/FakeApi.md +++ b/samples/client/petstore/python/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model [**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +[**test_inline_additional_properties**](FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**test_json_form_data**](FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data @@ -21,7 +22,7 @@ Method | HTTP request | Description Test serialization of outer boolean types -### Example +### Example ```python from __future__ import print_function import time @@ -33,7 +34,7 @@ from pprint import pprint api_instance = petstore_api.FakeApi() body = petstore_api.OuterBoolean() # OuterBoolean | Input boolean as post body (optional) -try: +try: api_response = api_instance.fake_outer_boolean_serialize(body=body) pprint(api_response) except ApiException as e: @@ -68,7 +69,7 @@ No authorization required Test serialization of object with outer number type -### Example +### Example ```python from __future__ import print_function import time @@ -80,7 +81,7 @@ from pprint import pprint api_instance = petstore_api.FakeApi() body = petstore_api.OuterComposite() # OuterComposite | Input composite as post body (optional) -try: +try: api_response = api_instance.fake_outer_composite_serialize(body=body) pprint(api_response) except ApiException as e: @@ -115,7 +116,7 @@ No authorization required Test serialization of outer number types -### Example +### Example ```python from __future__ import print_function import time @@ -127,7 +128,7 @@ from pprint import pprint api_instance = petstore_api.FakeApi() body = petstore_api.OuterNumber() # OuterNumber | Input number as post body (optional) -try: +try: api_response = api_instance.fake_outer_number_serialize(body=body) pprint(api_response) except ApiException as e: @@ -162,7 +163,7 @@ No authorization required Test serialization of outer string types -### Example +### Example ```python from __future__ import print_function import time @@ -174,7 +175,7 @@ from pprint import pprint api_instance = petstore_api.FakeApi() body = petstore_api.OuterString() # OuterString | Input string as post body (optional) -try: +try: api_response = api_instance.fake_outer_string_serialize(body=body) pprint(api_response) except ApiException as e: @@ -209,7 +210,7 @@ To test \"client\" model To test \"client\" model -### Example +### Example ```python from __future__ import print_function import time @@ -221,7 +222,7 @@ from pprint import pprint api_instance = petstore_api.FakeApi() body = petstore_api.Client() # Client | client model -try: +try: # To test \"client\" model api_response = api_instance.test_client_model(body) pprint(api_response) @@ -257,7 +258,7 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -### Example +### Example ```python from __future__ import print_function import time @@ -272,10 +273,10 @@ configuration.password = 'YOUR_PASSWORD' # create an instance of the API class api_instance = petstore_api.FakeApi(petstore_api.ApiClient(configuration)) -number = 3.4 # float | None +number = 8.14 # float | None double = 1.2 # float | None pattern_without_delimiter = 'pattern_without_delimiter_example' # str | None -byte = 'byte_example' # str | None +byte = 'B' # str | None integer = 56 # int | None (optional) int32 = 56 # int | None (optional) int64 = 789 # int | None (optional) @@ -287,7 +288,7 @@ date_time = '2013-10-20T19:20:30+01:00' # datetime | None (optional) password = 'password_example' # str | None (optional) param_callback = 'param_callback_example' # str | None (optional) -try: +try: # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password, param_callback=param_callback) except ApiException as e: @@ -335,7 +336,7 @@ To test enum parameters To test enum parameters -### Example +### Example ```python from __future__ import print_function import time @@ -354,7 +355,7 @@ enum_query_string = '-efg' # str | Query parameter enum test (string) (optional) enum_query_integer = 56 # int | Query parameter enum test (double) (optional) enum_query_double = 1.2 # float | Query parameter enum test (double) (optional) -try: +try: # To test enum parameters api_instance.test_enum_parameters(enum_form_string_array=enum_form_string_array, enum_form_string=enum_form_string, enum_header_string_array=enum_header_string_array, enum_header_string=enum_header_string, enum_query_string_array=enum_query_string_array, enum_query_string=enum_query_string, enum_query_integer=enum_query_integer, enum_query_double=enum_query_double) except ApiException as e: @@ -389,6 +390,53 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_inline_additional_properties** +> test_inline_additional_properties(param) + +test inline additionalProperties + + + +### Example +```python +from __future__ import print_function +import time +import petstore_api +from petstore_api.rest import ApiException +from pprint import pprint + +# create an instance of the API class +api_instance = petstore_api.FakeApi() +param = NULL # object | request body + +try: + # test inline additionalProperties + api_instance.test_inline_additional_properties(param) +except ApiException as e: + print("Exception when calling FakeApi->test_inline_additional_properties: %s\n" % e) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **object**| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_json_form_data** > test_json_form_data(param, param2) @@ -396,7 +444,7 @@ test json serialization of form data -### Example +### Example ```python from __future__ import print_function import time @@ -409,7 +457,7 @@ api_instance = petstore_api.FakeApi() param = 'param_example' # str | field1 param2 = 'param2_example' # str | field2 -try: +try: # test json serialization of form data api_instance.test_json_form_data(param, param2) except ApiException as e: diff --git a/samples/client/petstore/python/docs/FakeClassnameTags123Api.md b/samples/client/petstore/python/docs/FakeClassnameTags123Api.md index a103a4ee327..2546c09ca4a 100644 --- a/samples/client/petstore/python/docs/FakeClassnameTags123Api.md +++ b/samples/client/petstore/python/docs/FakeClassnameTags123Api.md @@ -12,7 +12,7 @@ Method | HTTP request | Description To test class name in snake case -### Example +### Example ```python from __future__ import print_function import time @@ -30,7 +30,7 @@ configuration.api_key['api_key_query'] = 'YOUR_API_KEY' api_instance = petstore_api.FakeClassnameTags123Api(petstore_api.ApiClient(configuration)) body = petstore_api.Client() # Client | client model -try: +try: # To test class name in snake case api_response = api_instance.test_classname(body) pprint(api_response) diff --git a/samples/client/petstore/python/docs/MapTest.md b/samples/client/petstore/python/docs/MapTest.md index 63cdab0374a..68844755d42 100644 --- a/samples/client/petstore/python/docs/MapTest.md +++ b/samples/client/petstore/python/docs/MapTest.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**map_map_of_string** | [**dict(str, dict(str, str))**](dict.md) | | [optional] +**map_map_of_string** | **dict(str, dict(str, str))** | | [optional] **map_of_enum_string** | **dict(str, 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/PetApi.md b/samples/client/petstore/python/docs/PetApi.md index 74c6a5196fd..53b9158e699 100644 --- a/samples/client/petstore/python/docs/PetApi.md +++ b/samples/client/petstore/python/docs/PetApi.md @@ -21,7 +21,7 @@ Add a new pet to the store -### Example +### Example ```python from __future__ import print_function import time @@ -37,7 +37,7 @@ configuration.access_token = 'YOUR_ACCESS_TOKEN' api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) body = petstore_api.Pet() # Pet | Pet object that needs to be added to the store -try: +try: # Add a new pet to the store api_instance.add_pet(body) except ApiException as e: @@ -72,7 +72,7 @@ Deletes a pet -### Example +### Example ```python from __future__ import print_function import time @@ -89,7 +89,7 @@ api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) pet_id = 789 # int | Pet id to delete api_key = 'api_key_example' # str | (optional) -try: +try: # Deletes a pet api_instance.delete_pet(pet_id, api_key=api_key) except ApiException as e: @@ -125,7 +125,7 @@ Finds Pets by status Multiple status values can be provided with comma separated strings -### Example +### Example ```python from __future__ import print_function import time @@ -141,7 +141,7 @@ configuration.access_token = 'YOUR_ACCESS_TOKEN' api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) status = ['status_example'] # list[str] | Status values that need to be considered for filter -try: +try: # Finds Pets by status api_response = api_instance.find_pets_by_status(status) pprint(api_response) @@ -177,7 +177,7 @@ Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. -### Example +### Example ```python from __future__ import print_function import time @@ -193,7 +193,7 @@ configuration.access_token = 'YOUR_ACCESS_TOKEN' api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) tags = ['tags_example'] # list[str] | Tags to filter by -try: +try: # Finds Pets by tags api_response = api_instance.find_pets_by_tags(tags) pprint(api_response) @@ -229,7 +229,7 @@ Find pet by ID Returns a single pet -### Example +### Example ```python from __future__ import print_function import time @@ -247,7 +247,7 @@ configuration.api_key['api_key'] = 'YOUR_API_KEY' api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) pet_id = 789 # int | ID of pet to return -try: +try: # Find pet by ID api_response = api_instance.get_pet_by_id(pet_id) pprint(api_response) @@ -283,7 +283,7 @@ Update an existing pet -### Example +### Example ```python from __future__ import print_function import time @@ -299,7 +299,7 @@ configuration.access_token = 'YOUR_ACCESS_TOKEN' api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) body = petstore_api.Pet() # Pet | Pet object that needs to be added to the store -try: +try: # Update an existing pet api_instance.update_pet(body) except ApiException as e: @@ -334,7 +334,7 @@ Updates a pet in the store with form data -### Example +### Example ```python from __future__ import print_function import time @@ -352,7 +352,7 @@ 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) -try: +try: # Updates a pet in the store with form data api_instance.update_pet_with_form(pet_id, name=name, status=status) except ApiException as e: @@ -389,7 +389,7 @@ uploads an image -### Example +### Example ```python from __future__ import print_function import time @@ -407,7 +407,7 @@ 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) -try: +try: # uploads an image api_response = api_instance.upload_file(pet_id, additional_metadata=additional_metadata, file=file) pprint(api_response) diff --git a/samples/client/petstore/python/docs/StoreApi.md b/samples/client/petstore/python/docs/StoreApi.md index a75113975ef..6cbb6b45145 100644 --- a/samples/client/petstore/python/docs/StoreApi.md +++ b/samples/client/petstore/python/docs/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 ```python from __future__ import print_function import time @@ -29,7 +29,7 @@ from pprint import pprint api_instance = petstore_api.StoreApi() order_id = 'order_id_example' # str | ID of the order that needs to be deleted -try: +try: # Delete purchase order by ID api_instance.delete_order(order_id) except ApiException as e: @@ -64,7 +64,7 @@ Returns pet inventories by status Returns a map of status codes to quantities -### Example +### Example ```python from __future__ import print_function import time @@ -81,7 +81,7 @@ configuration.api_key['api_key'] = 'YOUR_API_KEY' # create an instance of the API class api_instance = petstore_api.StoreApi(petstore_api.ApiClient(configuration)) -try: +try: # Returns pet inventories by status api_response = api_instance.get_inventory() pprint(api_response) @@ -114,7 +114,7 @@ Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions -### Example +### Example ```python from __future__ import print_function import time @@ -126,7 +126,7 @@ from pprint import pprint api_instance = petstore_api.StoreApi() order_id = 789 # int | ID of pet that needs to be fetched -try: +try: # Find purchase order by ID api_response = api_instance.get_order_by_id(order_id) pprint(api_response) @@ -162,7 +162,7 @@ Place an order for a pet -### Example +### Example ```python from __future__ import print_function import time @@ -174,7 +174,7 @@ from pprint import pprint api_instance = petstore_api.StoreApi() body = petstore_api.Order() # Order | order placed for purchasing the pet -try: +try: # Place an order for a pet api_response = api_instance.place_order(body) pprint(api_response) diff --git a/samples/client/petstore/python/docs/UserApi.md b/samples/client/petstore/python/docs/UserApi.md index 5b73179dce3..969485595ae 100644 --- a/samples/client/petstore/python/docs/UserApi.md +++ b/samples/client/petstore/python/docs/UserApi.md @@ -21,7 +21,7 @@ Create user This can only be done by the logged in user. -### Example +### Example ```python from __future__ import print_function import time @@ -33,7 +33,7 @@ from pprint import pprint api_instance = petstore_api.UserApi() body = petstore_api.User() # User | Created user object -try: +try: # Create user api_instance.create_user(body) except ApiException as e: @@ -68,7 +68,7 @@ Creates list of users with given input array -### Example +### Example ```python from __future__ import print_function import time @@ -80,7 +80,7 @@ from pprint import pprint api_instance = petstore_api.UserApi() body = [petstore_api.User()] # list[User] | List of user object -try: +try: # Creates list of users with given input array api_instance.create_users_with_array_input(body) except ApiException as e: @@ -115,7 +115,7 @@ Creates list of users with given input array -### Example +### Example ```python from __future__ import print_function import time @@ -127,7 +127,7 @@ from pprint import pprint api_instance = petstore_api.UserApi() body = [petstore_api.User()] # list[User] | List of user object -try: +try: # Creates list of users with given input array api_instance.create_users_with_list_input(body) except ApiException as e: @@ -162,7 +162,7 @@ Delete user This can only be done by the logged in user. -### Example +### Example ```python from __future__ import print_function import time @@ -174,7 +174,7 @@ from pprint import pprint api_instance = petstore_api.UserApi() username = 'username_example' # str | The name that needs to be deleted -try: +try: # Delete user api_instance.delete_user(username) except ApiException as e: @@ -209,7 +209,7 @@ Get user by user name -### Example +### Example ```python from __future__ import print_function import time @@ -221,7 +221,7 @@ from pprint import pprint api_instance = petstore_api.UserApi() username = 'username_example' # str | The name that needs to be fetched. Use user1 for testing. -try: +try: # Get user by user name api_response = api_instance.get_user_by_name(username) pprint(api_response) @@ -257,7 +257,7 @@ Logs user into the system -### Example +### Example ```python from __future__ import print_function import time @@ -270,7 +270,7 @@ 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 -try: +try: # Logs user into the system api_response = api_instance.login_user(username, password) pprint(api_response) @@ -307,7 +307,7 @@ Logs out current logged in user session -### Example +### Example ```python from __future__ import print_function import time @@ -318,7 +318,7 @@ from pprint import pprint # create an instance of the API class api_instance = petstore_api.UserApi() -try: +try: # Logs out current logged in user session api_instance.logout_user() except ApiException as e: @@ -350,7 +350,7 @@ Updated user This can only be done by the logged in user. -### Example +### Example ```python from __future__ import print_function import time @@ -363,7 +363,7 @@ api_instance = petstore_api.UserApi() username = 'username_example' # str | name that need to be deleted body = petstore_api.User() # User | Updated user object -try: +try: # Updated user api_instance.update_user(username, body) except ApiException as e: diff --git a/samples/client/petstore/python/petstore_api/__init__.py b/samples/client/petstore/python/petstore_api/__init__.py index cad09e2691c..c368867dd11 100644 --- a/samples/client/petstore/python/petstore_api/__init__.py +++ b/samples/client/petstore/python/petstore_api/__init__.py @@ -1,9 +1,11 @@ # coding: utf-8 +# flake8: noqa + """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,53 +15,51 @@ 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_of_array_of_number_only import ArrayOfArrayOfNumberOnly -from .models.array_of_number_only import ArrayOfNumberOnly -from .models.array_test import ArrayTest -from .models.capitalization import Capitalization -from .models.category import Category -from .models.class_model import ClassModel -from .models.client import Client -from .models.enum_arrays import EnumArrays -from .models.enum_class import EnumClass -from .models.enum_test import EnumTest -from .models.format_test import FormatTest -from .models.has_only_read_only import HasOnlyReadOnly -from .models.list import List -from .models.map_test import MapTest -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.number_only import NumberOnly -from .models.order import Order -from .models.outer_boolean import OuterBoolean -from .models.outer_composite import OuterComposite -from .models.outer_enum import OuterEnum -from .models.outer_number import OuterNumber -from .models.outer_string import OuterString -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 -from .models.cat import Cat -from .models.dog import Dog - # import apis into sdk package -from .apis.another_fake_api import AnotherFakeApi -from .apis.fake_api import FakeApi -from .apis.fake_classname_tags_123_api import FakeClassnameTags123Api -from .apis.pet_api import PetApi -from .apis.store_api import StoreApi -from .apis.user_api import UserApi +from petstore_api.api.another_fake_api import AnotherFakeApi +from petstore_api.api.fake_api import FakeApi +from petstore_api.api.fake_classname_tags_123_api import FakeClassnameTags123Api +from petstore_api.api.pet_api import PetApi +from petstore_api.api.store_api import StoreApi +from petstore_api.api.user_api import UserApi # import ApiClient -from .api_client import ApiClient - -from .configuration import Configuration +from petstore_api.api_client import ApiClient +from petstore_api.configuration import Configuration +# import models into sdk package +from petstore_api.models.additional_properties_class import AdditionalPropertiesClass +from petstore_api.models.animal import Animal +from petstore_api.models.animal_farm import AnimalFarm +from petstore_api.models.api_response import ApiResponse +from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly +from petstore_api.models.array_of_number_only import ArrayOfNumberOnly +from petstore_api.models.array_test import ArrayTest +from petstore_api.models.capitalization import Capitalization +from petstore_api.models.category import Category +from petstore_api.models.class_model import ClassModel +from petstore_api.models.client import Client +from petstore_api.models.enum_arrays import EnumArrays +from petstore_api.models.enum_class import EnumClass +from petstore_api.models.enum_test import EnumTest +from petstore_api.models.format_test import FormatTest +from petstore_api.models.has_only_read_only import HasOnlyReadOnly +from petstore_api.models.list import List +from petstore_api.models.map_test import MapTest +from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass +from petstore_api.models.model_200_response import Model200Response +from petstore_api.models.model_return import ModelReturn +from petstore_api.models.name import Name +from petstore_api.models.number_only import NumberOnly +from petstore_api.models.order import Order +from petstore_api.models.outer_boolean import OuterBoolean +from petstore_api.models.outer_composite import OuterComposite +from petstore_api.models.outer_enum import OuterEnum +from petstore_api.models.outer_number import OuterNumber +from petstore_api.models.outer_string import OuterString +from petstore_api.models.pet import Pet +from petstore_api.models.read_only_first import ReadOnlyFirst +from petstore_api.models.special_model_name import SpecialModelName +from petstore_api.models.tag import Tag +from petstore_api.models.user import User +from petstore_api.models.cat import Cat +from petstore_api.models.dog import Dog diff --git a/samples/client/petstore/python/petstore_api/api/__init__.py b/samples/client/petstore/python/petstore_api/api/__init__.py new file mode 100644 index 00000000000..74496adb5a2 --- /dev/null +++ b/samples/client/petstore/python/petstore_api/api/__init__.py @@ -0,0 +1,11 @@ +from __future__ import absolute_import + +# flake8: noqa + +# import apis into api package +from petstore_api.api.another_fake_api import AnotherFakeApi +from petstore_api.api.fake_api import FakeApi +from petstore_api.api.fake_classname_tags_123_api import FakeClassnameTags123Api +from petstore_api.api.pet_api import PetApi +from petstore_api.api.store_api import StoreApi +from petstore_api.api.user_api import UserApi diff --git a/samples/client/petstore/python/petstore_api/apis/another_fake_api.py b/samples/client/petstore/python/petstore_api/api/another_fake_api.py similarity index 59% rename from samples/client/petstore/python/petstore_api/apis/another_fake_api.py rename to samples/client/petstore/python/petstore_api/api/another_fake_api.py index 8fb991ff3df..0096dad1a37 100644 --- a/samples/client/petstore/python/petstore_api/apis/another_fake_api.py +++ b/samples/client/petstore/python/petstore_api/api/another_fake_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class AnotherFakeApi(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,10 +33,10 @@ class AnotherFakeApi(object): api_client = ApiClient() self.api_client = api_client - def test_special_tags(self, body, **kwargs): - """ - To test special tags - To test special tags + def test_special_tags(self, body, **kwargs): # noqa: E501 + """To test special tags # noqa: E501 + + To test special tags # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_special_tags(body, async=True) @@ -52,15 +50,15 @@ class AnotherFakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_special_tags_with_http_info(body, **kwargs) + return self.test_special_tags_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.test_special_tags_with_http_info(body, **kwargs) + (data) = self.test_special_tags_with_http_info(body, **kwargs) # noqa: E501 return data - def test_special_tags_with_http_info(self, body, **kwargs): - """ - To test special tags - To test special tags + def test_special_tags_with_http_info(self, body, **kwargs): # noqa: E501 + """To test special tags # noqa: E501 + + To test special tags # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_special_tags_with_http_info(body, async=True) @@ -73,14 +71,14 @@ class AnotherFakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -89,9 +87,9 @@ class AnotherFakeApi(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 `test_special_tags`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `test_special_tags`") # noqa: E501 collection_formats = {} @@ -108,27 +106,28 @@ class AnotherFakeApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/another-fake/dummy', 'PATCH', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Client', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/another-fake/dummy', 'PATCH', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Client', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python-tornado/petstore_api/apis/fake_api.py b/samples/client/petstore/python/petstore_api/api/fake_api.py similarity index 57% rename from samples/client/petstore/python-tornado/petstore_api/apis/fake_api.py rename to samples/client/petstore/python/petstore_api/api/fake_api.py index 46fb22f7290..4c52ee51647 100644 --- a/samples/client/petstore/python-tornado/petstore_api/apis/fake_api.py +++ b/samples/client/petstore/python/petstore_api/api/fake_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class FakeApi(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,9 +33,10 @@ class FakeApi(object): api_client = ApiClient() self.api_client = api_client - def fake_outer_boolean_serialize(self, **kwargs): - """ - Test serialization of outer boolean types + def fake_outer_boolean_serialize(self, **kwargs): # noqa: E501 + """fake_outer_boolean_serialize # noqa: E501 + + Test serialization of outer boolean types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_boolean_serialize(async=True) @@ -51,14 +50,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.fake_outer_boolean_serialize_with_http_info(**kwargs) + return self.fake_outer_boolean_serialize_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.fake_outer_boolean_serialize_with_http_info(**kwargs) + (data) = self.fake_outer_boolean_serialize_with_http_info(**kwargs) # noqa: E501 return data - def fake_outer_boolean_serialize_with_http_info(self, **kwargs): - """ - Test serialization of outer boolean types + def fake_outer_boolean_serialize_with_http_info(self, **kwargs): # noqa: E501 + """fake_outer_boolean_serialize # noqa: E501 + + Test serialization of outer boolean types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_boolean_serialize_with_http_info(async=True) @@ -71,14 +71,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -87,7 +87,6 @@ class FakeApi(object): params[key] = val del params['kwargs'] - collection_formats = {} path_params = {} @@ -103,26 +102,28 @@ class FakeApi(object): if 'body' in params: body_params = params['body'] # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake/outer/boolean', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='OuterBoolean', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake/outer/boolean', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='OuterBoolean', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def fake_outer_composite_serialize(self, **kwargs): - """ - Test serialization of object with outer number type + def fake_outer_composite_serialize(self, **kwargs): # noqa: E501 + """fake_outer_composite_serialize # noqa: E501 + + Test serialization of object with outer number type # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_composite_serialize(async=True) @@ -136,14 +137,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.fake_outer_composite_serialize_with_http_info(**kwargs) + return self.fake_outer_composite_serialize_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.fake_outer_composite_serialize_with_http_info(**kwargs) + (data) = self.fake_outer_composite_serialize_with_http_info(**kwargs) # noqa: E501 return data - def fake_outer_composite_serialize_with_http_info(self, **kwargs): - """ - Test serialization of object with outer number type + def fake_outer_composite_serialize_with_http_info(self, **kwargs): # noqa: E501 + """fake_outer_composite_serialize # noqa: E501 + + Test serialization of object with outer number type # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_composite_serialize_with_http_info(async=True) @@ -156,14 +158,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -172,7 +174,6 @@ class FakeApi(object): params[key] = val del params['kwargs'] - collection_formats = {} path_params = {} @@ -188,26 +189,28 @@ class FakeApi(object): if 'body' in params: body_params = params['body'] # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake/outer/composite', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='OuterComposite', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake/outer/composite', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='OuterComposite', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def fake_outer_number_serialize(self, **kwargs): - """ - Test serialization of outer number types + def fake_outer_number_serialize(self, **kwargs): # noqa: E501 + """fake_outer_number_serialize # noqa: E501 + + Test serialization of outer number types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_number_serialize(async=True) @@ -221,14 +224,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.fake_outer_number_serialize_with_http_info(**kwargs) + return self.fake_outer_number_serialize_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.fake_outer_number_serialize_with_http_info(**kwargs) + (data) = self.fake_outer_number_serialize_with_http_info(**kwargs) # noqa: E501 return data - def fake_outer_number_serialize_with_http_info(self, **kwargs): - """ - Test serialization of outer number types + def fake_outer_number_serialize_with_http_info(self, **kwargs): # noqa: E501 + """fake_outer_number_serialize # noqa: E501 + + Test serialization of outer number types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_number_serialize_with_http_info(async=True) @@ -241,14 +245,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -257,7 +261,6 @@ class FakeApi(object): params[key] = val del params['kwargs'] - collection_formats = {} path_params = {} @@ -273,26 +276,28 @@ class FakeApi(object): if 'body' in params: body_params = params['body'] # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake/outer/number', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='OuterNumber', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake/outer/number', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='OuterNumber', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def fake_outer_string_serialize(self, **kwargs): - """ - Test serialization of outer string types + def fake_outer_string_serialize(self, **kwargs): # noqa: E501 + """fake_outer_string_serialize # noqa: E501 + + Test serialization of outer string types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_string_serialize(async=True) @@ -306,14 +311,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.fake_outer_string_serialize_with_http_info(**kwargs) + return self.fake_outer_string_serialize_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.fake_outer_string_serialize_with_http_info(**kwargs) + (data) = self.fake_outer_string_serialize_with_http_info(**kwargs) # noqa: E501 return data - def fake_outer_string_serialize_with_http_info(self, **kwargs): - """ - Test serialization of outer string types + def fake_outer_string_serialize_with_http_info(self, **kwargs): # noqa: E501 + """fake_outer_string_serialize # noqa: E501 + + Test serialization of outer string types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.fake_outer_string_serialize_with_http_info(async=True) @@ -326,14 +332,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -342,7 +348,6 @@ class FakeApi(object): params[key] = val del params['kwargs'] - collection_formats = {} path_params = {} @@ -358,27 +363,28 @@ class FakeApi(object): if 'body' in params: body_params = params['body'] # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake/outer/string', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='OuterString', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake/outer/string', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='OuterString', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def test_client_model(self, body, **kwargs): - """ - To test \"client\" model - To test \"client\" model + def test_client_model(self, body, **kwargs): # noqa: E501 + """To test \"client\" model # noqa: E501 + + To test \"client\" model # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_client_model(body, async=True) @@ -392,15 +398,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_client_model_with_http_info(body, **kwargs) + return self.test_client_model_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.test_client_model_with_http_info(body, **kwargs) + (data) = self.test_client_model_with_http_info(body, **kwargs) # noqa: E501 return data - def test_client_model_with_http_info(self, body, **kwargs): - """ - To test \"client\" model - To test \"client\" model + def test_client_model_with_http_info(self, body, **kwargs): # noqa: E501 + """To test \"client\" model # noqa: E501 + + To test \"client\" model # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_client_model_with_http_info(body, async=True) @@ -413,14 +419,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -429,9 +435,9 @@ class FakeApi(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 `test_client_model`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `test_client_model`") # noqa: E501 collection_formats = {} @@ -448,35 +454,36 @@ class FakeApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake', 'PATCH', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Client', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake', 'PATCH', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Client', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def test_endpoint_parameters(self, number, double, pattern_without_delimiter, byte, **kwargs): - """ - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + def test_endpoint_parameters(self, number, double, pattern_without_delimiter, byte, **kwargs): # noqa: E501 + """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 + + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, async=True) @@ -503,15 +510,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, **kwargs) + return self.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, **kwargs) # noqa: E501 else: - (data) = self.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, **kwargs) + (data) = self.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, **kwargs) # noqa: E501 return data - def test_endpoint_parameters_with_http_info(self, number, double, pattern_without_delimiter, byte, **kwargs): - """ - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + def test_endpoint_parameters_with_http_info(self, number, double, pattern_without_delimiter, byte, **kwargs): # noqa: E501 + """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 + + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, async=True) @@ -537,14 +544,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['number', 'double', 'pattern_without_delimiter', 'byte', 'integer', 'int32', 'int64', 'float', 'string', 'binary', 'date', 'date_time', 'password', 'param_callback'] + all_params = ['number', 'double', 'pattern_without_delimiter', 'byte', 'integer', 'int32', 'int64', 'float', 'string', 'binary', 'date', 'date_time', 'password', 'param_callback'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -553,45 +560,50 @@ 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`") + if ('number' not in params or + params['number'] is None): + raise ValueError("Missing the required parameter `number` when calling `test_endpoint_parameters`") # noqa: E501 # verify the required parameter 'double' is set - if ('double' not in params) or (params['double'] is None): - raise ValueError("Missing the required parameter `double` when calling `test_endpoint_parameters`") + if ('double' not in params or + params['double'] is None): + raise ValueError("Missing the required parameter `double` when calling `test_endpoint_parameters`") # noqa: E501 # verify the required parameter 'pattern_without_delimiter' is set - if ('pattern_without_delimiter' not in params) or (params['pattern_without_delimiter'] is None): - raise ValueError("Missing the required parameter `pattern_without_delimiter` when calling `test_endpoint_parameters`") + if ('pattern_without_delimiter' not in params or + params['pattern_without_delimiter'] is None): + raise ValueError("Missing the required parameter `pattern_without_delimiter` when calling `test_endpoint_parameters`") # noqa: E501 # verify the required parameter 'byte' is set - 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: - 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: - 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: - 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: - raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value greater than or equal to `67.8`") - if 'pattern_without_delimiter' in params and not re.search('^[A-Z].*', params['pattern_without_delimiter']): - raise ValueError("Invalid value for parameter `pattern_without_delimiter` when calling `test_endpoint_parameters`, must conform to the pattern `/^[A-Z].*/`") - if 'integer' in params and params['integer'] > 100: - raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100`") - if 'integer' in params and params['integer'] < 10: - raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value greater than or equal to `10`") - if 'int32' in params and params['int32'] > 200: - raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value less than or equal to `200`") - if 'int32' in params and params['int32'] < 20: - raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value greater than or equal to `20`") - 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 '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 '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: - raise ValueError("Invalid value for parameter `password` when calling `test_endpoint_parameters`, length must be greater than or equal to `10`") + if ('byte' not in params or + params['byte'] is None): + raise ValueError("Missing the required parameter `byte` when calling `test_endpoint_parameters`") # noqa: E501 + if 'number' in params and params['number'] > 543.2: # noqa: E501 + raise ValueError("Invalid value for parameter `number` when calling `test_endpoint_parameters`, must be a value less than or equal to `543.2`") # noqa: E501 + if 'number' in params and params['number'] < 32.1: # noqa: E501 + raise ValueError("Invalid value for parameter `number` when calling `test_endpoint_parameters`, must be a value greater than or equal to `32.1`") # noqa: E501 + if 'double' in params and params['double'] > 123.4: # noqa: E501 + raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value less than or equal to `123.4`") # noqa: E501 + if 'double' in params and params['double'] < 67.8: # noqa: E501 + raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value greater than or equal to `67.8`") # noqa: E501 + if 'pattern_without_delimiter' in params and not re.search('^[A-Z].*', params['pattern_without_delimiter']): # noqa: E501 + raise ValueError("Invalid value for parameter `pattern_without_delimiter` when calling `test_endpoint_parameters`, must conform to the pattern `/^[A-Z].*/`") # noqa: E501 + if 'integer' in params and params['integer'] > 100: # noqa: E501 + raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100`") # noqa: E501 + if 'integer' in params and params['integer'] < 10: # noqa: E501 + raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value greater than or equal to `10`") # noqa: E501 + if 'int32' in params and params['int32'] > 200: # noqa: E501 + raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value less than or equal to `200`") # noqa: E501 + if 'int32' in params and params['int32'] < 20: # noqa: E501 + raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value greater than or equal to `20`") # noqa: E501 + if 'float' in params and params['float'] > 987.6: # noqa: E501 + raise ValueError("Invalid value for parameter `float` when calling `test_endpoint_parameters`, must be a value less than or equal to `987.6`") # noqa: E501 + if 'string' in params and not re.search('[a-z]', params['string'], flags=re.IGNORECASE): # noqa: E501 + raise ValueError("Invalid value for parameter `string` when calling `test_endpoint_parameters`, must conform to the pattern `/[a-z]/i`") # noqa: E501 + 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`") # noqa: E501 + 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`") # noqa: E501 collection_formats = {} path_params = {} @@ -603,65 +615,66 @@ class FakeApi(object): form_params = [] local_var_files = {} if 'integer' in params: - form_params.append(('integer', params['integer'])) + form_params.append(('integer', params['integer'])) # noqa: E501 if 'int32' in params: - form_params.append(('int32', params['int32'])) + form_params.append(('int32', params['int32'])) # noqa: E501 if 'int64' in params: - form_params.append(('int64', params['int64'])) + form_params.append(('int64', params['int64'])) # noqa: E501 if 'number' in params: - form_params.append(('number', params['number'])) + form_params.append(('number', params['number'])) # noqa: E501 if 'float' in params: - form_params.append(('float', params['float'])) + form_params.append(('float', params['float'])) # noqa: E501 if 'double' in params: - form_params.append(('double', params['double'])) + form_params.append(('double', params['double'])) # noqa: E501 if 'string' in params: - form_params.append(('string', params['string'])) + form_params.append(('string', params['string'])) # noqa: E501 if 'pattern_without_delimiter' in params: - form_params.append(('pattern_without_delimiter', params['pattern_without_delimiter'])) + form_params.append(('pattern_without_delimiter', params['pattern_without_delimiter'])) # noqa: E501 if 'byte' in params: - form_params.append(('byte', params['byte'])) + form_params.append(('byte', params['byte'])) # noqa: E501 if 'binary' in params: - form_params.append(('binary', params['binary'])) + form_params.append(('binary', params['binary'])) # noqa: E501 if 'date' in params: - form_params.append(('date', params['date'])) + form_params.append(('date', params['date'])) # noqa: E501 if 'date_time' in params: - form_params.append(('dateTime', params['date_time'])) + form_params.append(('dateTime', params['date_time'])) # noqa: E501 if 'password' in params: - form_params.append(('password', params['password'])) + form_params.append(('password', params['password'])) # noqa: E501 if 'param_callback' in params: - form_params.append(('callback', params['param_callback'])) + form_params.append(('callback', params['param_callback'])) # noqa: E501 body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml; charset=utf-8', 'application/json; charset=utf-8']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml; charset=utf-8', 'application/json; charset=utf-8']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/xml; charset=utf-8', 'application/json; charset=utf-8']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/xml; charset=utf-8', 'application/json; charset=utf-8']) # noqa: E501 # Authentication setting - auth_settings = ['http_basic_test'] + auth_settings = ['http_basic_test'] # noqa: E501 - return self.api_client.call_api('/fake', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def test_enum_parameters(self, **kwargs): - """ - To test enum parameters - To test enum parameters + def test_enum_parameters(self, **kwargs): # noqa: E501 + """To test enum parameters # noqa: E501 + + To test enum parameters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_enum_parameters(async=True) @@ -682,15 +695,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_enum_parameters_with_http_info(**kwargs) + return self.test_enum_parameters_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.test_enum_parameters_with_http_info(**kwargs) + (data) = self.test_enum_parameters_with_http_info(**kwargs) # noqa: E501 return data - def test_enum_parameters_with_http_info(self, **kwargs): - """ - To test enum parameters - To test enum parameters + def test_enum_parameters_with_http_info(self, **kwargs): # noqa: E501 + """To test enum parameters # noqa: E501 + + To test enum parameters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_enum_parameters_with_http_info(async=True) @@ -710,14 +723,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['enum_form_string_array', 'enum_form_string', 'enum_header_string_array', 'enum_header_string', 'enum_query_string_array', 'enum_query_string', 'enum_query_integer', 'enum_query_double'] + all_params = ['enum_form_string_array', 'enum_form_string', 'enum_header_string_array', 'enum_header_string', 'enum_query_string_array', 'enum_query_string', 'enum_query_integer', 'enum_query_double'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -726,68 +739,163 @@ class FakeApi(object): params[key] = val del params['kwargs'] - collection_formats = {} path_params = {} query_params = [] if 'enum_query_string_array' in params: - query_params.append(('enum_query_string_array', params['enum_query_string_array'])) - collection_formats['enum_query_string_array'] = 'csv' + query_params.append(('enum_query_string_array', params['enum_query_string_array'])) # noqa: E501 + collection_formats['enum_query_string_array'] = 'csv' # noqa: E501 if 'enum_query_string' in params: - query_params.append(('enum_query_string', params['enum_query_string'])) + query_params.append(('enum_query_string', params['enum_query_string'])) # noqa: E501 if 'enum_query_integer' in params: - query_params.append(('enum_query_integer', params['enum_query_integer'])) + query_params.append(('enum_query_integer', params['enum_query_integer'])) # noqa: E501 header_params = {} if 'enum_header_string_array' in params: - header_params['enum_header_string_array'] = params['enum_header_string_array'] - collection_formats['enum_header_string_array'] = 'csv' + header_params['enum_header_string_array'] = params['enum_header_string_array'] # noqa: E501 + collection_formats['enum_header_string_array'] = 'csv' # noqa: E501 if 'enum_header_string' in params: - header_params['enum_header_string'] = params['enum_header_string'] + header_params['enum_header_string'] = params['enum_header_string'] # noqa: E501 form_params = [] local_var_files = {} if 'enum_form_string_array' in params: - form_params.append(('enum_form_string_array', params['enum_form_string_array'])) - collection_formats['enum_form_string_array'] = 'csv' + form_params.append(('enum_form_string_array', params['enum_form_string_array'])) # noqa: E501 + collection_formats['enum_form_string_array'] = 'csv' # noqa: E501 if 'enum_form_string' in params: - form_params.append(('enum_form_string', params['enum_form_string'])) + form_params.append(('enum_form_string', params['enum_form_string'])) # noqa: E501 if 'enum_query_double' in params: - form_params.append(('enum_query_double', params['enum_query_double'])) + form_params.append(('enum_query_double', params['enum_query_double'])) # noqa: E501 body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['*/*']) + header_params['Accept'] = self.api_client.select_header_accept( + ['*/*']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['*/*']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['*/*']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def test_json_form_data(self, param, param2, **kwargs): + def test_inline_additional_properties(self, param, **kwargs): # noqa: E501 + """test inline additionalProperties # noqa: E501 + + # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async=True + >>> thread = api.test_inline_additional_properties(param, async=True) + >>> result = thread.get() + + :param async bool + :param object param: request body (required) + :return: None + If the method is called asynchronously, + returns the request thread. """ - test json serialization of form data - + kwargs['_return_http_data_only'] = True + if kwargs.get('async'): + return self.test_inline_additional_properties_with_http_info(param, **kwargs) # noqa: E501 + else: + (data) = self.test_inline_additional_properties_with_http_info(param, **kwargs) # noqa: E501 + return data + + def test_inline_additional_properties_with_http_info(self, param, **kwargs): # noqa: E501 + """test inline additionalProperties # noqa: E501 + + # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async=True + >>> thread = api.test_inline_additional_properties_with_http_info(param, async=True) + >>> result = thread.get() + + :param async bool + :param object param: request body (required) + :return: None + If the method is called asynchronously, + returns the request thread. + """ + + all_params = ['param'] # noqa: E501 + all_params.append('async') + all_params.append('_return_http_data_only') + all_params.append('_preload_content') + all_params.append('_request_timeout') + + params = locals() + for key, val in six.iteritems(params['kwargs']): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method test_inline_additional_properties" % key + ) + params[key] = val + del params['kwargs'] + # verify the required parameter 'param' is set + if ('param' not in params or + params['param'] is None): + raise ValueError("Missing the required parameter `param` when calling `test_inline_additional_properties`") # noqa: E501 + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if 'param' in params: + body_params = params['param'] + # HTTP header `Content-Type` + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json']) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + '/fake/inline-additionalProperties', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) + + def test_json_form_data(self, param, param2, **kwargs): # noqa: E501 + """test json serialization of form data # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_json_form_data(param, param2, async=True) @@ -802,15 +910,15 @@ class FakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_json_form_data_with_http_info(param, param2, **kwargs) + return self.test_json_form_data_with_http_info(param, param2, **kwargs) # noqa: E501 else: - (data) = self.test_json_form_data_with_http_info(param, param2, **kwargs) + (data) = self.test_json_form_data_with_http_info(param, param2, **kwargs) # noqa: E501 return data - def test_json_form_data_with_http_info(self, param, param2, **kwargs): - """ - test json serialization of form data - + def test_json_form_data_with_http_info(self, param, param2, **kwargs): # noqa: E501 + """test json serialization of form data # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_json_form_data_with_http_info(param, param2, async=True) @@ -824,14 +932,14 @@ class FakeApi(object): returns the request thread. """ - all_params = ['param', 'param2'] + all_params = ['param', 'param2'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -840,12 +948,13 @@ class FakeApi(object): params[key] = val del params['kwargs'] # verify the required parameter 'param' is set - if ('param' not in params) or (params['param'] is None): - raise ValueError("Missing the required parameter `param` when calling `test_json_form_data`") + if ('param' not in params or + params['param'] is None): + raise ValueError("Missing the required parameter `param` when calling `test_json_form_data`") # noqa: E501 # verify the required parameter 'param2' is set - if ('param2' not in params) or (params['param2'] is None): - raise ValueError("Missing the required parameter `param2` when calling `test_json_form_data`") - + if ('param2' not in params or + params['param2'] is None): + raise ValueError("Missing the required parameter `param2` when calling `test_json_form_data`") # noqa: E501 collection_formats = {} @@ -858,29 +967,30 @@ class FakeApi(object): form_params = [] local_var_files = {} if 'param' in params: - form_params.append(('param', params['param'])) + form_params.append(('param', params['param'])) # noqa: E501 if 'param2' in params: - form_params.append(('param2', params['param2'])) + form_params.append(('param2', params['param2'])) # noqa: E501 body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/fake/jsonFormData', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake/jsonFormData', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python-tornado/petstore_api/apis/fake_classname_tags_123_api.py b/samples/client/petstore/python/petstore_api/api/fake_classname_tags_123_api.py similarity index 60% rename from samples/client/petstore/python-tornado/petstore_api/apis/fake_classname_tags_123_api.py rename to samples/client/petstore/python/petstore_api/api/fake_classname_tags_123_api.py index da75ad3cccd..6b6606dc096 100644 --- a/samples/client/petstore/python-tornado/petstore_api/apis/fake_classname_tags_123_api.py +++ b/samples/client/petstore/python/petstore_api/api/fake_classname_tags_123_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class FakeClassnameTags123Api(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,9 +33,9 @@ class FakeClassnameTags123Api(object): api_client = ApiClient() self.api_client = api_client - def test_classname(self, body, **kwargs): - """ - To test class name in snake case + def test_classname(self, body, **kwargs): # noqa: E501 + """To test class name in snake case # noqa: E501 + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_classname(body, async=True) @@ -51,14 +49,14 @@ class FakeClassnameTags123Api(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.test_classname_with_http_info(body, **kwargs) + return self.test_classname_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.test_classname_with_http_info(body, **kwargs) + (data) = self.test_classname_with_http_info(body, **kwargs) # noqa: E501 return data - def test_classname_with_http_info(self, body, **kwargs): - """ - To test class name in snake case + def test_classname_with_http_info(self, body, **kwargs): # noqa: E501 + """To test class name in snake case # noqa: E501 + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.test_classname_with_http_info(body, async=True) @@ -71,14 +69,14 @@ class FakeClassnameTags123Api(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -87,9 +85,9 @@ class FakeClassnameTags123Api(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 `test_classname`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `test_classname`") # noqa: E501 collection_formats = {} @@ -106,27 +104,28 @@ class FakeClassnameTags123Api(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json']) # noqa: E501 # Authentication setting - auth_settings = ['api_key_query'] + auth_settings = ['api_key_query'] # noqa: E501 - return self.api_client.call_api('/fake_classname_test', 'PATCH', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Client', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/fake_classname_test', 'PATCH', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Client', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/pet_api.py b/samples/client/petstore/python/petstore_api/api/pet_api.py similarity index 57% rename from samples/client/petstore/python/petstore_api/apis/pet_api.py rename to samples/client/petstore/python/petstore_api/api/pet_api.py index 51b6ce82540..ff1026f3fae 100644 --- a/samples/client/petstore/python/petstore_api/apis/pet_api.py +++ b/samples/client/petstore/python/petstore_api/api/pet_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class PetApi(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,10 +33,10 @@ class PetApi(object): api_client = ApiClient() self.api_client = api_client - def add_pet(self, body, **kwargs): - """ - Add a new pet to the store - + def add_pet(self, body, **kwargs): # noqa: E501 + """Add a new pet to the store # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.add_pet(body, async=True) @@ -52,15 +50,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.add_pet_with_http_info(body, **kwargs) + return self.add_pet_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.add_pet_with_http_info(body, **kwargs) + (data) = self.add_pet_with_http_info(body, **kwargs) # noqa: E501 return data - def add_pet_with_http_info(self, body, **kwargs): - """ - Add a new pet to the store - + def add_pet_with_http_info(self, body, **kwargs): # noqa: E501 + """Add a new pet to the store # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.add_pet_with_http_info(body, async=True) @@ -73,14 +71,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -89,9 +87,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `add_pet`") # noqa: E501 collection_formats = {} @@ -108,35 +106,36 @@ class PetApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json', 'application/xml']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json', 'application/xml']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def delete_pet(self, pet_id, **kwargs): - """ - Deletes a pet - + def delete_pet(self, pet_id, **kwargs): # noqa: E501 + """Deletes a pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_pet(pet_id, async=True) @@ -151,15 +150,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.delete_pet_with_http_info(pet_id, **kwargs) + return self.delete_pet_with_http_info(pet_id, **kwargs) # noqa: E501 else: - (data) = self.delete_pet_with_http_info(pet_id, **kwargs) + (data) = self.delete_pet_with_http_info(pet_id, **kwargs) # noqa: E501 return data - def delete_pet_with_http_info(self, pet_id, **kwargs): - """ - Deletes a pet - + def delete_pet_with_http_info(self, pet_id, **kwargs): # noqa: E501 + """Deletes a pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_pet_with_http_info(pet_id, async=True) @@ -173,14 +172,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['pet_id', 'api_key'] + all_params = ['pet_id', 'api_key'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -189,52 +188,53 @@ 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`") - + if ('pet_id' not in params or + params['pet_id'] is None): + raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") # noqa: E501 collection_formats = {} path_params = {} if 'pet_id' in params: - path_params['petId'] = params['pet_id'] + path_params['petId'] = params['pet_id'] # noqa: E501 query_params = [] header_params = {} if 'api_key' in params: - header_params['api_key'] = params['api_key'] + header_params['api_key'] = params['api_key'] # noqa: E501 form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet/{petId}', 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/{petId}', 'DELETE', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def find_pets_by_status(self, status, **kwargs): - """ - Finds Pets by status - Multiple status values can be provided with comma separated strings + def find_pets_by_status(self, status, **kwargs): # noqa: E501 + """Finds Pets by status # noqa: E501 + + Multiple status values can be provided with comma separated strings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.find_pets_by_status(status, async=True) @@ -248,15 +248,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.find_pets_by_status_with_http_info(status, **kwargs) + return self.find_pets_by_status_with_http_info(status, **kwargs) # noqa: E501 else: - (data) = self.find_pets_by_status_with_http_info(status, **kwargs) + (data) = self.find_pets_by_status_with_http_info(status, **kwargs) # noqa: E501 return data - def find_pets_by_status_with_http_info(self, status, **kwargs): - """ - Finds Pets by status - Multiple status values can be provided with comma separated strings + def find_pets_by_status_with_http_info(self, status, **kwargs): # noqa: E501 + """Finds Pets by status # noqa: E501 + + Multiple status values can be provided with comma separated strings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.find_pets_by_status_with_http_info(status, async=True) @@ -269,14 +269,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['status'] + all_params = ['status'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -285,9 +285,9 @@ 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`") - + if ('status' not in params or + params['status'] is None): + raise ValueError("Missing the required parameter `status` when calling `find_pets_by_status`") # noqa: E501 collection_formats = {} @@ -295,8 +295,8 @@ class PetApi(object): query_params = [] if 'status' in params: - query_params.append(('status', params['status'])) - collection_formats['status'] = 'csv' + query_params.append(('status', params['status'])) # noqa: E501 + collection_formats['status'] = 'csv' # noqa: E501 header_params = {} @@ -305,31 +305,32 @@ class PetApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet/findByStatus', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[Pet]', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/findByStatus', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='list[Pet]', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def find_pets_by_tags(self, tags, **kwargs): - """ - Finds Pets by tags - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + def find_pets_by_tags(self, tags, **kwargs): # noqa: E501 + """Finds Pets by tags # noqa: E501 + + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.find_pets_by_tags(tags, async=True) @@ -343,15 +344,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.find_pets_by_tags_with_http_info(tags, **kwargs) + return self.find_pets_by_tags_with_http_info(tags, **kwargs) # noqa: E501 else: - (data) = self.find_pets_by_tags_with_http_info(tags, **kwargs) + (data) = self.find_pets_by_tags_with_http_info(tags, **kwargs) # noqa: E501 return data - def find_pets_by_tags_with_http_info(self, tags, **kwargs): - """ - Finds Pets by tags - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + def find_pets_by_tags_with_http_info(self, tags, **kwargs): # noqa: E501 + """Finds Pets by tags # noqa: E501 + + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.find_pets_by_tags_with_http_info(tags, async=True) @@ -364,14 +365,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['tags'] + all_params = ['tags'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -380,9 +381,9 @@ 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`") - + if ('tags' not in params or + params['tags'] is None): + raise ValueError("Missing the required parameter `tags` when calling `find_pets_by_tags`") # noqa: E501 collection_formats = {} @@ -390,8 +391,8 @@ class PetApi(object): query_params = [] if 'tags' in params: - query_params.append(('tags', params['tags'])) - collection_formats['tags'] = 'csv' + query_params.append(('tags', params['tags'])) # noqa: E501 + collection_formats['tags'] = 'csv' # noqa: E501 header_params = {} @@ -400,31 +401,32 @@ class PetApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet/findByTags', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[Pet]', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/findByTags', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='list[Pet]', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def get_pet_by_id(self, pet_id, **kwargs): - """ - Find pet by ID - Returns a single pet + def get_pet_by_id(self, pet_id, **kwargs): # noqa: E501 + """Find pet by ID # noqa: E501 + + Returns a single pet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_pet_by_id(pet_id, async=True) @@ -438,15 +440,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.get_pet_by_id_with_http_info(pet_id, **kwargs) + return self.get_pet_by_id_with_http_info(pet_id, **kwargs) # noqa: E501 else: - (data) = self.get_pet_by_id_with_http_info(pet_id, **kwargs) + (data) = self.get_pet_by_id_with_http_info(pet_id, **kwargs) # noqa: E501 return data - def get_pet_by_id_with_http_info(self, pet_id, **kwargs): - """ - Find pet by ID - Returns a single pet + def get_pet_by_id_with_http_info(self, pet_id, **kwargs): # noqa: E501 + """Find pet by ID # noqa: E501 + + Returns a single pet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_pet_by_id_with_http_info(pet_id, async=True) @@ -459,14 +461,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['pet_id'] + all_params = ['pet_id'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -475,15 +477,15 @@ 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`") - + 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`") # noqa: E501 collection_formats = {} path_params = {} if 'pet_id' in params: - path_params['petId'] = params['pet_id'] + path_params['petId'] = params['pet_id'] # noqa: E501 query_params = [] @@ -494,31 +496,32 @@ class PetApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = ['api_key'] + auth_settings = ['api_key'] # noqa: E501 - return self.api_client.call_api('/pet/{petId}', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Pet', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/{petId}', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Pet', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def update_pet(self, body, **kwargs): - """ - Update an existing pet - + def update_pet(self, body, **kwargs): # noqa: E501 + """Update an existing pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_pet(body, async=True) @@ -532,15 +535,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.update_pet_with_http_info(body, **kwargs) + return self.update_pet_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.update_pet_with_http_info(body, **kwargs) + (data) = self.update_pet_with_http_info(body, **kwargs) # noqa: E501 return data - def update_pet_with_http_info(self, body, **kwargs): - """ - Update an existing pet - + def update_pet_with_http_info(self, body, **kwargs): # noqa: E501 + """Update an existing pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_pet_with_http_info(body, async=True) @@ -553,14 +556,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -569,9 +572,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `update_pet`") # noqa: E501 collection_formats = {} @@ -588,35 +591,36 @@ class PetApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json', 'application/xml']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/json', 'application/xml']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet', 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet', 'PUT', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def update_pet_with_form(self, pet_id, **kwargs): - """ - Updates a pet in the store with form data - + def update_pet_with_form(self, pet_id, **kwargs): # noqa: E501 + """Updates a pet in the store with form data # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_pet_with_form(pet_id, async=True) @@ -632,15 +636,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.update_pet_with_form_with_http_info(pet_id, **kwargs) + return self.update_pet_with_form_with_http_info(pet_id, **kwargs) # noqa: E501 else: - (data) = self.update_pet_with_form_with_http_info(pet_id, **kwargs) + (data) = self.update_pet_with_form_with_http_info(pet_id, **kwargs) # noqa: E501 return data - def update_pet_with_form_with_http_info(self, pet_id, **kwargs): - """ - Updates a pet in the store with form data - + def update_pet_with_form_with_http_info(self, pet_id, **kwargs): # noqa: E501 + """Updates a pet in the store with form data # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_pet_with_form_with_http_info(pet_id, async=True) @@ -655,14 +659,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['pet_id', 'name', 'status'] + all_params = ['pet_id', 'name', 'status'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -671,15 +675,15 @@ 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`") - + 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`") # noqa: E501 collection_formats = {} path_params = {} if 'pet_id' in params: - path_params['petId'] = params['pet_id'] + path_params['petId'] = params['pet_id'] # noqa: E501 query_params = [] @@ -688,41 +692,42 @@ class PetApi(object): form_params = [] local_var_files = {} if 'name' in params: - form_params.append(('name', params['name'])) + form_params.append(('name', params['name'])) # noqa: E501 if 'status' in params: - form_params.append(('status', params['status'])) + form_params.append(('status', params['status'])) # noqa: E501 body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/x-www-form-urlencoded']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['application/x-www-form-urlencoded']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet/{petId}', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/{petId}', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def upload_file(self, pet_id, **kwargs): - """ - uploads an image - + def upload_file(self, pet_id, **kwargs): # noqa: E501 + """uploads an image # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.upload_file(pet_id, async=True) @@ -738,15 +743,15 @@ class PetApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.upload_file_with_http_info(pet_id, **kwargs) + return self.upload_file_with_http_info(pet_id, **kwargs) # noqa: E501 else: - (data) = self.upload_file_with_http_info(pet_id, **kwargs) + (data) = self.upload_file_with_http_info(pet_id, **kwargs) # noqa: E501 return data - def upload_file_with_http_info(self, pet_id, **kwargs): - """ - uploads an image - + def upload_file_with_http_info(self, pet_id, **kwargs): # noqa: E501 + """uploads an image # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.upload_file_with_http_info(pet_id, async=True) @@ -761,14 +766,14 @@ class PetApi(object): returns the request thread. """ - all_params = ['pet_id', 'additional_metadata', 'file'] + all_params = ['pet_id', 'additional_metadata', 'file'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -777,15 +782,15 @@ 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`") - + if ('pet_id' not in params or + params['pet_id'] is None): + raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") # noqa: E501 collection_formats = {} path_params = {} if 'pet_id' in params: - path_params['petId'] = params['pet_id'] + path_params['petId'] = params['pet_id'] # noqa: E501 query_params = [] @@ -794,33 +799,34 @@ class PetApi(object): form_params = [] local_var_files = {} if 'additional_metadata' in params: - form_params.append(('additionalMetadata', params['additional_metadata'])) + form_params.append(('additionalMetadata', params['additional_metadata'])) # noqa: E501 if 'file' in params: - local_var_files['file'] = params['file'] + local_var_files['file'] = params['file'] # noqa: E501 body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['multipart/form-data']) + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['multipart/form-data']) # noqa: E501 # Authentication setting - auth_settings = ['petstore_auth'] + auth_settings = ['petstore_auth'] # noqa: E501 - return self.api_client.call_api('/pet/{petId}/uploadImage', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='ApiResponse', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/pet/{petId}/uploadImage', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='ApiResponse', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/store_api.py b/samples/client/petstore/python/petstore_api/api/store_api.py similarity index 57% rename from samples/client/petstore/python/petstore_api/apis/store_api.py rename to samples/client/petstore/python/petstore_api/api/store_api.py index e9d9599c363..ebb9a4eb27a 100644 --- a/samples/client/petstore/python/petstore_api/apis/store_api.py +++ b/samples/client/petstore/python/petstore_api/api/store_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class StoreApi(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,10 +33,10 @@ class StoreApi(object): api_client = ApiClient() self.api_client = api_client - def delete_order(self, order_id, **kwargs): - """ - Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + def delete_order(self, order_id, **kwargs): # noqa: E501 + """Delete purchase order by ID # noqa: E501 + + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_order(order_id, async=True) @@ -52,15 +50,15 @@ class StoreApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.delete_order_with_http_info(order_id, **kwargs) + return self.delete_order_with_http_info(order_id, **kwargs) # noqa: E501 else: - (data) = self.delete_order_with_http_info(order_id, **kwargs) + (data) = self.delete_order_with_http_info(order_id, **kwargs) # noqa: E501 return data - def delete_order_with_http_info(self, order_id, **kwargs): - """ - Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + def delete_order_with_http_info(self, order_id, **kwargs): # noqa: E501 + """Delete purchase order by ID # noqa: E501 + + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_order_with_http_info(order_id, async=True) @@ -73,14 +71,14 @@ class StoreApi(object): returns the request thread. """ - all_params = ['order_id'] + all_params = ['order_id'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -89,15 +87,15 @@ 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' not in params or + params['order_id'] is None): + raise ValueError("Missing the required parameter `order_id` when calling `delete_order`") # noqa: E501 collection_formats = {} path_params = {} if 'order_id' in params: - path_params['order_id'] = params['order_id'] + path_params['order_id'] = params['order_id'] # noqa: E501 query_params = [] @@ -108,31 +106,32 @@ class StoreApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/store/order/{order_id}', 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/store/order/{order_id}', 'DELETE', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def get_inventory(self, **kwargs): - """ - Returns pet inventories by status - Returns a map of status codes to quantities + def get_inventory(self, **kwargs): # noqa: E501 + """Returns pet inventories by status # noqa: E501 + + Returns a map of status codes to quantities # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_inventory(async=True) @@ -145,15 +144,15 @@ class StoreApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.get_inventory_with_http_info(**kwargs) + return self.get_inventory_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.get_inventory_with_http_info(**kwargs) + (data) = self.get_inventory_with_http_info(**kwargs) # noqa: E501 return data - def get_inventory_with_http_info(self, **kwargs): - """ - Returns pet inventories by status - Returns a map of status codes to quantities + def get_inventory_with_http_info(self, **kwargs): # noqa: E501 + """Returns pet inventories by status # noqa: E501 + + Returns a map of status codes to quantities # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_inventory_with_http_info(async=True) @@ -165,14 +164,14 @@ class StoreApi(object): returns the request thread. """ - all_params = [] + all_params = [] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -194,31 +193,32 @@ class StoreApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 # Authentication setting - auth_settings = ['api_key'] + auth_settings = ['api_key'] # noqa: E501 - return self.api_client.call_api('/store/inventory', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='dict(str, int)', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/store/inventory', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='dict(str, int)', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def get_order_by_id(self, order_id, **kwargs): - """ - Find purchase order by ID - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + def get_order_by_id(self, order_id, **kwargs): # noqa: E501 + """Find purchase order by ID # noqa: E501 + + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_order_by_id(order_id, async=True) @@ -232,15 +232,15 @@ class StoreApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.get_order_by_id_with_http_info(order_id, **kwargs) + return self.get_order_by_id_with_http_info(order_id, **kwargs) # noqa: E501 else: - (data) = self.get_order_by_id_with_http_info(order_id, **kwargs) + (data) = self.get_order_by_id_with_http_info(order_id, **kwargs) # noqa: E501 return data - def get_order_by_id_with_http_info(self, order_id, **kwargs): - """ - Find purchase order by ID - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + def get_order_by_id_with_http_info(self, order_id, **kwargs): # noqa: E501 + """Find purchase order by ID # noqa: E501 + + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_order_by_id_with_http_info(order_id, async=True) @@ -253,14 +253,14 @@ class StoreApi(object): returns the request thread. """ - all_params = ['order_id'] + all_params = ['order_id'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -269,19 +269,19 @@ 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: - raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5`") - if 'order_id' in params and params['order_id'] < 1: - raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value greater than or equal to `1`") + 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`") # noqa: E501 + if 'order_id' in params and params['order_id'] > 5: # noqa: E501 + raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5`") # noqa: E501 + if 'order_id' in params and params['order_id'] < 1: # noqa: E501 + raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value greater than or equal to `1`") # noqa: E501 collection_formats = {} path_params = {} if 'order_id' in params: - path_params['order_id'] = params['order_id'] + path_params['order_id'] = params['order_id'] # noqa: E501 query_params = [] @@ -292,31 +292,32 @@ class StoreApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/store/order/{order_id}', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Order', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/store/order/{order_id}', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Order', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def place_order(self, body, **kwargs): - """ - Place an order for a pet - + def place_order(self, body, **kwargs): # noqa: E501 + """Place an order for a pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.place_order(body, async=True) @@ -330,15 +331,15 @@ class StoreApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.place_order_with_http_info(body, **kwargs) + return self.place_order_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.place_order_with_http_info(body, **kwargs) + (data) = self.place_order_with_http_info(body, **kwargs) # noqa: E501 return data - def place_order_with_http_info(self, body, **kwargs): - """ - Place an order for a pet - + def place_order_with_http_info(self, body, **kwargs): # noqa: E501 + """Place an order for a pet # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.place_order_with_http_info(body, async=True) @@ -351,14 +352,14 @@ class StoreApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -367,9 +368,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `place_order`") # noqa: E501 collection_formats = {} @@ -386,23 +387,24 @@ class StoreApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/store/order', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Order', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/store/order', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Order', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python-asyncio/petstore_api/apis/user_api.py b/samples/client/petstore/python/petstore_api/api/user_api.py similarity index 57% rename from samples/client/petstore/python-asyncio/petstore_api/apis/user_api.py rename to samples/client/petstore/python/petstore_api/api/user_api.py index ffdad2dd60f..89949844aa1 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/apis/user_api.py +++ b/samples/client/petstore/python/petstore_api/api/user_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,19 +13,17 @@ from __future__ import absolute_import -import sys -import os -import re +import re # noqa: F401 # python 2 and python 3 compatibility library -from six import iteritems +import six -from ..api_client import ApiClient +from petstore_api.api_client import ApiClient class UserApi(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """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 """ @@ -35,10 +33,10 @@ class UserApi(object): api_client = ApiClient() self.api_client = api_client - def create_user(self, body, **kwargs): - """ - Create user - This can only be done by the logged in user. + def create_user(self, body, **kwargs): # noqa: E501 + """Create user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_user(body, async=True) @@ -52,15 +50,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.create_user_with_http_info(body, **kwargs) + return self.create_user_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.create_user_with_http_info(body, **kwargs) + (data) = self.create_user_with_http_info(body, **kwargs) # noqa: E501 return data - def create_user_with_http_info(self, body, **kwargs): - """ - Create user - This can only be done by the logged in user. + def create_user_with_http_info(self, body, **kwargs): # noqa: E501 + """Create user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_user_with_http_info(body, async=True) @@ -73,14 +71,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -89,9 +87,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `create_user`") # noqa: E501 collection_formats = {} @@ -108,31 +106,32 @@ class UserApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def create_users_with_array_input(self, body, **kwargs): - """ - Creates list of users with given input array - + def create_users_with_array_input(self, body, **kwargs): # noqa: E501 + """Creates list of users with given input array # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_users_with_array_input(body, async=True) @@ -146,15 +145,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.create_users_with_array_input_with_http_info(body, **kwargs) + return self.create_users_with_array_input_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.create_users_with_array_input_with_http_info(body, **kwargs) + (data) = self.create_users_with_array_input_with_http_info(body, **kwargs) # noqa: E501 return data - def create_users_with_array_input_with_http_info(self, body, **kwargs): - """ - Creates list of users with given input array - + def create_users_with_array_input_with_http_info(self, body, **kwargs): # noqa: E501 + """Creates list of users with given input array # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_users_with_array_input_with_http_info(body, async=True) @@ -167,14 +166,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -183,9 +182,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `create_users_with_array_input`") # noqa: E501 collection_formats = {} @@ -202,31 +201,32 @@ class UserApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/createWithArray', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/createWithArray', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def create_users_with_list_input(self, body, **kwargs): - """ - Creates list of users with given input array - + def create_users_with_list_input(self, body, **kwargs): # noqa: E501 + """Creates list of users with given input array # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_users_with_list_input(body, async=True) @@ -240,15 +240,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.create_users_with_list_input_with_http_info(body, **kwargs) + return self.create_users_with_list_input_with_http_info(body, **kwargs) # noqa: E501 else: - (data) = self.create_users_with_list_input_with_http_info(body, **kwargs) + (data) = self.create_users_with_list_input_with_http_info(body, **kwargs) # noqa: E501 return data - def create_users_with_list_input_with_http_info(self, body, **kwargs): - """ - Creates list of users with given input array - + def create_users_with_list_input_with_http_info(self, body, **kwargs): # noqa: E501 + """Creates list of users with given input array # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_users_with_list_input_with_http_info(body, async=True) @@ -261,14 +261,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['body'] + all_params = ['body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -277,9 +277,9 @@ 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`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `create_users_with_list_input`") # noqa: E501 collection_formats = {} @@ -296,31 +296,32 @@ class UserApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/createWithList', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/createWithList', 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def delete_user(self, username, **kwargs): - """ - Delete user - This can only be done by the logged in user. + def delete_user(self, username, **kwargs): # noqa: E501 + """Delete user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_user(username, async=True) @@ -334,15 +335,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.delete_user_with_http_info(username, **kwargs) + return self.delete_user_with_http_info(username, **kwargs) # noqa: E501 else: - (data) = self.delete_user_with_http_info(username, **kwargs) + (data) = self.delete_user_with_http_info(username, **kwargs) # noqa: E501 return data - def delete_user_with_http_info(self, username, **kwargs): - """ - Delete user - This can only be done by the logged in user. + def delete_user_with_http_info(self, username, **kwargs): # noqa: E501 + """Delete user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_user_with_http_info(username, async=True) @@ -355,14 +356,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['username'] + all_params = ['username'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -371,15 +372,15 @@ 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`") - + if ('username' not in params or + params['username'] is None): + raise ValueError("Missing the required parameter `username` when calling `delete_user`") # noqa: E501 collection_formats = {} path_params = {} if 'username' in params: - path_params['username'] = params['username'] + path_params['username'] = params['username'] # noqa: E501 query_params = [] @@ -390,31 +391,32 @@ class UserApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/{username}', 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/{username}', 'DELETE', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def get_user_by_name(self, username, **kwargs): - """ - Get user by user name - + def get_user_by_name(self, username, **kwargs): # noqa: E501 + """Get user by user name # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_user_by_name(username, async=True) @@ -428,15 +430,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.get_user_by_name_with_http_info(username, **kwargs) + return self.get_user_by_name_with_http_info(username, **kwargs) # noqa: E501 else: - (data) = self.get_user_by_name_with_http_info(username, **kwargs) + (data) = self.get_user_by_name_with_http_info(username, **kwargs) # noqa: E501 return data - def get_user_by_name_with_http_info(self, username, **kwargs): - """ - Get user by user name - + def get_user_by_name_with_http_info(self, username, **kwargs): # noqa: E501 + """Get user by user name # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_user_by_name_with_http_info(username, async=True) @@ -449,14 +451,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['username'] + all_params = ['username'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -465,15 +467,15 @@ 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`") - + if ('username' not in params or + params['username'] is None): + raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") # noqa: E501 collection_formats = {} path_params = {} if 'username' in params: - path_params['username'] = params['username'] + path_params['username'] = params['username'] # noqa: E501 query_params = [] @@ -484,31 +486,32 @@ class UserApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/{username}', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='User', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/{username}', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='User', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def login_user(self, username, password, **kwargs): - """ - Logs user into the system - + def login_user(self, username, password, **kwargs): # noqa: E501 + """Logs user into the system # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.login_user(username, password, async=True) @@ -523,15 +526,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.login_user_with_http_info(username, password, **kwargs) + return self.login_user_with_http_info(username, password, **kwargs) # noqa: E501 else: - (data) = self.login_user_with_http_info(username, password, **kwargs) + (data) = self.login_user_with_http_info(username, password, **kwargs) # noqa: E501 return data - def login_user_with_http_info(self, username, password, **kwargs): - """ - Logs user into the system - + def login_user_with_http_info(self, username, password, **kwargs): # noqa: E501 + """Logs user into the system # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.login_user_with_http_info(username, password, async=True) @@ -545,14 +548,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['username', 'password'] + all_params = ['username', 'password'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -561,12 +564,13 @@ 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`") + if ('username' not in params or + params['username'] is None): + raise ValueError("Missing the required parameter `username` when calling `login_user`") # noqa: E501 # verify the required parameter 'password' is set - if ('password' not in params) or (params['password'] is None): - raise ValueError("Missing the required parameter `password` when calling `login_user`") - + if ('password' not in params or + params['password'] is None): + raise ValueError("Missing the required parameter `password` when calling `login_user`") # noqa: E501 collection_formats = {} @@ -574,9 +578,9 @@ class UserApi(object): query_params = [] if 'username' in params: - query_params.append(('username', params['username'])) + query_params.append(('username', params['username'])) # noqa: E501 if 'password' in params: - query_params.append(('password', params['password'])) + query_params.append(('password', params['password'])) # noqa: E501 header_params = {} @@ -585,31 +589,32 @@ class UserApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/login', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='str', - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/login', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='str', # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def logout_user(self, **kwargs): - """ - Logs out current logged in user session - + def logout_user(self, **kwargs): # noqa: E501 + """Logs out current logged in user session # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.logout_user(async=True) @@ -622,15 +627,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.logout_user_with_http_info(**kwargs) + return self.logout_user_with_http_info(**kwargs) # noqa: E501 else: - (data) = self.logout_user_with_http_info(**kwargs) + (data) = self.logout_user_with_http_info(**kwargs) # noqa: E501 return data - def logout_user_with_http_info(self, **kwargs): - """ - Logs out current logged in user session - + def logout_user_with_http_info(self, **kwargs): # noqa: E501 + """Logs out current logged in user session # noqa: E501 + + # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.logout_user_with_http_info(async=True) @@ -642,14 +647,14 @@ class UserApi(object): returns the request thread. """ - all_params = [] + all_params = [] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -671,31 +676,32 @@ class UserApi(object): body_params = None # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/logout', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/logout', 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) - def update_user(self, username, body, **kwargs): - """ - Updated user - This can only be done by the logged in user. + def update_user(self, username, body, **kwargs): # noqa: E501 + """Updated user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_user(username, body, async=True) @@ -710,15 +716,15 @@ class UserApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): - return self.update_user_with_http_info(username, body, **kwargs) + return self.update_user_with_http_info(username, body, **kwargs) # noqa: E501 else: - (data) = self.update_user_with_http_info(username, body, **kwargs) + (data) = self.update_user_with_http_info(username, body, **kwargs) # noqa: E501 return data - def update_user_with_http_info(self, username, body, **kwargs): - """ - Updated user - This can only be done by the logged in user. + def update_user_with_http_info(self, username, body, **kwargs): # noqa: E501 + """Updated user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_user_with_http_info(username, body, async=True) @@ -732,14 +738,14 @@ class UserApi(object): returns the request thread. """ - all_params = ['username', 'body'] + all_params = ['username', 'body'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() - for key, val in iteritems(params['kwargs']): + for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" @@ -748,18 +754,19 @@ 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`") + if ('username' not in params or + params['username'] is None): + raise ValueError("Missing the required parameter `username` when calling `update_user`") # noqa: E501 # 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_user`") - + if ('body' not in params or + params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `update_user`") # noqa: E501 collection_formats = {} path_params = {} if 'username' in params: - path_params['username'] = params['username'] + path_params['username'] = params['username'] # noqa: E501 query_params = [] @@ -772,23 +779,24 @@ class UserApi(object): if 'body' in params: body_params = params['body'] # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/xml', 'application/json']) + header_params['Accept'] = self.api_client.select_header_accept( + ['application/xml', 'application/json']) # noqa: E501 # Authentication setting - auth_settings = [] + auth_settings = [] # noqa: E501 - return self.api_client.call_api('/user/{username}', 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async=params.get('async'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + return self.api_client.call_api( + '/user/{username}', 'PUT', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async=params.get('async'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py index ff29a063d8c..ec4e3cd5c42 100644 --- a/samples/client/petstore/python/petstore_api/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -2,7 +2,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,27 +11,25 @@ from __future__ import absolute_import -import os -import re +import datetime import json import mimetypes -import tempfile from multiprocessing.pool import ThreadPool - -from datetime import date, datetime +import os +import re +import tempfile # python 2 and python 3 compatibility library -from six import PY3, integer_types, iteritems, text_type +import six from six.moves.urllib.parse import quote -from . import models -from .configuration import Configuration -from .rest import ApiException, RESTClientObject +from petstore_api.configuration import Configuration +import petstore_api.models +from petstore_api import rest class ApiClient(object): - """ - Generic API client for Swagger client library builds. + """Generic API client for Swagger client library builds. Swagger generic API client. This client handles the client- server communication, and is invariant across implementations. Specifics of @@ -42,64 +40,63 @@ class ApiClient(object): Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. - :param host: The base path for the server to call. + :param configuration: .Configuration object for this client :param header_name: a header to pass when making calls to the API. - :param header_value: a header value to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API """ - PRIMITIVE_TYPES = (float, bool, bytes, text_type) + integer_types + PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types NATIVE_TYPES_MAPPING = { 'int': int, - 'long': int if PY3 else long, + 'long': int if six.PY3 else long, # noqa: F821 'float': float, 'str': str, 'bool': bool, - 'date': date, - 'datetime': datetime, + 'date': datetime.date, + 'datetime': datetime.datetime, 'object': object, } - def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None): + def __init__(self, configuration=None, header_name=None, header_value=None, + cookie=None): if configuration is None: configuration = Configuration() self.configuration = configuration self.pool = ThreadPool() - self.rest_client = RESTClientObject(configuration) + self.rest_client = rest.RESTClientObject(configuration) self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value self.cookie = cookie # Set default User-Agent. self.user_agent = 'Swagger-Codegen/1.0.0/python' - + def __del__(self): self.pool.close() self.pool.join() @property def user_agent(self): - """ - Gets user agent. - """ + """User agent for this API client""" return self.default_headers['User-Agent'] @user_agent.setter def user_agent(self, value): - """ - Sets user agent. - """ self.default_headers['User-Agent'] = value def set_default_header(self, header_name, header_value): self.default_headers[header_name] = header_value - def __call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_type=None, auth_settings=None, - _return_http_data_only=None, collection_formats=None, _preload_content=True, - _request_timeout=None): + def __call_api( + self, resource_path, method, path_params=None, + query_params=None, header_params=None, body=None, post_params=None, + files=None, response_type=None, auth_settings=None, + _return_http_data_only=None, collection_formats=None, + _preload_content=True, _request_timeout=None): config = self.configuration @@ -121,7 +118,9 @@ class ApiClient(object): for k, v in path_params: # specified safe chars, encode everything resource_path = resource_path.replace( - '{%s}' % k, quote(str(v), safe=config.safe_chars_for_path_param)) + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) # query parameters if query_params: @@ -147,12 +146,11 @@ class ApiClient(object): url = self.configuration.host + resource_path # perform request and return response - response_data = self.request(method, url, - query_params=query_params, - headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) + response_data = self.request( + method, url, query_params=query_params, headers=header_params, + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout) self.last_response = response_data @@ -167,11 +165,11 @@ class ApiClient(object): if _return_http_data_only: return (return_data) else: - return (return_data, response_data.status, response_data.getheaders()) + return (return_data, response_data.status, + response_data.getheaders()) def sanitize_for_serialization(self, obj): - """ - Builds a JSON POST object. + """Builds a JSON POST object. If obj is None, return None. If obj is str, int, long, float, bool, return directly. @@ -194,7 +192,7 @@ class ApiClient(object): elif isinstance(obj, tuple): return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj) - elif isinstance(obj, (datetime, date)): + elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() if isinstance(obj, dict): @@ -206,15 +204,14 @@ class ApiClient(object): # Convert attribute name to json key in # model definition for request. obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in iteritems(obj.swagger_types) + for attr, _ in six.iteritems(obj.swagger_types) if getattr(obj, attr) is not None} return {key: self.sanitize_for_serialization(val) - for key, val in iteritems(obj_dict)} + for key, val in six.iteritems(obj_dict)} def deserialize(self, response, response_type): - """ - Deserializes response into an object. + """Deserializes response into an object. :param response: RESTResponse object to be deserialized. :param response_type: class literal for @@ -236,8 +233,7 @@ class ApiClient(object): return self.__deserialize(data, response_type) def __deserialize(self, data, klass): - """ - Deserializes dict, list, str into an object. + """Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. @@ -256,21 +252,21 @@ class ApiClient(object): if klass.startswith('dict('): sub_kls = re.match('dict\(([^,]*), (.*)\)', klass).group(2) return {k: self.__deserialize(v, sub_kls) - for k, v in iteritems(data)} + for k, v in six.iteritems(data)} # convert str to class if klass in self.NATIVE_TYPES_MAPPING: klass = self.NATIVE_TYPES_MAPPING[klass] else: - klass = getattr(models, klass) + klass = getattr(petstore_api.models, klass) if klass in self.PRIMITIVE_TYPES: return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) - elif klass == date: + elif klass == datetime.date: return self.__deserialize_date(data) - elif klass == datetime: + elif klass == datetime.datetime: return self.__deserialize_datatime(data) else: return self.__deserialize_model(data, klass) @@ -279,10 +275,10 @@ class ApiClient(object): path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, async=None, - _return_http_data_only=None, collection_formats=None, _preload_content=True, - _request_timeout=None): - """ - Makes the HTTP request (synchronous) and return the deserialized data. + _return_http_data_only=None, collection_formats=None, + _preload_content=True, _request_timeout=None): + """Makes the HTTP request (synchronous) and returns deserialized data. + To make an async request, set the async parameter. :param resource_path: Path to method endpoint. @@ -299,13 +295,17 @@ class ApiClient(object): :param files dict: key -> filename, value -> filepath, for `multipart/form-data`. :param async bool: execute request asynchronously - :param _return_http_data_only: response data without head status code and headers + :param _return_http_data_only: response data without head status code + and headers :param collection_formats: dict of collection formats for path, query, header, and post parameters. - :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without - reading/decoding response data. Default is True. - :param _request_timeout: timeout setting for this request. If one number provided, it will be total request - timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: If async parameter is True, the request will be called asynchronously. @@ -318,22 +318,23 @@ class ApiClient(object): path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, - _return_http_data_only, collection_formats, _preload_content, _request_timeout) + _return_http_data_only, collection_formats, + _preload_content, _request_timeout) else: - thread = self.pool.apply_async(self.__call_api, (resource_path, method, - path_params, query_params, + thread = self.pool.apply_async(self.__call_api, (resource_path, + method, path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, _return_http_data_only, - collection_formats, _preload_content, _request_timeout)) + collection_formats, + _preload_content, _request_timeout)) return thread def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, _request_timeout=None): - """ - Makes the HTTP request using RESTClient. - """ + post_params=None, body=None, _preload_content=True, + _request_timeout=None): + """Makes the HTTP request using RESTClient.""" if method == "GET": return self.rest_client.GET(url, query_params=query_params, @@ -392,8 +393,7 @@ class ApiClient(object): ) def parameters_to_tuples(self, params, collection_formats): - """ - Get parameters as list of tuples, formatting collections. + """Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or list of two-tuples :param dict collection_formats: Parameter collection formats @@ -402,7 +402,7 @@ class ApiClient(object): new_params = [] if collection_formats is None: collection_formats = {} - for k, v in iteritems(params) if isinstance(params, dict) else params: + for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501 if k in collection_formats: collection_format = collection_formats[k] if collection_format == 'multi': @@ -423,8 +423,7 @@ class ApiClient(object): return new_params def prepare_post_parameters(self, post_params=None, files=None): - """ - Builds form parameters. + """Builds form parameters. :param post_params: Normal form parameters. :param files: File parameters. @@ -436,7 +435,7 @@ class ApiClient(object): params = post_params if files: - for k, v in iteritems(files): + for k, v in six.iteritems(files): if not v: continue file_names = v if type(v) is list else [v] @@ -444,15 +443,15 @@ class ApiClient(object): with open(n, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() - mimetype = mimetypes.\ - guess_type(filename)[0] or 'application/octet-stream' - params.append(tuple([k, tuple([filename, filedata, mimetype])])) + mimetype = (mimetypes.guess_type(filename)[0] or + 'application/octet-stream') + params.append( + tuple([k, tuple([filename, filedata, mimetype])])) return params def select_header_accept(self, accepts): - """ - Returns `Accept` based on an array of accepts provided. + """Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json). @@ -468,8 +467,7 @@ class ApiClient(object): return ', '.join(accepts) def select_header_content_type(self, content_types): - """ - Returns `Content-Type` based on an array of content_types provided. + """Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. :return: Content-Type (e.g. application/json). @@ -485,8 +483,7 @@ class ApiClient(object): return content_types[0] def update_params_for_auth(self, headers, querys, auth_settings): - """ - Updates header and query params based on authentication setting. + """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. :param querys: Query parameters tuple list to be updated. @@ -510,7 +507,8 @@ class ApiClient(object): ) def __deserialize_file(self, response): - """ + """Deserializes body to file + Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. @@ -523,19 +521,17 @@ class ApiClient(object): content_disposition = response.getheader("Content-Disposition") if content_disposition: - filename = re.\ - search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).\ - group(1) + filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition).group(1) path = os.path.join(os.path.dirname(path), filename) - with open(path, "w") as f: + with open(path, "wb") as f: f.write(response.data) return path def __deserialize_primitive(self, data, klass): - """ - Deserializes string to primitive type. + """Deserializes string to primitive type. :param data: str. :param klass: class literal. @@ -545,21 +541,19 @@ class ApiClient(object): try: return klass(data) except UnicodeEncodeError: - return unicode(data) + return six.u(data) except TypeError: return data def __deserialize_object(self, value): - """ - Return a original value. + """Return a original value. :return: object. """ return value def __deserialize_date(self, string): - """ - Deserializes string to date. + """Deserializes string to date. :param string: str. :return: date. @@ -570,14 +564,13 @@ class ApiClient(object): except ImportError: return string except ValueError: - raise ApiException( + raise rest.ApiException( status=0, - reason="Failed to parse `{0}` into a date object".format(string) + reason="Failed to parse `{0}` as date object".format(string) ) def __deserialize_datatime(self, string): - """ - Deserializes string to datetime. + """Deserializes string to datetime. The string should be in iso8601 datetime format. @@ -590,32 +583,32 @@ class ApiClient(object): except ImportError: return string except ValueError: - raise ApiException( + raise rest.ApiException( status=0, reason=( - "Failed to parse `{0}` into a datetime object" + "Failed to parse `{0}` as datetime object" .format(string) ) ) def __deserialize_model(self, data, klass): - """ - Deserializes list or dict to model. + """Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object. """ - if not klass.swagger_types and not hasattr(klass, 'get_real_child_model'): + if not klass.swagger_types and not hasattr(klass, + 'get_real_child_model'): return data kwargs = {} if klass.swagger_types is not None: - for attr, attr_type in iteritems(klass.swagger_types): - if data is not None \ - and klass.attribute_map[attr] in data \ - and isinstance(data, (list, dict)): + for attr, attr_type in six.iteritems(klass.swagger_types): + if (data is not None and + klass.attribute_map[attr] in data and + isinstance(data, (list, dict))): value = data[klass.attribute_map[attr]] kwargs[attr] = self.__deserialize(value, attr_type) diff --git a/samples/client/petstore/python/petstore_api/apis/__init__.py b/samples/client/petstore/python/petstore_api/apis/__init__.py deleted file mode 100644 index b4b975ca8e0..00000000000 --- a/samples/client/petstore/python/petstore_api/apis/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -from __future__ import absolute_import - -# import apis into api package -from .another_fake_api import AnotherFakeApi -from .fake_api import FakeApi -from .fake_classname_tags_123_api import FakeClassnameTags123Api -from .pet_api import PetApi -from .store_api import StoreApi -from .user_api import UserApi diff --git a/samples/client/petstore/python/petstore_api/apis/fake_classname_tags123_api.py b/samples/client/petstore/python/petstore_api/apis/fake_classname_tags123_api.py deleted file mode 100644 index 4fe6106e00f..00000000000 --- a/samples/client/petstore/python/petstore_api/apis/fake_classname_tags123_api.py +++ /dev/null @@ -1,141 +0,0 @@ -# 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 -""" - - -from __future__ import absolute_import - -import sys -import os -import re - -# python 2 and python 3 compatibility library -from six import iteritems - -from ..api_client import ApiClient - - -class FakeClassnameTags123Api(object): - """ - 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 - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient() - self.api_client = api_client - - def test_classname(self, body, **kwargs): - """ - To test class name in snake case - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.test_classname(body, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Client body: client model (required) - :return: Client - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('callback'): - return self.test_classname_with_http_info(body, **kwargs) - else: - (data) = self.test_classname_with_http_info(body, **kwargs) - return data - - def test_classname_with_http_info(self, body, **kwargs): - """ - To test class name in snake case - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.test_classname_with_http_info(body, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Client body: client model (required) - :return: Client - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body'] - all_params.append('callback') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method test_classname" % key - ) - 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 `test_classname`") - - - collection_formats = {} - - resource_path = '/fake_classname_test'.replace('{format}', 'json') - path_params = {} - - query_params = {} - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) - - # Authentication setting - auth_settings = [] - - return self.api_client.call_api(resource_path, 'PATCH', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Client', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/configuration.py b/samples/client/petstore/python/petstore_api/configuration.py index 29bf22034aa..f6273cf28cc 100644 --- a/samples/client/petstore/python/petstore_api/configuration.py +++ b/samples/client/petstore/python/petstore_api/configuration.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,24 +13,23 @@ from __future__ import absolute_import -import urllib3 - import copy import logging import multiprocessing import sys +import urllib3 -from six import iteritems -from six import with_metaclass +import six from six.moves import http_client as httplib + class TypeWithDefault(type): def __init__(cls, name, bases, dct): super(TypeWithDefault, cls).__init__(name, bases, dct) cls._default = None def __call__(cls): - if cls._default == None: + if cls._default is None: cls._default = type.__call__(cls) return copy.copy(cls._default) @@ -38,17 +37,15 @@ class TypeWithDefault(type): cls._default = copy.copy(default) -class Configuration(with_metaclass(TypeWithDefault, object)): - """ - NOTE: This class is auto generated by the swagger code generator program. +class Configuration(six.with_metaclass(TypeWithDefault, object)): + """NOTE: This class is auto generated by the swagger code generator program. + Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. """ def __init__(self): - """ - Constructor - """ + """Constructor""" # Default Base url self.host = "http://petstore.swagger.io:80/v2" # Temp file folder for downloading files @@ -83,7 +80,8 @@ class Configuration(with_metaclass(TypeWithDefault, object)): self.debug = False # SSL/TLS verification - # Set this to false to skip verifying SSL certificate when calling API from https server. + # Set this to false to skip verifying SSL certificate when calling API + # from https server. self.verify_ssl = True # Set this to customize the certificate file to verify the peer. self.ssl_ca_cert = None @@ -101,7 +99,6 @@ class Configuration(with_metaclass(TypeWithDefault, object)): # cpu_count * 5 is used as default value to increase performance. self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - # Proxy URL self.proxy = None # Safe chars for path_param @@ -109,18 +106,22 @@ class Configuration(with_metaclass(TypeWithDefault, object)): @property def logger_file(self): - """ - Gets the logger_file. + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str """ return self.__logger_file @logger_file.setter def logger_file(self, value): - """ - Sets the logger_file. + """The logger file. - If the logger_file is None, then add stream handler and remove file handler. - Otherwise, add file handler and remove stream handler. + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. :param value: The logger_file path. :type: str @@ -131,7 +132,7 @@ class Configuration(with_metaclass(TypeWithDefault, object)): # then add file handler and remove stream handler. self.logger_file_handler = logging.FileHandler(self.__logger_file) self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.addHandler(self.logger_file_handler) if self.logger_stream_handler: logger.removeHandler(self.logger_stream_handler) @@ -140,22 +141,23 @@ class Configuration(with_metaclass(TypeWithDefault, object)): # then add stream handler and remove file handler. self.logger_stream_handler = logging.StreamHandler() self.logger_stream_handler.setFormatter(self.logger_formatter) - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.addHandler(self.logger_stream_handler) if self.logger_file_handler: logger.removeHandler(self.logger_file_handler) @property def debug(self): - """ - Gets the debug status. + """Debug status + + :param value: The debug status, True or False. + :type: bool """ return self.__debug @debug.setter def debug(self, value): - """ - Sets the debug status. + """Debug status :param value: The debug status, True or False. :type: bool @@ -163,29 +165,32 @@ class Configuration(with_metaclass(TypeWithDefault, object)): self.__debug = value if self.__debug: # if debug status is True, turn on debug logging - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.setLevel(logging.DEBUG) # turn on httplib debug httplib.HTTPConnection.debuglevel = 1 else: # if debug status is False, turn off debug logging, # setting log level to default `logging.WARNING` - for _, logger in iteritems(self.logger): + for _, logger in six.iteritems(self.logger): logger.setLevel(logging.WARNING) # turn off httplib debug httplib.HTTPConnection.debuglevel = 0 @property def logger_format(self): - """ - Gets the logger_format. + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str """ return self.__logger_format @logger_format.setter def logger_format(self, value): - """ - Sets the logger_format. + """The logger format. The logger_formatter will be updated when sets logger_format. @@ -196,29 +201,28 @@ class Configuration(with_metaclass(TypeWithDefault, object)): self.logger_formatter = logging.Formatter(self.__logger_format) def get_api_key_with_prefix(self, identifier): - """ - Gets API key (with prefix if set). + """Gets API key (with prefix if set). :param identifier: The identifier of apiKey. :return: The token for api key authentication. """ - if self.api_key.get(identifier) and self.api_key_prefix.get(identifier): - return self.api_key_prefix[identifier] + ' ' + self.api_key[identifier] + if (self.api_key.get(identifier) and + self.api_key_prefix.get(identifier)): + return self.api_key_prefix[identifier] + ' ' + self.api_key[identifier] # noqa: E501 elif self.api_key.get(identifier): return self.api_key[identifier] def get_basic_auth_token(self): - """ - Gets HTTP basic authentication header (string). + """Gets HTTP basic authentication header (string). :return: The token for basic HTTP authentication. """ - return urllib3.util.make_headers(basic_auth=self.username + ':' + self.password)\ - .get('authorization') + return urllib3.util.make_headers( + basic_auth=self.username + ':' + self.password + ).get('authorization') def auth_settings(self): - """ - Gets Auth Settings dict for api client. + """Gets Auth Settings dict for api client. :return: The Auth Settings information dict. """ @@ -256,8 +260,7 @@ class Configuration(with_metaclass(TypeWithDefault, object)): } def to_debug_report(self): - """ - Gets the essential information for debugging. + """Gets the essential information for debugging. :return: The report for debugging. """ diff --git a/samples/client/petstore/python/petstore_api/models/__init__.py b/samples/client/petstore/python/petstore_api/models/__init__.py index 21b5d20fa3c..7b339102f9b 100644 --- a/samples/client/petstore/python/petstore_api/models/__init__.py +++ b/samples/client/petstore/python/petstore_api/models/__init__.py @@ -1,9 +1,10 @@ # coding: utf-8 +# flake8: noqa """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -14,39 +15,39 @@ 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_of_array_of_number_only import ArrayOfArrayOfNumberOnly -from .array_of_number_only import ArrayOfNumberOnly -from .array_test import ArrayTest -from .capitalization import Capitalization -from .category import Category -from .class_model import ClassModel -from .client import Client -from .enum_arrays import EnumArrays -from .enum_class import EnumClass -from .enum_test import EnumTest -from .format_test import FormatTest -from .has_only_read_only import HasOnlyReadOnly -from .list import List -from .map_test import MapTest -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 .number_only import NumberOnly -from .order import Order -from .outer_boolean import OuterBoolean -from .outer_composite import OuterComposite -from .outer_enum import OuterEnum -from .outer_number import OuterNumber -from .outer_string import OuterString -from .pet import Pet -from .read_only_first import ReadOnlyFirst -from .special_model_name import SpecialModelName -from .tag import Tag -from .user import User -from .cat import Cat -from .dog import Dog +from petstore_api.models.additional_properties_class import AdditionalPropertiesClass +from petstore_api.models.animal import Animal +from petstore_api.models.animal_farm import AnimalFarm +from petstore_api.models.api_response import ApiResponse +from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly +from petstore_api.models.array_of_number_only import ArrayOfNumberOnly +from petstore_api.models.array_test import ArrayTest +from petstore_api.models.capitalization import Capitalization +from petstore_api.models.category import Category +from petstore_api.models.class_model import ClassModel +from petstore_api.models.client import Client +from petstore_api.models.enum_arrays import EnumArrays +from petstore_api.models.enum_class import EnumClass +from petstore_api.models.enum_test import EnumTest +from petstore_api.models.format_test import FormatTest +from petstore_api.models.has_only_read_only import HasOnlyReadOnly +from petstore_api.models.list import List +from petstore_api.models.map_test import MapTest +from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass +from petstore_api.models.model_200_response import Model200Response +from petstore_api.models.model_return import ModelReturn +from petstore_api.models.name import Name +from petstore_api.models.number_only import NumberOnly +from petstore_api.models.order import Order +from petstore_api.models.outer_boolean import OuterBoolean +from petstore_api.models.outer_composite import OuterComposite +from petstore_api.models.outer_enum import OuterEnum +from petstore_api.models.outer_number import OuterNumber +from petstore_api.models.outer_string import OuterString +from petstore_api.models.pet import Pet +from petstore_api.models.read_only_first import ReadOnlyFirst +from petstore_api.models.special_model_name import SpecialModelName +from petstore_api.models.tag import Tag +from petstore_api.models.user import User +from petstore_api.models.cat import Cat +from petstore_api.models.dog import Dog 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 index a5329b411cd..03dbe975f1b 100644 --- a/samples/client/petstore/python/petstore_api/models/additional_properties_class.py +++ b/samples/client/petstore/python/petstore_api/models/additional_properties_class.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class AdditionalPropertiesClass(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class AdditionalPropertiesClass(object): 'map_of_map_property': 'map_of_map_property' } - def __init__(self, map_property=None, map_of_map_property=None): - """ - AdditionalPropertiesClass - a model defined in Swagger - """ + def __init__(self, map_property=None, map_of_map_property=None): # noqa: E501 + """AdditionalPropertiesClass - a model defined in Swagger""" # noqa: E501 self._map_property = None self._map_of_map_property = None self.discriminator = None if map_property is not None: - self.map_property = map_property + self.map_property = map_property if map_of_map_property is not None: - self.map_of_map_property = map_of_map_property + self.map_of_map_property = map_of_map_property @property def map_property(self): - """ - Gets the map_property of this AdditionalPropertiesClass. + """Gets the map_property of this AdditionalPropertiesClass. # noqa: E501 - :return: The map_property of this AdditionalPropertiesClass. + + :return: The map_property of this AdditionalPropertiesClass. # noqa: E501 :rtype: dict(str, str) """ return self._map_property @map_property.setter def map_property(self, map_property): - """ - Sets the map_property of this AdditionalPropertiesClass. + """Sets the map_property of this AdditionalPropertiesClass. - :param map_property: The map_property of this AdditionalPropertiesClass. + + :param map_property: The map_property of this AdditionalPropertiesClass. # noqa: E501 :type: dict(str, str) """ @@ -77,32 +75,30 @@ class AdditionalPropertiesClass(object): @property def map_of_map_property(self): - """ - Gets the map_of_map_property of this AdditionalPropertiesClass. + """Gets the map_of_map_property of this AdditionalPropertiesClass. # noqa: E501 - :return: The map_of_map_property of this AdditionalPropertiesClass. + + :return: The map_of_map_property of this AdditionalPropertiesClass. # noqa: E501 :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. + """Sets the map_of_map_property of this AdditionalPropertiesClass. - :param map_of_map_property: The map_of_map_property of this AdditionalPropertiesClass. + + :param map_of_map_property: The map_of_map_property of this AdditionalPropertiesClass. # noqa: E501 :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 - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class AdditionalPropertiesClass(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, AdditionalPropertiesClass): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/animal.py b/samples/client/petstore/python/petstore_api/models/animal.py index 13d8276713d..390ac83905e 100644 --- a/samples/client/petstore/python/petstore_api/models/animal.py +++ b/samples/client/petstore/python/petstore_api/models/animal.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Animal(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -41,14 +41,12 @@ class Animal(object): } discriminator_value_class_map = { - '': 'Dog', - '': 'Cat' + 'Dog': 'Dog', + 'Cat': 'Cat' } - def __init__(self, class_name=None, color='red'): - """ - Animal - a model defined in Swagger - """ + def __init__(self, class_name=None, color='red'): # noqa: E501 + """Animal - a model defined in Swagger""" # noqa: E501 self._class_name = None self._color = None @@ -56,69 +54,62 @@ class Animal(object): self.class_name = class_name if color is not None: - self.color = color + self.color = color @property def class_name(self): - """ - Gets the class_name of this Animal. + """Gets the class_name of this Animal. # noqa: E501 - :return: The class_name of this Animal. + + :return: The class_name of this Animal. # noqa: E501 :rtype: str """ return self._class_name @class_name.setter def class_name(self, class_name): - """ - Sets the class_name of this Animal. + """Sets the class_name of this Animal. - :param class_name: The class_name of this Animal. + + :param class_name: The class_name of this Animal. # noqa: E501 :type: str """ if class_name is None: - raise ValueError("Invalid value for `class_name`, must not be `None`") + raise ValueError("Invalid value for `class_name`, must not be `None`") # noqa: E501 self._class_name = class_name @property def color(self): - """ - Gets the color of this Animal. + """Gets the color of this Animal. # noqa: E501 - :return: The color of this Animal. + + :return: The color of this Animal. # noqa: E501 :rtype: str """ return self._color @color.setter def color(self, color): - """ - Sets the color of this Animal. + """Sets the color of this Animal. - :param color: The color of this Animal. + + :param color: The color of this Animal. # noqa: E501 :type: str """ self._color = color def get_real_child_model(self, data): - """ - Returns the real base class specified by the discriminator - """ + """Returns the real base class specified by the discriminator""" discriminator_value = data[self.discriminator].lower() - if self.discriminator_value_class_map.has_key(discriminator_value): - return self.discriminator_value_class_map[discriminator_value] - else: - return None + return self.discriminator_value_class_map.get(discriminator_value) def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -139,28 +130,20 @@ class Animal(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Animal): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """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 index fa47d63f881..6371257286e 100644 --- a/samples/client/petstore/python/petstore_api/models/animal_farm.py +++ b/samples/client/petstore/python/petstore_api/models/animal_farm.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.animal import Animal # noqa: F401,E501 class AnimalFarm(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -31,28 +33,20 @@ class AnimalFarm(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - AnimalFarm - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """AnimalFarm - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -73,28 +67,20 @@ class AnimalFarm(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, AnimalFarm): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/api_response.py b/samples/client/petstore/python/petstore_api/models/api_response.py index b2d784d8020..45c4831bb10 100644 --- a/samples/client/petstore/python/petstore_api/models/api_response.py +++ b/samples/client/petstore/python/petstore_api/models/api_response.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ApiResponse(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -42,10 +42,8 @@ class ApiResponse(object): 'message': 'message' } - def __init__(self, code=None, type=None, message=None): - """ - ApiResponse - a model defined in Swagger - """ + def __init__(self, code=None, type=None, message=None): # noqa: E501 + """ApiResponse - a model defined in Swagger""" # noqa: E501 self._code = None self._type = None @@ -53,28 +51,28 @@ class ApiResponse(object): self.discriminator = None if code is not None: - self.code = code + self.code = code if type is not None: - self.type = type + self.type = type if message is not None: - self.message = message + self.message = message @property def code(self): - """ - Gets the code of this ApiResponse. + """Gets the code of this ApiResponse. # noqa: E501 - :return: The code of this ApiResponse. + + :return: The code of this ApiResponse. # noqa: E501 :rtype: int """ return self._code @code.setter def code(self, code): - """ - Sets the code of this ApiResponse. + """Sets the code of this ApiResponse. - :param code: The code of this ApiResponse. + + :param code: The code of this ApiResponse. # noqa: E501 :type: int """ @@ -82,20 +80,20 @@ class ApiResponse(object): @property def type(self): - """ - Gets the type of this ApiResponse. + """Gets the type of this ApiResponse. # noqa: E501 - :return: The type of this ApiResponse. + + :return: The type of this ApiResponse. # noqa: E501 :rtype: str """ return self._type @type.setter def type(self, type): - """ - Sets the type of this ApiResponse. + """Sets the type of this ApiResponse. - :param type: The type of this ApiResponse. + + :param type: The type of this ApiResponse. # noqa: E501 :type: str """ @@ -103,32 +101,30 @@ class ApiResponse(object): @property def message(self): - """ - Gets the message of this ApiResponse. + """Gets the message of this ApiResponse. # noqa: E501 - :return: The message of this ApiResponse. + + :return: The message of this ApiResponse. # noqa: E501 :rtype: str """ return self._message @message.setter def message(self, message): - """ - Sets the message of this ApiResponse. + """Sets the message of this ApiResponse. - :param message: The message of this ApiResponse. + + :param message: The message of this ApiResponse. # noqa: E501 :type: str """ self._message = message def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -149,28 +145,20 @@ class ApiResponse(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ApiResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py b/samples/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py index 0792f5a8a23..c6b363f19d8 100644 --- a/samples/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ArrayOfArrayOfNumberOnly(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class ArrayOfArrayOfNumberOnly(object): 'array_array_number': 'ArrayArrayNumber' } - def __init__(self, array_array_number=None): - """ - ArrayOfArrayOfNumberOnly - a model defined in Swagger - """ + def __init__(self, array_array_number=None): # noqa: E501 + """ArrayOfArrayOfNumberOnly - a model defined in Swagger""" # noqa: E501 self._array_array_number = None self.discriminator = None if array_array_number is not None: - self.array_array_number = array_array_number + self.array_array_number = array_array_number @property def array_array_number(self): - """ - Gets the array_array_number of this ArrayOfArrayOfNumberOnly. + """Gets the array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501 - :return: The array_array_number of this ArrayOfArrayOfNumberOnly. + + :return: The array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501 :rtype: list[list[float]] """ return self._array_array_number @array_array_number.setter def array_array_number(self, array_array_number): - """ - Sets the array_array_number of this ArrayOfArrayOfNumberOnly. + """Sets the array_array_number of this ArrayOfArrayOfNumberOnly. - :param array_array_number: The array_array_number of this ArrayOfArrayOfNumberOnly. + + :param array_array_number: The array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501 :type: list[list[float]] """ self._array_array_number = array_array_number def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class ArrayOfArrayOfNumberOnly(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ArrayOfArrayOfNumberOnly): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/array_of_number_only.py b/samples/client/petstore/python/petstore_api/models/array_of_number_only.py index 9d00e1b37a2..240362696cd 100644 --- a/samples/client/petstore/python/petstore_api/models/array_of_number_only.py +++ b/samples/client/petstore/python/petstore_api/models/array_of_number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ArrayOfNumberOnly(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class ArrayOfNumberOnly(object): 'array_number': 'ArrayNumber' } - def __init__(self, array_number=None): - """ - ArrayOfNumberOnly - a model defined in Swagger - """ + def __init__(self, array_number=None): # noqa: E501 + """ArrayOfNumberOnly - a model defined in Swagger""" # noqa: E501 self._array_number = None self.discriminator = None if array_number is not None: - self.array_number = array_number + self.array_number = array_number @property def array_number(self): - """ - Gets the array_number of this ArrayOfNumberOnly. + """Gets the array_number of this ArrayOfNumberOnly. # noqa: E501 - :return: The array_number of this ArrayOfNumberOnly. + + :return: The array_number of this ArrayOfNumberOnly. # noqa: E501 :rtype: list[float] """ return self._array_number @array_number.setter def array_number(self, array_number): - """ - Sets the array_number of this ArrayOfNumberOnly. + """Sets the array_number of this ArrayOfNumberOnly. - :param array_number: The array_number of this ArrayOfNumberOnly. + + :param array_number: The array_number of this ArrayOfNumberOnly. # noqa: E501 :type: list[float] """ self._array_number = array_number def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class ArrayOfNumberOnly(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ArrayOfNumberOnly): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """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 index ac3079087c8..c5cd6bfe159 100644 --- a/samples/client/petstore/python/petstore_api/models/array_test.py +++ b/samples/client/petstore/python/petstore_api/models/array_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.read_only_first import ReadOnlyFirst # noqa: F401,E501 class ArrayTest(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -42,10 +44,8 @@ class ArrayTest(object): 'array_array_of_model': 'array_array_of_model' } - def __init__(self, array_of_string=None, array_array_of_integer=None, array_array_of_model=None): - """ - ArrayTest - a model defined in Swagger - """ + def __init__(self, array_of_string=None, array_array_of_integer=None, array_array_of_model=None): # noqa: E501 + """ArrayTest - a model defined in Swagger""" # noqa: E501 self._array_of_string = None self._array_array_of_integer = None @@ -53,28 +53,28 @@ class ArrayTest(object): self.discriminator = None if array_of_string is not None: - self.array_of_string = array_of_string + self.array_of_string = array_of_string if array_array_of_integer is not None: - self.array_array_of_integer = array_array_of_integer + self.array_array_of_integer = array_array_of_integer if array_array_of_model is not None: - self.array_array_of_model = array_array_of_model + self.array_array_of_model = array_array_of_model @property def array_of_string(self): - """ - Gets the array_of_string of this ArrayTest. + """Gets the array_of_string of this ArrayTest. # noqa: E501 - :return: The array_of_string of this ArrayTest. + + :return: The array_of_string of this ArrayTest. # noqa: E501 :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. + """Sets the array_of_string of this ArrayTest. - :param array_of_string: The array_of_string of this ArrayTest. + + :param array_of_string: The array_of_string of this ArrayTest. # noqa: E501 :type: list[str] """ @@ -82,20 +82,20 @@ class ArrayTest(object): @property def array_array_of_integer(self): - """ - Gets the array_array_of_integer of this ArrayTest. + """Gets the array_array_of_integer of this ArrayTest. # noqa: E501 - :return: The array_array_of_integer of this ArrayTest. + + :return: The array_array_of_integer of this ArrayTest. # noqa: E501 :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. + """Sets the array_array_of_integer of this ArrayTest. - :param array_array_of_integer: The array_array_of_integer of this ArrayTest. + + :param array_array_of_integer: The array_array_of_integer of this ArrayTest. # noqa: E501 :type: list[list[int]] """ @@ -103,32 +103,30 @@ class ArrayTest(object): @property def array_array_of_model(self): - """ - Gets the array_array_of_model of this ArrayTest. + """Gets the array_array_of_model of this ArrayTest. # noqa: E501 - :return: The array_array_of_model of this ArrayTest. + + :return: The array_array_of_model of this ArrayTest. # noqa: E501 :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. + """Sets the array_array_of_model of this ArrayTest. - :param array_array_of_model: The array_array_of_model of this ArrayTest. + + :param array_array_of_model: The array_array_of_model of this ArrayTest. # noqa: E501 :type: list[list[ReadOnlyFirst]] """ self._array_array_of_model = array_array_of_model def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -149,28 +147,20 @@ class ArrayTest(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ArrayTest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/capitalization.py b/samples/client/petstore/python/petstore_api/models/capitalization.py index c9be6ed4d15..309642bdeff 100644 --- a/samples/client/petstore/python/petstore_api/models/capitalization.py +++ b/samples/client/petstore/python/petstore_api/models/capitalization.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Capitalization(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -48,10 +48,8 @@ class Capitalization(object): 'att_name': 'ATT_NAME' } - def __init__(self, small_camel=None, capital_camel=None, small_snake=None, capital_snake=None, sca_eth_flow_points=None, att_name=None): - """ - Capitalization - a model defined in Swagger - """ + def __init__(self, small_camel=None, capital_camel=None, small_snake=None, capital_snake=None, sca_eth_flow_points=None, att_name=None): # noqa: E501 + """Capitalization - a model defined in Swagger""" # noqa: E501 self._small_camel = None self._capital_camel = None @@ -62,34 +60,34 @@ class Capitalization(object): self.discriminator = None if small_camel is not None: - self.small_camel = small_camel + self.small_camel = small_camel if capital_camel is not None: - self.capital_camel = capital_camel + self.capital_camel = capital_camel if small_snake is not None: - self.small_snake = small_snake + self.small_snake = small_snake if capital_snake is not None: - self.capital_snake = capital_snake + self.capital_snake = capital_snake if sca_eth_flow_points is not None: - self.sca_eth_flow_points = sca_eth_flow_points + self.sca_eth_flow_points = sca_eth_flow_points if att_name is not None: - self.att_name = att_name + self.att_name = att_name @property def small_camel(self): - """ - Gets the small_camel of this Capitalization. + """Gets the small_camel of this Capitalization. # noqa: E501 - :return: The small_camel of this Capitalization. + + :return: The small_camel of this Capitalization. # noqa: E501 :rtype: str """ return self._small_camel @small_camel.setter def small_camel(self, small_camel): - """ - Sets the small_camel of this Capitalization. + """Sets the small_camel of this Capitalization. - :param small_camel: The small_camel of this Capitalization. + + :param small_camel: The small_camel of this Capitalization. # noqa: E501 :type: str """ @@ -97,20 +95,20 @@ class Capitalization(object): @property def capital_camel(self): - """ - Gets the capital_camel of this Capitalization. + """Gets the capital_camel of this Capitalization. # noqa: E501 - :return: The capital_camel of this Capitalization. + + :return: The capital_camel of this Capitalization. # noqa: E501 :rtype: str """ return self._capital_camel @capital_camel.setter def capital_camel(self, capital_camel): - """ - Sets the capital_camel of this Capitalization. + """Sets the capital_camel of this Capitalization. - :param capital_camel: The capital_camel of this Capitalization. + + :param capital_camel: The capital_camel of this Capitalization. # noqa: E501 :type: str """ @@ -118,20 +116,20 @@ class Capitalization(object): @property def small_snake(self): - """ - Gets the small_snake of this Capitalization. + """Gets the small_snake of this Capitalization. # noqa: E501 - :return: The small_snake of this Capitalization. + + :return: The small_snake of this Capitalization. # noqa: E501 :rtype: str """ return self._small_snake @small_snake.setter def small_snake(self, small_snake): - """ - Sets the small_snake of this Capitalization. + """Sets the small_snake of this Capitalization. - :param small_snake: The small_snake of this Capitalization. + + :param small_snake: The small_snake of this Capitalization. # noqa: E501 :type: str """ @@ -139,20 +137,20 @@ class Capitalization(object): @property def capital_snake(self): - """ - Gets the capital_snake of this Capitalization. + """Gets the capital_snake of this Capitalization. # noqa: E501 - :return: The capital_snake of this Capitalization. + + :return: The capital_snake of this Capitalization. # noqa: E501 :rtype: str """ return self._capital_snake @capital_snake.setter def capital_snake(self, capital_snake): - """ - Sets the capital_snake of this Capitalization. + """Sets the capital_snake of this Capitalization. - :param capital_snake: The capital_snake of this Capitalization. + + :param capital_snake: The capital_snake of this Capitalization. # noqa: E501 :type: str """ @@ -160,20 +158,20 @@ class Capitalization(object): @property def sca_eth_flow_points(self): - """ - Gets the sca_eth_flow_points of this Capitalization. + """Gets the sca_eth_flow_points of this Capitalization. # noqa: E501 - :return: The sca_eth_flow_points of this Capitalization. + + :return: The sca_eth_flow_points of this Capitalization. # noqa: E501 :rtype: str """ return self._sca_eth_flow_points @sca_eth_flow_points.setter def sca_eth_flow_points(self, sca_eth_flow_points): - """ - Sets the sca_eth_flow_points of this Capitalization. + """Sets the sca_eth_flow_points of this Capitalization. - :param sca_eth_flow_points: The sca_eth_flow_points of this Capitalization. + + :param sca_eth_flow_points: The sca_eth_flow_points of this Capitalization. # noqa: E501 :type: str """ @@ -181,34 +179,32 @@ class Capitalization(object): @property def att_name(self): - """ - Gets the att_name of this Capitalization. - Name of the pet + """Gets the att_name of this Capitalization. # noqa: E501 - :return: The att_name of this Capitalization. + Name of the pet # noqa: E501 + + :return: The att_name of this Capitalization. # noqa: E501 :rtype: str """ return self._att_name @att_name.setter def att_name(self, att_name): - """ - Sets the att_name of this Capitalization. - Name of the pet + """Sets the att_name of this Capitalization. - :param att_name: The att_name of this Capitalization. + Name of the pet # noqa: E501 + + :param att_name: The att_name of this Capitalization. # noqa: E501 :type: str """ self._att_name = att_name def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -229,28 +225,20 @@ class Capitalization(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Capitalization): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/cat.py b/samples/client/petstore/python/petstore_api/models/cat.py index 76dfdc0e5b1..526d3e2aaf5 100644 --- a/samples/client/petstore/python/petstore_api/models/cat.py +++ b/samples/client/petstore/python/petstore_api/models/cat.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.animal import Animal # noqa: F401,E501 class Cat(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +40,41 @@ class Cat(object): 'declawed': 'declawed' } - def __init__(self, declawed=None): - """ - Cat - a model defined in Swagger - """ + def __init__(self, declawed=None): # noqa: E501 + """Cat - a model defined in Swagger""" # noqa: E501 self._declawed = None self.discriminator = None if declawed is not None: - self.declawed = declawed + self.declawed = declawed @property def declawed(self): - """ - Gets the declawed of this Cat. + """Gets the declawed of this Cat. # noqa: E501 - :return: The declawed of this Cat. + + :return: The declawed of this Cat. # noqa: E501 :rtype: bool """ return self._declawed @declawed.setter def declawed(self, declawed): - """ - Sets the declawed of this Cat. + """Sets the declawed of this Cat. - :param declawed: The declawed of this Cat. + + :param declawed: The declawed of this Cat. # noqa: E501 :type: bool """ self._declawed = declawed def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +95,20 @@ class Cat(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Cat): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/category.py b/samples/client/petstore/python/petstore_api/models/category.py index 859283a3f77..02d393af888 100644 --- a/samples/client/petstore/python/petstore_api/models/category.py +++ b/samples/client/petstore/python/petstore_api/models/category.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Category(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class Category(object): 'name': 'name' } - def __init__(self, id=None, name=None): - """ - Category - a model defined in Swagger - """ + def __init__(self, id=None, name=None): # noqa: E501 + """Category - a model defined in Swagger""" # noqa: E501 self._id = None self._name = None self.discriminator = None if id is not None: - self.id = id + self.id = id if name is not None: - self.name = name + self.name = name @property def id(self): - """ - Gets the id of this Category. + """Gets the id of this Category. # noqa: E501 - :return: The id of this Category. + + :return: The id of this Category. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): - """ - Sets the id of this Category. + """Sets the id of this Category. - :param id: The id of this Category. + + :param id: The id of this Category. # noqa: E501 :type: int """ @@ -77,32 +75,30 @@ class Category(object): @property def name(self): - """ - Gets the name of this Category. + """Gets the name of this Category. # noqa: E501 - :return: The name of this Category. + + :return: The name of this Category. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): - """ - Sets the name of this Category. + """Sets the name of this Category. - :param name: The name of this Category. + + :param name: The name of this Category. # noqa: E501 :type: str """ self._name = name def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class Category(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Category): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/class_model.py b/samples/client/petstore/python/petstore_api/models/class_model.py index 7b39d38abe9..4bcb19b8dc2 100644 --- a/samples/client/petstore/python/petstore_api/models/class_model.py +++ b/samples/client/petstore/python/petstore_api/models/class_model.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ClassModel(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class ClassModel(object): '_class': '_class' } - def __init__(self, _class=None): - """ - ClassModel - a model defined in Swagger - """ + def __init__(self, _class=None): # noqa: E501 + """ClassModel - a model defined in Swagger""" # noqa: E501 self.__class = None self.discriminator = None if _class is not None: - self._class = _class + self._class = _class @property def _class(self): - """ - Gets the _class of this ClassModel. + """Gets the _class of this ClassModel. # noqa: E501 - :return: The _class of this ClassModel. + + :return: The _class of this ClassModel. # noqa: E501 :rtype: str """ return self.__class @_class.setter def _class(self, _class): - """ - Sets the _class of this ClassModel. + """Sets the _class of this ClassModel. - :param _class: The _class of this ClassModel. + + :param _class: The _class of this ClassModel. # noqa: E501 :type: str """ self.__class = _class def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class ClassModel(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ClassModel): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/client.py b/samples/client/petstore/python/petstore_api/models/client.py index 395f77913cc..e267fed6d8c 100644 --- a/samples/client/petstore/python/petstore_api/models/client.py +++ b/samples/client/petstore/python/petstore_api/models/client.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Client(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class Client(object): 'client': 'client' } - def __init__(self, client=None): - """ - Client - a model defined in Swagger - """ + def __init__(self, client=None): # noqa: E501 + """Client - a model defined in Swagger""" # noqa: E501 self._client = None self.discriminator = None if client is not None: - self.client = client + self.client = client @property def client(self): - """ - Gets the client of this Client. + """Gets the client of this Client. # noqa: E501 - :return: The client of this Client. + + :return: The client of this Client. # noqa: E501 :rtype: str """ return self._client @client.setter def client(self, client): - """ - Sets the client of this Client. + """Sets the client of this Client. - :param client: The client of this Client. + + :param client: The client of this Client. # noqa: E501 :type: str """ self._client = client def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class Client(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Client): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/dog.py b/samples/client/petstore/python/petstore_api/models/dog.py index 3c159ad0d6f..34aac6aaad4 100644 --- a/samples/client/petstore/python/petstore_api/models/dog.py +++ b/samples/client/petstore/python/petstore_api/models/dog.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.animal import Animal # noqa: F401,E501 class Dog(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +40,41 @@ class Dog(object): 'breed': 'breed' } - def __init__(self, breed=None): - """ - Dog - a model defined in Swagger - """ + def __init__(self, breed=None): # noqa: E501 + """Dog - a model defined in Swagger""" # noqa: E501 self._breed = None self.discriminator = None if breed is not None: - self.breed = breed + self.breed = breed @property def breed(self): - """ - Gets the breed of this Dog. + """Gets the breed of this Dog. # noqa: E501 - :return: The breed of this Dog. + + :return: The breed of this Dog. # noqa: E501 :rtype: str """ return self._breed @breed.setter def breed(self, breed): - """ - Sets the breed of this Dog. + """Sets the breed of this Dog. - :param breed: The breed of this Dog. + + :param breed: The breed of this Dog. # noqa: E501 :type: str """ self._breed = breed def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +95,20 @@ class Dog(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Dog): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/enum_arrays.py b/samples/client/petstore/python/petstore_api/models/enum_arrays.py index 893085ea235..d02be298d2f 100644 --- a/samples/client/petstore/python/petstore_api/models/enum_arrays.py +++ b/samples/client/petstore/python/petstore_api/models/enum_arrays.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class EnumArrays(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,42 +40,40 @@ class EnumArrays(object): 'array_enum': 'array_enum' } - def __init__(self, just_symbol=None, array_enum=None): - """ - EnumArrays - a model defined in Swagger - """ + def __init__(self, just_symbol=None, array_enum=None): # noqa: E501 + """EnumArrays - a model defined in Swagger""" # noqa: E501 self._just_symbol = None self._array_enum = None self.discriminator = None if just_symbol is not None: - self.just_symbol = just_symbol + self.just_symbol = just_symbol if array_enum is not None: - self.array_enum = array_enum + self.array_enum = array_enum @property def just_symbol(self): - """ - Gets the just_symbol of this EnumArrays. + """Gets the just_symbol of this EnumArrays. # noqa: E501 - :return: The just_symbol of this EnumArrays. + + :return: The just_symbol of this EnumArrays. # noqa: E501 :rtype: str """ return self._just_symbol @just_symbol.setter def just_symbol(self, just_symbol): - """ - Sets the just_symbol of this EnumArrays. + """Sets the just_symbol of this EnumArrays. - :param just_symbol: The just_symbol of this EnumArrays. + + :param just_symbol: The just_symbol of this EnumArrays. # noqa: E501 :type: str """ - allowed_values = [">=", "$"] + allowed_values = [">=", "$"] # noqa: E501 if just_symbol not in allowed_values: raise ValueError( - "Invalid value for `just_symbol` ({0}), must be one of {1}" + "Invalid value for `just_symbol` ({0}), must be one of {1}" # noqa: E501 .format(just_symbol, allowed_values) ) @@ -83,39 +81,37 @@ class EnumArrays(object): @property def array_enum(self): - """ - Gets the array_enum of this EnumArrays. + """Gets the array_enum of this EnumArrays. # noqa: E501 - :return: The array_enum of this EnumArrays. + + :return: The array_enum of this EnumArrays. # noqa: E501 :rtype: list[str] """ return self._array_enum @array_enum.setter def array_enum(self, array_enum): - """ - Sets the array_enum of this EnumArrays. + """Sets the array_enum of this EnumArrays. - :param array_enum: The array_enum of this EnumArrays. + + :param array_enum: The array_enum of this EnumArrays. # noqa: E501 :type: list[str] """ - allowed_values = ["fish", "crab"] + allowed_values = ["fish", "crab"] # noqa: E501 if not set(array_enum).issubset(set(allowed_values)): raise ValueError( - "Invalid values for `array_enum` [{0}], must be a subset of [{1}]" - .format(", ".join(map(str, set(array_enum)-set(allowed_values))), + "Invalid values for `array_enum` [{0}], must be a subset of [{1}]" # noqa: E501 + .format(", ".join(map(str, set(array_enum) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._array_enum = array_enum def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -136,28 +132,20 @@ class EnumArrays(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, EnumArrays): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """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 index d9e0b771a7d..e4721545e83 100644 --- a/samples/client/petstore/python/petstore_api/models/enum_class.py +++ b/samples/client/petstore/python/petstore_api/models/enum_class.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,14 +11,15 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class EnumClass(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ @@ -37,28 +38,20 @@ class EnumClass(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - EnumClass - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """EnumClass - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -79,28 +72,20 @@ class EnumClass(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, EnumClass): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """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 index 6d7caa1f4bc..1bb234764ab 100644 --- a/samples/client/petstore/python/petstore_api/models/enum_test.py +++ b/samples/client/petstore/python/petstore_api/models/enum_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.outer_enum import OuterEnum # noqa: F401,E501 class EnumTest(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -44,10 +46,8 @@ class EnumTest(object): 'outer_enum': 'outerEnum' } - def __init__(self, enum_string=None, enum_integer=None, enum_number=None, outer_enum=None): - """ - EnumTest - a model defined in Swagger - """ + def __init__(self, enum_string=None, enum_integer=None, enum_number=None, outer_enum=None): # noqa: E501 + """EnumTest - a model defined in Swagger""" # noqa: E501 self._enum_string = None self._enum_integer = None @@ -56,36 +56,36 @@ class EnumTest(object): self.discriminator = None if enum_string is not None: - self.enum_string = enum_string + self.enum_string = enum_string if enum_integer is not None: - self.enum_integer = enum_integer + self.enum_integer = enum_integer if enum_number is not None: - self.enum_number = enum_number + self.enum_number = enum_number if outer_enum is not None: - self.outer_enum = outer_enum + self.outer_enum = outer_enum @property def enum_string(self): - """ - Gets the enum_string of this EnumTest. + """Gets the enum_string of this EnumTest. # noqa: E501 - :return: The enum_string of this EnumTest. + + :return: The enum_string of this EnumTest. # noqa: E501 :rtype: str """ return self._enum_string @enum_string.setter def enum_string(self, enum_string): - """ - Sets the enum_string of this EnumTest. + """Sets the enum_string of this EnumTest. - :param enum_string: The enum_string of this EnumTest. + + :param enum_string: The enum_string of this EnumTest. # noqa: E501 :type: str """ - allowed_values = ["UPPER", "lower", ""] + allowed_values = ["UPPER", "lower", ""] # noqa: E501 if enum_string not in allowed_values: raise ValueError( - "Invalid value for `enum_string` ({0}), must be one of {1}" + "Invalid value for `enum_string` ({0}), must be one of {1}" # noqa: E501 .format(enum_string, allowed_values) ) @@ -93,26 +93,26 @@ class EnumTest(object): @property def enum_integer(self): - """ - Gets the enum_integer of this EnumTest. + """Gets the enum_integer of this EnumTest. # noqa: E501 - :return: The enum_integer of this EnumTest. + + :return: The enum_integer of this EnumTest. # noqa: E501 :rtype: int """ return self._enum_integer @enum_integer.setter def enum_integer(self, enum_integer): - """ - Sets the enum_integer of this EnumTest. + """Sets the enum_integer of this EnumTest. - :param enum_integer: The enum_integer of this EnumTest. + + :param enum_integer: The enum_integer of this EnumTest. # noqa: E501 :type: int """ - allowed_values = [1, -1] + allowed_values = [1, -1] # noqa: E501 if enum_integer not in allowed_values: raise ValueError( - "Invalid value for `enum_integer` ({0}), must be one of {1}" + "Invalid value for `enum_integer` ({0}), must be one of {1}" # noqa: E501 .format(enum_integer, allowed_values) ) @@ -120,26 +120,26 @@ class EnumTest(object): @property def enum_number(self): - """ - Gets the enum_number of this EnumTest. + """Gets the enum_number of this EnumTest. # noqa: E501 - :return: The enum_number of this EnumTest. + + :return: The enum_number of this EnumTest. # noqa: E501 :rtype: float """ return self._enum_number @enum_number.setter def enum_number(self, enum_number): - """ - Sets the enum_number of this EnumTest. + """Sets the enum_number of this EnumTest. - :param enum_number: The enum_number of this EnumTest. + + :param enum_number: The enum_number of this EnumTest. # noqa: E501 :type: float """ - allowed_values = [1.1, -1.2] + allowed_values = [1.1, -1.2] # noqa: E501 if enum_number not in allowed_values: raise ValueError( - "Invalid value for `enum_number` ({0}), must be one of {1}" + "Invalid value for `enum_number` ({0}), must be one of {1}" # noqa: E501 .format(enum_number, allowed_values) ) @@ -147,32 +147,30 @@ class EnumTest(object): @property def outer_enum(self): - """ - Gets the outer_enum of this EnumTest. + """Gets the outer_enum of this EnumTest. # noqa: E501 - :return: The outer_enum of this EnumTest. + + :return: The outer_enum of this EnumTest. # noqa: E501 :rtype: OuterEnum """ return self._outer_enum @outer_enum.setter def outer_enum(self, outer_enum): - """ - Sets the outer_enum of this EnumTest. + """Sets the outer_enum of this EnumTest. - :param outer_enum: The outer_enum of this EnumTest. + + :param outer_enum: The outer_enum of this EnumTest. # noqa: E501 :type: OuterEnum """ self._outer_enum = outer_enum def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -193,28 +191,20 @@ class EnumTest(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, EnumTest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/format_test.py b/samples/client/petstore/python/petstore_api/models/format_test.py index 139d1733b35..7974d732fda 100644 --- a/samples/client/petstore/python/petstore_api/models/format_test.py +++ b/samples/client/petstore/python/petstore_api/models/format_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class FormatTest(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -62,10 +62,8 @@ class FormatTest(object): 'password': 'password' } - 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 - """ + 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): # noqa: E501 + """FormatTest - a model defined in Swagger""" # noqa: E501 self._integer = None self._int32 = None @@ -83,94 +81,94 @@ class FormatTest(object): self.discriminator = None if integer is not None: - self.integer = integer + self.integer = integer if int32 is not None: - self.int32 = int32 + self.int32 = int32 if int64 is not None: - self.int64 = int64 + self.int64 = int64 self.number = number if float is not None: - self.float = float + self.float = float if double is not None: - self.double = double + self.double = double if string is not None: - self.string = string + self.string = string self.byte = byte if binary is not None: - self.binary = binary + self.binary = binary self.date = date if date_time is not None: - self.date_time = date_time + self.date_time = date_time if uuid is not None: - self.uuid = uuid + self.uuid = uuid self.password = password @property def integer(self): - """ - Gets the integer of this FormatTest. + """Gets the integer of this FormatTest. # noqa: E501 - :return: The integer of this FormatTest. + + :return: The integer of this FormatTest. # noqa: E501 :rtype: int """ return self._integer @integer.setter def integer(self, integer): - """ - Sets the integer of this FormatTest. + """Sets the integer of this FormatTest. - :param integer: The integer of this FormatTest. + + :param integer: The integer of this FormatTest. # noqa: E501 :type: int """ - if integer is not None and integer > 100: - raise ValueError("Invalid value for `integer`, must be a value less than or equal to `100`") - if integer is not None and integer < 10: - raise ValueError("Invalid value for `integer`, must be a value greater than or equal to `10`") + if integer is not None and integer > 100: # noqa: E501 + raise ValueError("Invalid value for `integer`, must be a value less than or equal to `100`") # noqa: E501 + if integer is not None and integer < 10: # noqa: E501 + raise ValueError("Invalid value for `integer`, must be a value greater than or equal to `10`") # noqa: E501 self._integer = integer @property def int32(self): - """ - Gets the int32 of this FormatTest. + """Gets the int32 of this FormatTest. # noqa: E501 - :return: The int32 of this FormatTest. + + :return: The int32 of this FormatTest. # noqa: E501 :rtype: int """ return self._int32 @int32.setter def int32(self, int32): - """ - Sets the int32 of this FormatTest. + """Sets the int32 of this FormatTest. - :param int32: The int32 of this FormatTest. + + :param int32: The int32 of this FormatTest. # noqa: E501 :type: int """ - if int32 is not None and int32 > 200: - raise ValueError("Invalid value for `int32`, must be a value less than or equal to `200`") - if int32 is not None and int32 < 20: - raise ValueError("Invalid value for `int32`, must be a value greater than or equal to `20`") + if int32 is not None and int32 > 200: # noqa: E501 + raise ValueError("Invalid value for `int32`, must be a value less than or equal to `200`") # noqa: E501 + if int32 is not None and int32 < 20: # noqa: E501 + raise ValueError("Invalid value for `int32`, must be a value greater than or equal to `20`") # noqa: E501 self._int32 = int32 @property def int64(self): - """ - Gets the int64 of this FormatTest. + """Gets the int64 of this FormatTest. # noqa: E501 - :return: The int64 of this FormatTest. + + :return: The int64 of this FormatTest. # noqa: E501 :rtype: int """ return self._int64 @int64.setter def int64(self, int64): - """ - Sets the int64 of this FormatTest. + """Sets the int64 of this FormatTest. - :param int64: The int64 of this FormatTest. + + :param int64: The int64 of this FormatTest. # noqa: E501 :type: int """ @@ -178,145 +176,145 @@ class FormatTest(object): @property def number(self): - """ - Gets the number of this FormatTest. + """Gets the number of this FormatTest. # noqa: E501 - :return: The number of this FormatTest. + + :return: The number of this FormatTest. # noqa: E501 :rtype: float """ return self._number @number.setter def number(self, number): - """ - Sets the number of this FormatTest. + """Sets the number of this FormatTest. - :param number: The number of this FormatTest. + + :param number: The number of this FormatTest. # noqa: E501 :type: float """ if number is None: - raise ValueError("Invalid value for `number`, must not be `None`") - if number is not None and number > 543.2: - raise ValueError("Invalid value for `number`, must be a value less than or equal to `543.2`") - if number is not None and number < 32.1: - raise ValueError("Invalid value for `number`, must be a value greater than or equal to `32.1`") + raise ValueError("Invalid value for `number`, must not be `None`") # noqa: E501 + if number is not None and number > 543.2: # noqa: E501 + raise ValueError("Invalid value for `number`, must be a value less than or equal to `543.2`") # noqa: E501 + if number is not None and number < 32.1: # noqa: E501 + raise ValueError("Invalid value for `number`, must be a value greater than or equal to `32.1`") # noqa: E501 self._number = number @property def float(self): - """ - Gets the float of this FormatTest. + """Gets the float of this FormatTest. # noqa: E501 - :return: The float of this FormatTest. + + :return: The float of this FormatTest. # noqa: E501 :rtype: float """ return self._float @float.setter def float(self, float): - """ - Sets the float of this FormatTest. + """Sets the float of this FormatTest. - :param float: The float of this FormatTest. + + :param float: The float of this FormatTest. # noqa: E501 :type: float """ - if float is not None and float > 987.6: - raise ValueError("Invalid value for `float`, must be a value less than or equal to `987.6`") - if float is not None and float < 54.3: - raise ValueError("Invalid value for `float`, must be a value greater than or equal to `54.3`") + if float is not None and float > 987.6: # noqa: E501 + raise ValueError("Invalid value for `float`, must be a value less than or equal to `987.6`") # noqa: E501 + if float is not None and float < 54.3: # noqa: E501 + raise ValueError("Invalid value for `float`, must be a value greater than or equal to `54.3`") # noqa: E501 self._float = float @property def double(self): - """ - Gets the double of this FormatTest. + """Gets the double of this FormatTest. # noqa: E501 - :return: The double of this FormatTest. + + :return: The double of this FormatTest. # noqa: E501 :rtype: float """ return self._double @double.setter def double(self, double): - """ - Sets the double of this FormatTest. + """Sets the double of this FormatTest. - :param double: The double of this FormatTest. + + :param double: The double of this FormatTest. # noqa: E501 :type: float """ - if double is not None and double > 123.4: - raise ValueError("Invalid value for `double`, must be a value less than or equal to `123.4`") - if double is not None and double < 67.8: - raise ValueError("Invalid value for `double`, must be a value greater than or equal to `67.8`") + if double is not None and double > 123.4: # noqa: E501 + raise ValueError("Invalid value for `double`, must be a value less than or equal to `123.4`") # noqa: E501 + if double is not None and double < 67.8: # noqa: E501 + raise ValueError("Invalid value for `double`, must be a value greater than or equal to `67.8`") # noqa: E501 self._double = double @property def string(self): - """ - Gets the string of this FormatTest. + """Gets the string of this FormatTest. # noqa: E501 - :return: The string of this FormatTest. + + :return: The string of this FormatTest. # noqa: E501 :rtype: str """ return self._string @string.setter def string(self, string): - """ - Sets the string of this FormatTest. + """Sets the string of this FormatTest. - :param string: The string of this FormatTest. + + :param string: The string of this FormatTest. # noqa: E501 :type: str """ - if string is not None and 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`") + if string is not None and not re.search('[a-z]', string, flags=re.IGNORECASE): # noqa: E501 + raise ValueError("Invalid value for `string`, must be a follow pattern or equal to `/[a-z]/i`") # noqa: E501 self._string = string @property def byte(self): - """ - Gets the byte of this FormatTest. + """Gets the byte of this FormatTest. # noqa: E501 - :return: The byte of this FormatTest. + + :return: The byte of this FormatTest. # noqa: E501 :rtype: str """ return self._byte @byte.setter def byte(self, byte): - """ - Sets the byte of this FormatTest. + """Sets the byte of this FormatTest. - :param byte: The byte of this FormatTest. + + :param byte: The byte of this FormatTest. # noqa: E501 :type: str """ if byte is None: - raise ValueError("Invalid value for `byte`, must not be `None`") - if byte is not None and not re.search('^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', byte): - raise ValueError("Invalid value for `byte`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") + raise ValueError("Invalid value for `byte`, must not be `None`") # noqa: E501 + if byte is not None and not re.search('^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', byte): # noqa: E501 + raise ValueError("Invalid value for `byte`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501 self._byte = byte @property def binary(self): - """ - Gets the binary of this FormatTest. + """Gets the binary of this FormatTest. # noqa: E501 - :return: The binary of this FormatTest. + + :return: The binary of this FormatTest. # noqa: E501 :rtype: str """ return self._binary @binary.setter def binary(self, binary): - """ - Sets the binary of this FormatTest. + """Sets the binary of this FormatTest. - :param binary: The binary of this FormatTest. + + :param binary: The binary of this FormatTest. # noqa: E501 :type: str """ @@ -324,43 +322,43 @@ class FormatTest(object): @property def date(self): - """ - Gets the date of this FormatTest. + """Gets the date of this FormatTest. # noqa: E501 - :return: The date of this FormatTest. + + :return: The date of this FormatTest. # noqa: E501 :rtype: date """ return self._date @date.setter def date(self, date): - """ - Sets the date of this FormatTest. + """Sets the date of this FormatTest. - :param date: The date of this FormatTest. + + :param date: The date of this FormatTest. # noqa: E501 :type: date """ if date is None: - raise ValueError("Invalid value for `date`, must not be `None`") + raise ValueError("Invalid value for `date`, must not be `None`") # noqa: E501 self._date = date @property def date_time(self): - """ - Gets the date_time of this FormatTest. + """Gets the date_time of this FormatTest. # noqa: E501 - :return: The date_time of this FormatTest. + + :return: The date_time of this FormatTest. # noqa: E501 :rtype: datetime """ return self._date_time @date_time.setter def date_time(self, date_time): - """ - Sets the date_time of this FormatTest. + """Sets the date_time of this FormatTest. - :param date_time: The date_time of this FormatTest. + + :param date_time: The date_time of this FormatTest. # noqa: E501 :type: datetime """ @@ -368,20 +366,20 @@ class FormatTest(object): @property def uuid(self): - """ - Gets the uuid of this FormatTest. + """Gets the uuid of this FormatTest. # noqa: E501 - :return: The uuid of this FormatTest. + + :return: The uuid of this FormatTest. # noqa: E501 :rtype: str """ return self._uuid @uuid.setter def uuid(self, uuid): - """ - Sets the uuid of this FormatTest. + """Sets the uuid of this FormatTest. - :param uuid: The uuid of this FormatTest. + + :param uuid: The uuid of this FormatTest. # noqa: E501 :type: str """ @@ -389,38 +387,36 @@ class FormatTest(object): @property def password(self): - """ - Gets the password of this FormatTest. + """Gets the password of this FormatTest. # noqa: E501 - :return: The password of this FormatTest. + + :return: The password of this FormatTest. # noqa: E501 :rtype: str """ return self._password @password.setter def password(self, password): - """ - Sets the password of this FormatTest. + """Sets the password of this FormatTest. - :param password: The password of this FormatTest. + + :param password: The password of this FormatTest. # noqa: E501 :type: str """ if password is None: - raise ValueError("Invalid value for `password`, must not be `None`") + raise ValueError("Invalid value for `password`, must not be `None`") # noqa: E501 if password is not None and len(password) > 64: - raise ValueError("Invalid value for `password`, length must be less than or equal to `64`") + raise ValueError("Invalid value for `password`, length must be less than or equal to `64`") # noqa: E501 if password is not None and len(password) < 10: - raise ValueError("Invalid value for `password`, length must be greater than or equal to `10`") + raise ValueError("Invalid value for `password`, length must be greater than or equal to `10`") # noqa: E501 self._password = password def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -441,28 +437,20 @@ class FormatTest(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, FormatTest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/has_only_read_only.py b/samples/client/petstore/python/petstore_api/models/has_only_read_only.py index da0c14ec5b1..3c93eb30996 100644 --- a/samples/client/petstore/python/petstore_api/models/has_only_read_only.py +++ b/samples/client/petstore/python/petstore_api/models/has_only_read_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class HasOnlyReadOnly(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class HasOnlyReadOnly(object): 'foo': 'foo' } - def __init__(self, bar=None, foo=None): - """ - HasOnlyReadOnly - a model defined in Swagger - """ + def __init__(self, bar=None, foo=None): # noqa: E501 + """HasOnlyReadOnly - a model defined in Swagger""" # noqa: E501 self._bar = None self._foo = None self.discriminator = None if bar is not None: - self.bar = bar + self.bar = bar if foo is not None: - self.foo = foo + self.foo = foo @property def bar(self): - """ - Gets the bar of this HasOnlyReadOnly. + """Gets the bar of this HasOnlyReadOnly. # noqa: E501 - :return: The bar of this HasOnlyReadOnly. + + :return: The bar of this HasOnlyReadOnly. # noqa: E501 :rtype: str """ return self._bar @bar.setter def bar(self, bar): - """ - Sets the bar of this HasOnlyReadOnly. + """Sets the bar of this HasOnlyReadOnly. - :param bar: The bar of this HasOnlyReadOnly. + + :param bar: The bar of this HasOnlyReadOnly. # noqa: E501 :type: str """ @@ -77,32 +75,30 @@ class HasOnlyReadOnly(object): @property def foo(self): - """ - Gets the foo of this HasOnlyReadOnly. + """Gets the foo of this HasOnlyReadOnly. # noqa: E501 - :return: The foo of this HasOnlyReadOnly. + + :return: The foo of this HasOnlyReadOnly. # noqa: E501 :rtype: str """ return self._foo @foo.setter def foo(self, foo): - """ - Sets the foo of this HasOnlyReadOnly. + """Sets the foo of this HasOnlyReadOnly. - :param foo: The foo of this HasOnlyReadOnly. + + :param foo: The foo of this HasOnlyReadOnly. # noqa: E501 :type: str """ self._foo = foo def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class HasOnlyReadOnly(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, HasOnlyReadOnly): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/list.py b/samples/client/petstore/python/petstore_api/models/list.py index 2ac0e51fb12..fbe30e6d01e 100644 --- a/samples/client/petstore/python/petstore_api/models/list.py +++ b/samples/client/petstore/python/petstore_api/models/list.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class List(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class List(object): '_123_list': '123-list' } - def __init__(self, _123_list=None): - """ - List - a model defined in Swagger - """ + def __init__(self, _123_list=None): # noqa: E501 + """List - a model defined in Swagger""" # noqa: E501 self.__123_list = None self.discriminator = None if _123_list is not None: - self._123_list = _123_list + self._123_list = _123_list @property def _123_list(self): - """ - Gets the _123_list of this List. + """Gets the _123_list of this List. # noqa: E501 - :return: The _123_list of this List. + + :return: The _123_list of this List. # noqa: E501 :rtype: str """ return self.__123_list @_123_list.setter def _123_list(self, _123_list): - """ - Sets the _123_list of this List. + """Sets the _123_list of this List. - :param _123_list: The _123_list of this List. + + :param _123_list: The _123_list of this List. # noqa: E501 :type: str """ self.__123_list = _123_list def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class List(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, List): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/map_test.py b/samples/client/petstore/python/petstore_api/models/map_test.py index 3cb936e0db8..374c0661ba5 100644 --- a/samples/client/petstore/python/petstore_api/models/map_test.py +++ b/samples/client/petstore/python/petstore_api/models/map_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class MapTest(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class MapTest(object): 'map_of_enum_string': 'map_of_enum_string' } - def __init__(self, map_map_of_string=None, map_of_enum_string=None): - """ - MapTest - a model defined in Swagger - """ + def __init__(self, map_map_of_string=None, map_of_enum_string=None): # noqa: E501 + """MapTest - a model defined in Swagger""" # noqa: E501 self._map_map_of_string = None self._map_of_enum_string = None self.discriminator = None if map_map_of_string is not None: - self.map_map_of_string = map_map_of_string + self.map_map_of_string = map_map_of_string if map_of_enum_string is not None: - self.map_of_enum_string = map_of_enum_string + self.map_of_enum_string = map_of_enum_string @property def map_map_of_string(self): - """ - Gets the map_map_of_string of this MapTest. + """Gets the map_map_of_string of this MapTest. # noqa: E501 - :return: The map_map_of_string of this MapTest. + + :return: The map_map_of_string of this MapTest. # noqa: E501 :rtype: dict(str, dict(str, str)) """ return self._map_map_of_string @map_map_of_string.setter def map_map_of_string(self, map_map_of_string): - """ - Sets the map_map_of_string of this MapTest. + """Sets the map_map_of_string of this MapTest. - :param map_map_of_string: The map_map_of_string of this MapTest. + + :param map_map_of_string: The map_map_of_string of this MapTest. # noqa: E501 :type: dict(str, dict(str, str)) """ @@ -77,39 +75,37 @@ class MapTest(object): @property def map_of_enum_string(self): - """ - Gets the map_of_enum_string of this MapTest. + """Gets the map_of_enum_string of this MapTest. # noqa: E501 - :return: The map_of_enum_string of this MapTest. + + :return: The map_of_enum_string of this MapTest. # noqa: E501 :rtype: dict(str, str) """ return self._map_of_enum_string @map_of_enum_string.setter def map_of_enum_string(self, map_of_enum_string): - """ - Sets the map_of_enum_string of this MapTest. + """Sets the map_of_enum_string of this MapTest. - :param map_of_enum_string: The map_of_enum_string of this MapTest. + + :param map_of_enum_string: The map_of_enum_string of this MapTest. # noqa: E501 :type: dict(str, str) """ - allowed_values = ["UPPER", "lower"] + allowed_values = ["UPPER", "lower"] # noqa: E501 if not set(map_of_enum_string.keys()).issubset(set(allowed_values)): raise ValueError( - "Invalid keys in `map_of_enum_string` [{0}], must be a subset of [{1}]" - .format(", ".join(map(str, set(map_of_enum_string.keys())-set(allowed_values))), + "Invalid keys in `map_of_enum_string` [{0}], must be a subset of [{1}]" # noqa: E501 + .format(", ".join(map(str, set(map_of_enum_string.keys()) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._map_of_enum_string = map_of_enum_string def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -130,28 +126,20 @@ class MapTest(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, MapTest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """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 index 4b773deacef..dba1f261352 100644 --- 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 @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,20 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.animal import Animal # noqa: F401,E501 class MixedPropertiesAndAdditionalPropertiesClass(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -42,10 +44,8 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): 'map': 'map' } - def __init__(self, uuid=None, date_time=None, map=None): - """ - MixedPropertiesAndAdditionalPropertiesClass - a model defined in Swagger - """ + def __init__(self, uuid=None, date_time=None, map=None): # noqa: E501 + """MixedPropertiesAndAdditionalPropertiesClass - a model defined in Swagger""" # noqa: E501 self._uuid = None self._date_time = None @@ -53,28 +53,28 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): self.discriminator = None if uuid is not None: - self.uuid = uuid + self.uuid = uuid if date_time is not None: - self.date_time = date_time + self.date_time = date_time if map is not None: - self.map = map + self.map = map @property def uuid(self): - """ - Gets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. + """Gets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - :return: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. + + :return: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :rtype: str """ return self._uuid @uuid.setter def uuid(self, uuid): - """ - Sets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. + """Sets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. - :param uuid: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. + + :param uuid: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :type: str """ @@ -82,20 +82,20 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): @property def date_time(self): - """ - Gets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. + """Gets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - :return: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. + + :return: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :rtype: datetime """ return self._date_time @date_time.setter def date_time(self, date_time): - """ - Sets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. + """Sets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. - :param date_time: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. + + :param date_time: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :type: datetime """ @@ -103,32 +103,30 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): @property def map(self): - """ - Gets the map of this MixedPropertiesAndAdditionalPropertiesClass. + """Gets the map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - :return: The map of this MixedPropertiesAndAdditionalPropertiesClass. + + :return: The map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :rtype: dict(str, Animal) """ return self._map @map.setter def map(self, map): - """ - Sets the map of this MixedPropertiesAndAdditionalPropertiesClass. + """Sets the map of this MixedPropertiesAndAdditionalPropertiesClass. - :param map: The map of this MixedPropertiesAndAdditionalPropertiesClass. + + :param map: The map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 :type: dict(str, Animal) """ self._map = map def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -149,28 +147,20 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, MixedPropertiesAndAdditionalPropertiesClass): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/model_200_response.py b/samples/client/petstore/python/petstore_api/models/model_200_response.py index 2b6aeb090c0..60f9c96a676 100644 --- a/samples/client/petstore/python/petstore_api/models/model_200_response.py +++ b/samples/client/petstore/python/petstore_api/models/model_200_response.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Model200Response(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class Model200Response(object): '_class': 'class' } - def __init__(self, name=None, _class=None): - """ - Model200Response - a model defined in Swagger - """ + def __init__(self, name=None, _class=None): # noqa: E501 + """Model200Response - a model defined in Swagger""" # noqa: E501 self._name = None self.__class = None self.discriminator = None if name is not None: - self.name = name + self.name = name if _class is not None: - self._class = _class + self._class = _class @property def name(self): - """ - Gets the name of this Model200Response. + """Gets the name of this Model200Response. # noqa: E501 - :return: The name of this Model200Response. + + :return: The name of this Model200Response. # noqa: E501 :rtype: int """ return self._name @name.setter def name(self, name): - """ - Sets the name of this Model200Response. + """Sets the name of this Model200Response. - :param name: The name of this Model200Response. + + :param name: The name of this Model200Response. # noqa: E501 :type: int """ @@ -77,32 +75,30 @@ class Model200Response(object): @property def _class(self): - """ - Gets the _class of this Model200Response. + """Gets the _class of this Model200Response. # noqa: E501 - :return: The _class of this Model200Response. + + :return: The _class of this Model200Response. # noqa: E501 :rtype: str """ return self.__class @_class.setter def _class(self, _class): - """ - Sets the _class of this Model200Response. + """Sets the _class of this Model200Response. - :param _class: The _class of this Model200Response. + + :param _class: The _class of this Model200Response. # noqa: E501 :type: str """ self.__class = _class def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class Model200Response(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Model200Response): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/model_return.py b/samples/client/petstore/python/petstore_api/models/model_return.py index a2160d21dd1..c9d8b5682aa 100644 --- a/samples/client/petstore/python/petstore_api/models/model_return.py +++ b/samples/client/petstore/python/petstore_api/models/model_return.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ModelReturn(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class ModelReturn(object): '_return': 'return' } - def __init__(self, _return=None): - """ - ModelReturn - a model defined in Swagger - """ + def __init__(self, _return=None): # noqa: E501 + """ModelReturn - a model defined in Swagger""" # noqa: E501 self.__return = None self.discriminator = None if _return is not None: - self._return = _return + self._return = _return @property def _return(self): - """ - Gets the _return of this ModelReturn. + """Gets the _return of this ModelReturn. # noqa: E501 - :return: The _return of this ModelReturn. + + :return: The _return of this ModelReturn. # noqa: E501 :rtype: int """ return self.__return @_return.setter def _return(self, _return): - """ - Sets the _return of this ModelReturn. + """Sets the _return of this ModelReturn. - :param _return: The _return of this ModelReturn. + + :param _return: The _return of this ModelReturn. # noqa: E501 :type: int """ self.__return = _return def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class ModelReturn(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ModelReturn): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/name.py b/samples/client/petstore/python/petstore_api/models/name.py index 52b51890dde..cbfbddeb1ab 100644 --- a/samples/client/petstore/python/petstore_api/models/name.py +++ b/samples/client/petstore/python/petstore_api/models/name.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Name(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -44,10 +44,8 @@ class Name(object): '_123_number': '123Number' } - def __init__(self, name=None, snake_case=None, _property=None, _123_number=None): - """ - Name - a model defined in Swagger - """ + def __init__(self, name=None, snake_case=None, _property=None, _123_number=None): # noqa: E501 + """Name - a model defined in Swagger""" # noqa: E501 self._name = None self._snake_case = None @@ -57,51 +55,51 @@ class Name(object): self.name = name if snake_case is not None: - self.snake_case = snake_case + self.snake_case = snake_case if _property is not None: - self._property = _property + self._property = _property if _123_number is not None: - self._123_number = _123_number + self._123_number = _123_number @property def name(self): - """ - Gets the name of this Name. + """Gets the name of this Name. # noqa: E501 - :return: The name of this Name. + + :return: The name of this Name. # noqa: E501 :rtype: int """ return self._name @name.setter def name(self, name): - """ - Sets the name of this Name. + """Sets the name of this Name. - :param name: The name of this Name. + + :param name: The name of this Name. # noqa: E501 :type: int """ if name is None: - raise ValueError("Invalid value for `name`, must not be `None`") + raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name @property def snake_case(self): - """ - Gets the snake_case of this Name. + """Gets the snake_case of this Name. # noqa: E501 - :return: The snake_case of this Name. + + :return: The snake_case of this Name. # noqa: E501 :rtype: int """ return self._snake_case @snake_case.setter def snake_case(self, snake_case): - """ - Sets the snake_case of this Name. + """Sets the snake_case of this Name. - :param snake_case: The snake_case of this Name. + + :param snake_case: The snake_case of this Name. # noqa: E501 :type: int """ @@ -109,20 +107,20 @@ class Name(object): @property def _property(self): - """ - Gets the _property of this Name. + """Gets the _property of this Name. # noqa: E501 - :return: The _property of this Name. + + :return: The _property of this Name. # noqa: E501 :rtype: str """ return self.__property @_property.setter def _property(self, _property): - """ - Sets the _property of this Name. + """Sets the _property of this Name. - :param _property: The _property of this Name. + + :param _property: The _property of this Name. # noqa: E501 :type: str """ @@ -130,32 +128,30 @@ class Name(object): @property def _123_number(self): - """ - Gets the _123_number of this Name. + """Gets the _123_number of this Name. # noqa: E501 - :return: The _123_number of this Name. + + :return: The _123_number of this Name. # noqa: E501 :rtype: int """ return self.__123_number @_123_number.setter def _123_number(self, _123_number): - """ - Sets the _123_number of this Name. + """Sets the _123_number of this Name. - :param _123_number: The _123_number of this Name. + + :param _123_number: The _123_number of this Name. # noqa: E501 :type: int """ self.__123_number = _123_number def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -176,28 +172,20 @@ class Name(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Name): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/number_only.py b/samples/client/petstore/python/petstore_api/models/number_only.py index b0e279b53a5..b96321109b9 100644 --- a/samples/client/petstore/python/petstore_api/models/number_only.py +++ b/samples/client/petstore/python/petstore_api/models/number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class NumberOnly(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class NumberOnly(object): 'just_number': 'JustNumber' } - def __init__(self, just_number=None): - """ - NumberOnly - a model defined in Swagger - """ + def __init__(self, just_number=None): # noqa: E501 + """NumberOnly - a model defined in Swagger""" # noqa: E501 self._just_number = None self.discriminator = None if just_number is not None: - self.just_number = just_number + self.just_number = just_number @property def just_number(self): - """ - Gets the just_number of this NumberOnly. + """Gets the just_number of this NumberOnly. # noqa: E501 - :return: The just_number of this NumberOnly. + + :return: The just_number of this NumberOnly. # noqa: E501 :rtype: float """ return self._just_number @just_number.setter def just_number(self, just_number): - """ - Sets the just_number of this NumberOnly. + """Sets the just_number of this NumberOnly. - :param just_number: The just_number of this NumberOnly. + + :param just_number: The just_number of this NumberOnly. # noqa: E501 :type: float """ self._just_number = just_number def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class NumberOnly(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, NumberOnly): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/order.py b/samples/client/petstore/python/petstore_api/models/order.py index 52c7b6c227e..6636542e941 100644 --- a/samples/client/petstore/python/petstore_api/models/order.py +++ b/samples/client/petstore/python/petstore_api/models/order.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Order(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -48,10 +48,8 @@ class Order(object): 'complete': 'complete' } - def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=None, complete=False): - """ - Order - a model defined in Swagger - """ + def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=None, complete=False): # noqa: E501 + """Order - a model defined in Swagger""" # noqa: E501 self._id = None self._pet_id = None @@ -62,34 +60,34 @@ class Order(object): self.discriminator = None if id is not None: - self.id = id + self.id = id if pet_id is not None: - self.pet_id = pet_id + self.pet_id = pet_id if quantity is not None: - self.quantity = quantity + self.quantity = quantity if ship_date is not None: - self.ship_date = ship_date + self.ship_date = ship_date if status is not None: - self.status = status + self.status = status if complete is not None: - self.complete = complete + self.complete = complete @property def id(self): - """ - Gets the id of this Order. + """Gets the id of this Order. # noqa: E501 - :return: The id of this Order. + + :return: The id of this Order. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): - """ - Sets the id of this Order. + """Sets the id of this Order. - :param id: The id of this Order. + + :param id: The id of this Order. # noqa: E501 :type: int """ @@ -97,20 +95,20 @@ class Order(object): @property def pet_id(self): - """ - Gets the pet_id of this Order. + """Gets the pet_id of this Order. # noqa: E501 - :return: The pet_id of this Order. + + :return: The pet_id of this Order. # noqa: E501 :rtype: int """ return self._pet_id @pet_id.setter def pet_id(self, pet_id): - """ - Sets the pet_id of this Order. + """Sets the pet_id of this Order. - :param pet_id: The pet_id of this Order. + + :param pet_id: The pet_id of this Order. # noqa: E501 :type: int """ @@ -118,20 +116,20 @@ class Order(object): @property def quantity(self): - """ - Gets the quantity of this Order. + """Gets the quantity of this Order. # noqa: E501 - :return: The quantity of this Order. + + :return: The quantity of this Order. # noqa: E501 :rtype: int """ return self._quantity @quantity.setter def quantity(self, quantity): - """ - Sets the quantity of this Order. + """Sets the quantity of this Order. - :param quantity: The quantity of this Order. + + :param quantity: The quantity of this Order. # noqa: E501 :type: int """ @@ -139,20 +137,20 @@ class Order(object): @property def ship_date(self): - """ - Gets the ship_date of this Order. + """Gets the ship_date of this Order. # noqa: E501 - :return: The ship_date of this Order. + + :return: The ship_date of this Order. # noqa: E501 :rtype: datetime """ return self._ship_date @ship_date.setter def ship_date(self, ship_date): - """ - Sets the ship_date of this Order. + """Sets the ship_date of this Order. - :param ship_date: The ship_date of this Order. + + :param ship_date: The ship_date of this Order. # noqa: E501 :type: datetime """ @@ -160,28 +158,28 @@ class Order(object): @property def status(self): - """ - Gets the status of this Order. - Order Status + """Gets the status of this Order. # noqa: E501 - :return: The status of this Order. + Order Status # noqa: E501 + + :return: The status of this Order. # noqa: E501 :rtype: str """ return self._status @status.setter def status(self, status): - """ - Sets the status of this Order. - Order Status + """Sets the status of this Order. - :param status: The status of this Order. + Order Status # noqa: E501 + + :param status: The status of this Order. # noqa: E501 :type: str """ - allowed_values = ["placed", "approved", "delivered"] + allowed_values = ["placed", "approved", "delivered"] # noqa: E501 if status not in allowed_values: raise ValueError( - "Invalid value for `status` ({0}), must be one of {1}" + "Invalid value for `status` ({0}), must be one of {1}" # noqa: E501 .format(status, allowed_values) ) @@ -189,32 +187,30 @@ class Order(object): @property def complete(self): - """ - Gets the complete of this Order. + """Gets the complete of this Order. # noqa: E501 - :return: The complete of this Order. + + :return: The complete of this Order. # noqa: E501 :rtype: bool """ return self._complete @complete.setter def complete(self, complete): - """ - Sets the complete of this Order. + """Sets the complete of this Order. - :param complete: The complete of this Order. + + :param complete: The complete of this Order. # noqa: E501 :type: bool """ self._complete = complete def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -235,28 +231,20 @@ class Order(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Order): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/outer_boolean.py b/samples/client/petstore/python/petstore_api/models/outer_boolean.py index aa9aee11973..9b3aebd3608 100644 --- a/samples/client/petstore/python/petstore_api/models/outer_boolean.py +++ b/samples/client/petstore/python/petstore_api/models/outer_boolean.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class OuterBoolean(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -31,28 +31,20 @@ class OuterBoolean(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - OuterBoolean - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """OuterBoolean - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -73,28 +65,20 @@ class OuterBoolean(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, OuterBoolean): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/outer_composite.py b/samples/client/petstore/python/petstore_api/models/outer_composite.py index 81611c17688..19775255e4e 100644 --- a/samples/client/petstore/python/petstore_api/models/outer_composite.py +++ b/samples/client/petstore/python/petstore_api/models/outer_composite.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,22 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.outer_boolean import OuterBoolean # noqa: F401,E501 +from petstore_api.models.outer_number import OuterNumber # noqa: F401,E501 +from petstore_api.models.outer_string import OuterString # noqa: F401,E501 class OuterComposite(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -42,10 +46,8 @@ class OuterComposite(object): 'my_boolean': 'my_boolean' } - def __init__(self, my_number=None, my_string=None, my_boolean=None): - """ - OuterComposite - a model defined in Swagger - """ + def __init__(self, my_number=None, my_string=None, my_boolean=None): # noqa: E501 + """OuterComposite - a model defined in Swagger""" # noqa: E501 self._my_number = None self._my_string = None @@ -53,28 +55,28 @@ class OuterComposite(object): self.discriminator = None if my_number is not None: - self.my_number = my_number + self.my_number = my_number if my_string is not None: - self.my_string = my_string + self.my_string = my_string if my_boolean is not None: - self.my_boolean = my_boolean + self.my_boolean = my_boolean @property def my_number(self): - """ - Gets the my_number of this OuterComposite. + """Gets the my_number of this OuterComposite. # noqa: E501 - :return: The my_number of this OuterComposite. + + :return: The my_number of this OuterComposite. # noqa: E501 :rtype: OuterNumber """ return self._my_number @my_number.setter def my_number(self, my_number): - """ - Sets the my_number of this OuterComposite. + """Sets the my_number of this OuterComposite. - :param my_number: The my_number of this OuterComposite. + + :param my_number: The my_number of this OuterComposite. # noqa: E501 :type: OuterNumber """ @@ -82,20 +84,20 @@ class OuterComposite(object): @property def my_string(self): - """ - Gets the my_string of this OuterComposite. + """Gets the my_string of this OuterComposite. # noqa: E501 - :return: The my_string of this OuterComposite. + + :return: The my_string of this OuterComposite. # noqa: E501 :rtype: OuterString """ return self._my_string @my_string.setter def my_string(self, my_string): - """ - Sets the my_string of this OuterComposite. + """Sets the my_string of this OuterComposite. - :param my_string: The my_string of this OuterComposite. + + :param my_string: The my_string of this OuterComposite. # noqa: E501 :type: OuterString """ @@ -103,32 +105,30 @@ class OuterComposite(object): @property def my_boolean(self): - """ - Gets the my_boolean of this OuterComposite. + """Gets the my_boolean of this OuterComposite. # noqa: E501 - :return: The my_boolean of this OuterComposite. + + :return: The my_boolean of this OuterComposite. # noqa: E501 :rtype: OuterBoolean """ return self._my_boolean @my_boolean.setter def my_boolean(self, my_boolean): - """ - Sets the my_boolean of this OuterComposite. + """Sets the my_boolean of this OuterComposite. - :param my_boolean: The my_boolean of this OuterComposite. + + :param my_boolean: The my_boolean of this OuterComposite. # noqa: E501 :type: OuterBoolean """ self._my_boolean = my_boolean def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -149,28 +149,20 @@ class OuterComposite(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, OuterComposite): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/outer_enum.py b/samples/client/petstore/python/petstore_api/models/outer_enum.py index 8772472c655..5ee1e49a587 100644 --- a/samples/client/petstore/python/petstore_api/models/outer_enum.py +++ b/samples/client/petstore/python/petstore_api/models/outer_enum.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,14 +11,15 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class OuterEnum(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ @@ -37,28 +38,20 @@ class OuterEnum(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - OuterEnum - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """OuterEnum - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -79,28 +72,20 @@ class OuterEnum(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, OuterEnum): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/outer_number.py b/samples/client/petstore/python/petstore_api/models/outer_number.py index 04c44923fb0..a35587be65e 100644 --- a/samples/client/petstore/python/petstore_api/models/outer_number.py +++ b/samples/client/petstore/python/petstore_api/models/outer_number.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class OuterNumber(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -31,28 +31,20 @@ class OuterNumber(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - OuterNumber - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """OuterNumber - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -73,28 +65,20 @@ class OuterNumber(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, OuterNumber): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/outer_string.py b/samples/client/petstore/python/petstore_api/models/outer_string.py index fd2d7c7623e..736edacd1bc 100644 --- a/samples/client/petstore/python/petstore_api/models/outer_string.py +++ b/samples/client/petstore/python/petstore_api/models/outer_string.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class OuterString(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -31,28 +31,20 @@ class OuterString(object): and the value is json key in definition. """ swagger_types = { - } attribute_map = { - } - def __init__(self): - """ - OuterString - a model defined in Swagger - """ - + def __init__(self): # noqa: E501 + """OuterString - a model defined in Swagger""" # noqa: E501 self.discriminator = None - def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -73,28 +65,20 @@ class OuterString(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, OuterString): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/pet.py b/samples/client/petstore/python/petstore_api/models/pet.py index e1afa26f785..81b2bb617f9 100644 --- a/samples/client/petstore/python/petstore_api/models/pet.py +++ b/samples/client/petstore/python/petstore_api/models/pet.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,21 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six + +from petstore_api.models.category import Category # noqa: F401,E501 +from petstore_api.models.tag import Tag # noqa: F401,E501 class Pet(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -48,10 +51,8 @@ class Pet(object): 'status': 'status' } - def __init__(self, id=None, category=None, name=None, photo_urls=None, tags=None, status=None): - """ - Pet - a model defined in Swagger - """ + def __init__(self, id=None, category=None, name=None, photo_urls=None, tags=None, status=None): # noqa: E501 + """Pet - a model defined in Swagger""" # noqa: E501 self._id = None self._category = None @@ -62,32 +63,32 @@ class Pet(object): self.discriminator = None if id is not None: - self.id = id + self.id = id if category is not None: - self.category = category + self.category = category self.name = name self.photo_urls = photo_urls if tags is not None: - self.tags = tags + self.tags = tags if status is not None: - self.status = status + self.status = status @property def id(self): - """ - Gets the id of this Pet. + """Gets the id of this Pet. # noqa: E501 - :return: The id of this Pet. + + :return: The id of this Pet. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): - """ - Sets the id of this Pet. + """Sets the id of this Pet. - :param id: The id of this Pet. + + :param id: The id of this Pet. # noqa: E501 :type: int """ @@ -95,20 +96,20 @@ class Pet(object): @property def category(self): - """ - Gets the category of this Pet. + """Gets the category of this Pet. # noqa: E501 - :return: The category of this Pet. + + :return: The category of this Pet. # noqa: E501 :rtype: Category """ return self._category @category.setter def category(self, category): - """ - Sets the category of this Pet. + """Sets the category of this Pet. - :param category: The category of this Pet. + + :param category: The category of this Pet. # noqa: E501 :type: Category """ @@ -116,66 +117,66 @@ class Pet(object): @property def name(self): - """ - Gets the name of this Pet. + """Gets the name of this Pet. # noqa: E501 - :return: The name of this Pet. + + :return: The name of this Pet. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): - """ - Sets the name of this Pet. + """Sets the name of this Pet. - :param name: The name of this Pet. + + :param name: The name of this Pet. # noqa: E501 :type: str """ if name is None: - raise ValueError("Invalid value for `name`, must not be `None`") + raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name @property def photo_urls(self): - """ - Gets the photo_urls of this Pet. + """Gets the photo_urls of this Pet. # noqa: E501 - :return: The photo_urls of this Pet. + + :return: The photo_urls of this Pet. # noqa: E501 :rtype: list[str] """ return self._photo_urls @photo_urls.setter def photo_urls(self, photo_urls): - """ - Sets the photo_urls of this Pet. + """Sets the photo_urls of this Pet. - :param photo_urls: The photo_urls of this Pet. + + :param photo_urls: The photo_urls of this Pet. # noqa: E501 :type: list[str] """ if photo_urls is None: - raise ValueError("Invalid value for `photo_urls`, must not be `None`") + raise ValueError("Invalid value for `photo_urls`, must not be `None`") # noqa: E501 self._photo_urls = photo_urls @property def tags(self): - """ - Gets the tags of this Pet. + """Gets the tags of this Pet. # noqa: E501 - :return: The tags of this Pet. + + :return: The tags of this Pet. # noqa: E501 :rtype: list[Tag] """ return self._tags @tags.setter def tags(self, tags): - """ - Sets the tags of this Pet. + """Sets the tags of this Pet. - :param tags: The tags of this Pet. + + :param tags: The tags of this Pet. # noqa: E501 :type: list[Tag] """ @@ -183,40 +184,38 @@ class Pet(object): @property def status(self): - """ - Gets the status of this Pet. - pet status in the store + """Gets the status of this Pet. # noqa: E501 - :return: The status of this Pet. + pet status in the store # noqa: E501 + + :return: The status of this Pet. # noqa: E501 :rtype: str """ return self._status @status.setter def status(self, status): - """ - Sets the status of this Pet. - pet status in the store + """Sets the status of this Pet. - :param status: The status of this Pet. + pet status in the store # noqa: E501 + + :param status: The status of this Pet. # noqa: E501 :type: str """ - allowed_values = ["available", "pending", "sold"] + allowed_values = ["available", "pending", "sold"] # noqa: E501 if status not in allowed_values: raise ValueError( - "Invalid value for `status` ({0}), must be one of {1}" + "Invalid value for `status` ({0}), must be one of {1}" # noqa: E501 .format(status, allowed_values) ) self._status = status def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -237,28 +236,20 @@ class Pet(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Pet): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """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 index a26d1f33c87..106463077e8 100644 --- a/samples/client/petstore/python/petstore_api/models/read_only_first.py +++ b/samples/client/petstore/python/petstore_api/models/read_only_first.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class ReadOnlyFirst(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class ReadOnlyFirst(object): 'baz': 'baz' } - def __init__(self, bar=None, baz=None): - """ - ReadOnlyFirst - a model defined in Swagger - """ + def __init__(self, bar=None, baz=None): # noqa: E501 + """ReadOnlyFirst - a model defined in Swagger""" # noqa: E501 self._bar = None self._baz = None self.discriminator = None if bar is not None: - self.bar = bar + self.bar = bar if baz is not None: - self.baz = baz + self.baz = baz @property def bar(self): - """ - Gets the bar of this ReadOnlyFirst. + """Gets the bar of this ReadOnlyFirst. # noqa: E501 - :return: The bar of this ReadOnlyFirst. + + :return: The bar of this ReadOnlyFirst. # noqa: E501 :rtype: str """ return self._bar @bar.setter def bar(self, bar): - """ - Sets the bar of this ReadOnlyFirst. + """Sets the bar of this ReadOnlyFirst. - :param bar: The bar of this ReadOnlyFirst. + + :param bar: The bar of this ReadOnlyFirst. # noqa: E501 :type: str """ @@ -77,32 +75,30 @@ class ReadOnlyFirst(object): @property def baz(self): - """ - Gets the baz of this ReadOnlyFirst. + """Gets the baz of this ReadOnlyFirst. # noqa: E501 - :return: The baz of this ReadOnlyFirst. + + :return: The baz of this ReadOnlyFirst. # noqa: E501 :rtype: str """ return self._baz @baz.setter def baz(self, baz): - """ - Sets the baz of this ReadOnlyFirst. + """Sets the baz of this ReadOnlyFirst. - :param baz: The baz of this ReadOnlyFirst. + + :param baz: The baz of this ReadOnlyFirst. # noqa: E501 :type: str """ self._baz = baz def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class ReadOnlyFirst(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, ReadOnlyFirst): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/special_model_name.py b/samples/client/petstore/python/petstore_api/models/special_model_name.py index 6be888fb9e3..a31b8db66e2 100644 --- a/samples/client/petstore/python/petstore_api/models/special_model_name.py +++ b/samples/client/petstore/python/petstore_api/models/special_model_name.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class SpecialModelName(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -38,45 +38,41 @@ class SpecialModelName(object): 'special_property_name': '$special[property.name]' } - def __init__(self, special_property_name=None): - """ - SpecialModelName - a model defined in Swagger - """ + def __init__(self, special_property_name=None): # noqa: E501 + """SpecialModelName - a model defined in Swagger""" # noqa: E501 self._special_property_name = None self.discriminator = None if special_property_name is not None: - self.special_property_name = special_property_name + self.special_property_name = special_property_name @property def special_property_name(self): - """ - Gets the special_property_name of this SpecialModelName. + """Gets the special_property_name of this SpecialModelName. # noqa: E501 - :return: The special_property_name of this SpecialModelName. + + :return: The special_property_name of this SpecialModelName. # noqa: E501 :rtype: int """ return self._special_property_name @special_property_name.setter def special_property_name(self, special_property_name): - """ - Sets the special_property_name of this SpecialModelName. + """Sets the special_property_name of this SpecialModelName. - :param special_property_name: The special_property_name of this SpecialModelName. + + :param special_property_name: The special_property_name of this SpecialModelName. # noqa: E501 :type: int """ self._special_property_name = special_property_name def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -97,28 +93,20 @@ class SpecialModelName(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, SpecialModelName): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/tag.py b/samples/client/petstore/python/petstore_api/models/tag.py index d59a490a07d..b486a672b88 100644 --- a/samples/client/petstore/python/petstore_api/models/tag.py +++ b/samples/client/petstore/python/petstore_api/models/tag.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class Tag(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -40,36 +40,34 @@ class Tag(object): 'name': 'name' } - def __init__(self, id=None, name=None): - """ - Tag - a model defined in Swagger - """ + def __init__(self, id=None, name=None): # noqa: E501 + """Tag - a model defined in Swagger""" # noqa: E501 self._id = None self._name = None self.discriminator = None if id is not None: - self.id = id + self.id = id if name is not None: - self.name = name + self.name = name @property def id(self): - """ - Gets the id of this Tag. + """Gets the id of this Tag. # noqa: E501 - :return: The id of this Tag. + + :return: The id of this Tag. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): - """ - Sets the id of this Tag. + """Sets the id of this Tag. - :param id: The id of this Tag. + + :param id: The id of this Tag. # noqa: E501 :type: int """ @@ -77,32 +75,30 @@ class Tag(object): @property def name(self): - """ - Gets the name of this Tag. + """Gets the name of this Tag. # noqa: E501 - :return: The name of this Tag. + + :return: The name of this Tag. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): - """ - Sets the name of this Tag. + """Sets the name of this Tag. - :param name: The name of this Tag. + + :param name: The name of this Tag. # noqa: E501 :type: str """ self._name = name def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -123,28 +119,20 @@ class Tag(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, Tag): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/user.py b/samples/client/petstore/python/petstore_api/models/user.py index 21993e90521..c9fe0072a9c 100644 --- a/samples/client/petstore/python/petstore_api/models/user.py +++ b/samples/client/petstore/python/petstore_api/models/user.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,18 +11,18 @@ """ -from pprint import pformat -from six import iteritems -import re +import pprint +import re # noqa: F401 + +import six class User(object): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ - """ Attributes: swagger_types (dict): The key is attribute name @@ -52,10 +52,8 @@ class User(object): 'user_status': 'userStatus' } - 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 - """ + def __init__(self, id=None, username=None, first_name=None, last_name=None, email=None, password=None, phone=None, user_status=None): # noqa: E501 + """User - a model defined in Swagger""" # noqa: E501 self._id = None self._username = None @@ -68,38 +66,38 @@ class User(object): self.discriminator = None if id is not None: - self.id = id + self.id = id if username is not None: - self.username = username + self.username = username if first_name is not None: - self.first_name = first_name + self.first_name = first_name if last_name is not None: - self.last_name = last_name + self.last_name = last_name if email is not None: - self.email = email + self.email = email if password is not None: - self.password = password + self.password = password if phone is not None: - self.phone = phone + self.phone = phone if user_status is not None: - self.user_status = user_status + self.user_status = user_status @property def id(self): - """ - Gets the id of this User. + """Gets the id of this User. # noqa: E501 - :return: The id of this User. + + :return: The id of this User. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): - """ - Sets the id of this User. + """Sets the id of this User. - :param id: The id of this User. + + :param id: The id of this User. # noqa: E501 :type: int """ @@ -107,20 +105,20 @@ class User(object): @property def username(self): - """ - Gets the username of this User. + """Gets the username of this User. # noqa: E501 - :return: The username of this User. + + :return: The username of this User. # noqa: E501 :rtype: str """ return self._username @username.setter def username(self, username): - """ - Sets the username of this User. + """Sets the username of this User. - :param username: The username of this User. + + :param username: The username of this User. # noqa: E501 :type: str """ @@ -128,20 +126,20 @@ class User(object): @property def first_name(self): - """ - Gets the first_name of this User. + """Gets the first_name of this User. # noqa: E501 - :return: The first_name of this User. + + :return: The first_name of this User. # noqa: E501 :rtype: str """ return self._first_name @first_name.setter def first_name(self, first_name): - """ - Sets the first_name of this User. + """Sets the first_name of this User. - :param first_name: The first_name of this User. + + :param first_name: The first_name of this User. # noqa: E501 :type: str """ @@ -149,20 +147,20 @@ class User(object): @property def last_name(self): - """ - Gets the last_name of this User. + """Gets the last_name of this User. # noqa: E501 - :return: The last_name of this User. + + :return: The last_name of this User. # noqa: E501 :rtype: str """ return self._last_name @last_name.setter def last_name(self, last_name): - """ - Sets the last_name of this User. + """Sets the last_name of this User. - :param last_name: The last_name of this User. + + :param last_name: The last_name of this User. # noqa: E501 :type: str """ @@ -170,20 +168,20 @@ class User(object): @property def email(self): - """ - Gets the email of this User. + """Gets the email of this User. # noqa: E501 - :return: The email of this User. + + :return: The email of this User. # noqa: E501 :rtype: str """ return self._email @email.setter def email(self, email): - """ - Sets the email of this User. + """Sets the email of this User. - :param email: The email of this User. + + :param email: The email of this User. # noqa: E501 :type: str """ @@ -191,20 +189,20 @@ class User(object): @property def password(self): - """ - Gets the password of this User. + """Gets the password of this User. # noqa: E501 - :return: The password of this User. + + :return: The password of this User. # noqa: E501 :rtype: str """ return self._password @password.setter def password(self, password): - """ - Sets the password of this User. + """Sets the password of this User. - :param password: The password of this User. + + :param password: The password of this User. # noqa: E501 :type: str """ @@ -212,20 +210,20 @@ class User(object): @property def phone(self): - """ - Gets the phone of this User. + """Gets the phone of this User. # noqa: E501 - :return: The phone of this User. + + :return: The phone of this User. # noqa: E501 :rtype: str """ return self._phone @phone.setter def phone(self, phone): - """ - Sets the phone of this User. + """Sets the phone of this User. - :param phone: The phone of this User. + + :param phone: The phone of this User. # noqa: E501 :type: str """ @@ -233,34 +231,32 @@ class User(object): @property def user_status(self): - """ - Gets the user_status of this User. - User Status + """Gets the user_status of this User. # noqa: E501 - :return: The user_status of this User. + User Status # noqa: E501 + + :return: The user_status of this User. # noqa: E501 :rtype: int """ return self._user_status @user_status.setter def user_status(self, user_status): - """ - Sets the user_status of this User. - User Status + """Sets the user_status of this User. - :param user_status: The user_status of this User. + User Status # noqa: E501 + + :param user_status: The user_status of this User. # noqa: E501 :type: int """ self._user_status = user_status def to_dict(self): - """ - Returns the model properties as a dict - """ + """Returns the model properties as a dict""" result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -281,28 +277,20 @@ class User(object): return result def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """Returns true if both objects are equal""" if not isinstance(other, User): return False return self.__dict__ == other.__dict__ def __ne__(self, other): - """ - Returns true if both objects are not equal - """ + """Returns true if both objects are not equal""" return not self == other diff --git a/samples/client/petstore/python/petstore_api/rest.py b/samples/client/petstore/python/petstore_api/rest.py index 5a73a2b908c..ef55c4ea44a 100644 --- a/samples/client/petstore/python/petstore_api/rest.py +++ b/samples/client/petstore/python/petstore_api/rest.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -15,13 +15,13 @@ from __future__ import absolute_import import io import json -import ssl -import certifi import logging import re +import ssl +import certifi # python 2 and python 3 compatibility library -from six import PY3 +import six from six.moves.urllib.parse import urlencode try: @@ -42,15 +42,11 @@ class RESTResponse(io.IOBase): self.data = resp.data def getheaders(self): - """ - Returns a dictionary of the response headers. - """ + """Returns a dictionary of the response headers.""" return self.urllib3_response.getheaders() def getheader(self, name, default=None): - """ - Returns a given response header. - """ + """Returns a given response header.""" return self.urllib3_response.getheader(name, default) @@ -58,10 +54,10 @@ class RESTClientObject(object): def __init__(self, configuration, pools_size=4, maxsize=None): # urllib3.PoolManager will pass all kw parameters to connectionpool - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 - # maxsize is the number of requests to host that are allowed in parallel - # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 # cert_reqs if configuration.verify_ssl: @@ -78,7 +74,7 @@ class RESTClientObject(object): addition_pool_args = {} if configuration.assert_hostname is not None: - addition_pool_args['assert_hostname'] = configuration.assert_hostname + addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 if maxsize is None: if configuration.connection_pool_maxsize is not None: @@ -110,8 +106,10 @@ class RESTClientObject(object): ) def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, _request_timeout=None): - """ + body=None, post_params=None, _preload_content=True, + _request_timeout=None): + """Perform requests. + :param method: http request method :param url: http request url :param query_params: query parameters in the url @@ -120,13 +118,17 @@ class RESTClientObject(object): :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without - reading/decoding response data. Default is True. - :param _request_timeout: timeout setting for this request. If one number provided, it will be total request - timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', + 'PATCH', 'OPTIONS'] if post_params and body: raise ValueError( @@ -138,10 +140,12 @@ class RESTClientObject(object): timeout = None if _request_timeout: - if isinstance(_request_timeout, (int, ) if PY3 else (int, long)): + if isinstance(_request_timeout, (int, ) if six.PY3 else (int, long)): # noqa: E501,F821 timeout = urllib3.Timeout(total=_request_timeout) - elif isinstance(_request_timeout, tuple) and len(_request_timeout) == 2: - timeout = urllib3.Timeout(connect=_request_timeout[0], read=_request_timeout[1]) + elif (isinstance(_request_timeout, tuple) and + len(_request_timeout) == 2): + timeout = urllib3.Timeout( + connect=_request_timeout[0], read=_request_timeout[1]) if 'Content-Type' not in headers: headers['Content-Type'] = 'application/json' @@ -155,42 +159,48 @@ class RESTClientObject(object): request_body = None if body is not None: request_body = json.dumps(body) - r = self.pool_manager.request(method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': - r = self.pool_manager.request(method, url, - fields=post_params, - encode_multipart=False, - preload_content=_preload_content, - timeout=timeout, - headers=headers) + r = self.pool_manager.request( + method, url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + r = self.pool_manager.request( + method, url, + fields=post_params, + encode_multipart=False, + preload_content=_preload_content, + timeout=timeout, + headers=headers) elif headers['Content-Type'] == 'multipart/form-data': - # must del headers['Content-Type'], or the correct Content-Type - # which generated by urllib3 will be overwritten. + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. del headers['Content-Type'] - r = self.pool_manager.request(method, url, - fields=post_params, - encode_multipart=True, - preload_content=_preload_content, - timeout=timeout, - headers=headers) + r = self.pool_manager.request( + method, url, + fields=post_params, + encode_multipart=True, + preload_content=_preload_content, + timeout=timeout, + headers=headers) # Pass a `string` parameter directly in the body to support - # other content types than Json when `body` argument is provided - # in serialized form + # other content types than Json when `body` argument is + # provided in serialized form elif isinstance(body, str): request_body = body - r = self.pool_manager.request(method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) + r = self.pool_manager.request( + method, url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers) else: # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided arguments. - Please check that your arguments match declared content type.""" + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: @@ -208,7 +218,7 @@ class RESTClientObject(object): # In the python 3, the response.data is bytes. # we need to decode it to string. - if PY3: + if six.PY3: r.data = r.data.decode('utf8') # log response body @@ -219,22 +229,24 @@ class RESTClientObject(object): return r - def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): + def GET(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): return self.request("GET", url, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout, query_params=query_params) - def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): + def HEAD(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): return self.request("HEAD", url, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout, query_params=query_params) - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): return self.request("OPTIONS", url, headers=headers, query_params=query_params, @@ -243,7 +255,8 @@ class RESTClientObject(object): _request_timeout=_request_timeout, body=body) - def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None): + def DELETE(self, url, headers=None, query_params=None, body=None, + _preload_content=True, _request_timeout=None): return self.request("DELETE", url, headers=headers, query_params=query_params, @@ -251,8 +264,8 @@ class RESTClientObject(object): _request_timeout=_request_timeout, body=body) - def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def POST(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): return self.request("POST", url, headers=headers, query_params=query_params, @@ -261,8 +274,8 @@ class RESTClientObject(object): _request_timeout=_request_timeout, body=body) - def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def PUT(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): return self.request("PUT", url, headers=headers, query_params=query_params, @@ -271,8 +284,8 @@ class RESTClientObject(object): _request_timeout=_request_timeout, body=body) - def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def PATCH(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): return self.request("PATCH", url, headers=headers, query_params=query_params, @@ -297,13 +310,12 @@ class ApiException(Exception): self.headers = None def __str__(self): - """ - Custom error messages for exception - """ + """Custom error messages for exception""" error_message = "({0})\n"\ "Reason: {1}\n".format(self.status, self.reason) if self.headers: - error_message += "HTTP response headers: {0}\n".format(self.headers) + error_message += "HTTP response headers: {0}\n".format( + self.headers) if self.body: error_message += "HTTP response body: {0}\n".format(self.body) diff --git a/samples/client/petstore/python/setup.py b/samples/client/petstore/python/setup.py index 187e1b1636f..6831357735b 100644 --- a/samples/client/petstore/python/setup.py +++ b/samples/client/petstore/python/setup.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -11,8 +11,7 @@ """ -import sys -from setuptools import setup, find_packages +from setuptools import setup, find_packages # noqa: H301 NAME = "petstore-api" VERSION = "1.0.0" @@ -36,6 +35,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. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 """ ) diff --git a/samples/client/petstore/python/test/test_additional_properties_class.py b/samples/client/petstore/python/test/test_additional_properties_class.py index 36fa7fb3a18..77ccb73b028 100644 --- a/samples/client/petstore/python/test/test_additional_properties_class.py +++ b/samples/client/petstore/python/test/test_additional_properties_class.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.additional_properties_class import AdditionalPropertiesClass # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.additional_properties_class import AdditionalPropertiesClass class TestAdditionalPropertiesClass(unittest.TestCase): - """ AdditionalPropertiesClass unit test stubs """ + """AdditionalPropertiesClass unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestAdditionalPropertiesClass(unittest.TestCase): pass def testAdditionalPropertiesClass(self): - """ - Test AdditionalPropertiesClass - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.additional_properties_class.AdditionalPropertiesClass() + """Test AdditionalPropertiesClass""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.additional_properties_class.AdditionalPropertiesClass() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_animal.py b/samples/client/petstore/python/test/test_animal.py index 67eba1eaffb..eb5f7cb930e 100644 --- a/samples/client/petstore/python/test/test_animal.py +++ b/samples/client/petstore/python/test/test_animal.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.animal import Animal # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.animal import Animal class TestAnimal(unittest.TestCase): - """ Animal unit test stubs """ + """Animal unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestAnimal(unittest.TestCase): pass def testAnimal(self): - """ - Test Animal - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.animal.Animal() + """Test Animal""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.animal.Animal() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_animal_farm.py b/samples/client/petstore/python/test/test_animal_farm.py index d8610735ec6..8f79946fa73 100644 --- a/samples/client/petstore/python/test/test_animal_farm.py +++ b/samples/client/petstore/python/test/test_animal_farm.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.animal_farm import AnimalFarm # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.animal_farm import AnimalFarm class TestAnimalFarm(unittest.TestCase): - """ AnimalFarm unit test stubs """ + """AnimalFarm unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestAnimalFarm(unittest.TestCase): pass def testAnimalFarm(self): - """ - Test AnimalFarm - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.animal_farm.AnimalFarm() + """Test AnimalFarm""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.animal_farm.AnimalFarm() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_another_fake_api.py b/samples/client/petstore/python/test/test_another_fake_api.py index 9f562fe1134..c294aa90359 100644 --- a/samples/client/petstore/python/test/test_another_fake_api.py +++ b/samples/client/petstore/python/test/test_another_fake_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,29 +13,26 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.another_fake_api import AnotherFakeApi # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.another_fake_api import AnotherFakeApi class TestAnotherFakeApi(unittest.TestCase): - """ AnotherFakeApi unit test stubs """ + """AnotherFakeApi unit test stubs""" def setUp(self): - self.api = petstore_api.apis.another_fake_api.AnotherFakeApi() + self.api = petstore_api.api.another_fake_api.AnotherFakeApi() # noqa: E501 def tearDown(self): pass def test_test_special_tags(self): - """ - Test case for test_special_tags + """Test case for test_special_tags - To test special tags + To test special tags # noqa: E501 """ pass diff --git a/samples/client/petstore/python/test/test_api_response.py b/samples/client/petstore/python/test/test_api_response.py index 766c0a93f85..97ed978a5f6 100644 --- a/samples/client/petstore/python/test/test_api_response.py +++ b/samples/client/petstore/python/test/test_api_response.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.api_response import ApiResponse # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.api_response import ApiResponse class TestApiResponse(unittest.TestCase): - """ ApiResponse unit test stubs """ + """ApiResponse unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestApiResponse(unittest.TestCase): pass def testApiResponse(self): - """ - Test ApiResponse - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.api_response.ApiResponse() + """Test ApiResponse""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.api_response.ApiResponse() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_array_of_array_of_number_only.py b/samples/client/petstore/python/test/test_array_of_array_of_number_only.py index d095b23abf2..b617ed2cd3e 100644 --- a/samples/client/petstore/python/test/test_array_of_array_of_number_only.py +++ b/samples/client/petstore/python/test/test_array_of_array_of_number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly class TestArrayOfArrayOfNumberOnly(unittest.TestCase): - """ ArrayOfArrayOfNumberOnly unit test stubs """ + """ArrayOfArrayOfNumberOnly unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestArrayOfArrayOfNumberOnly(unittest.TestCase): pass def testArrayOfArrayOfNumberOnly(self): - """ - Test ArrayOfArrayOfNumberOnly - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.array_of_array_of_number_only.ArrayOfArrayOfNumberOnly() + """Test ArrayOfArrayOfNumberOnly""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.array_of_array_of_number_only.ArrayOfArrayOfNumberOnly() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_array_of_number_only.py b/samples/client/petstore/python/test/test_array_of_number_only.py index 24c5adb8299..7439364c7b1 100644 --- a/samples/client/petstore/python/test/test_array_of_number_only.py +++ b/samples/client/petstore/python/test/test_array_of_number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.array_of_number_only import ArrayOfNumberOnly # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.array_of_number_only import ArrayOfNumberOnly class TestArrayOfNumberOnly(unittest.TestCase): - """ ArrayOfNumberOnly unit test stubs """ + """ArrayOfNumberOnly unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestArrayOfNumberOnly(unittest.TestCase): pass def testArrayOfNumberOnly(self): - """ - Test ArrayOfNumberOnly - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.array_of_number_only.ArrayOfNumberOnly() + """Test ArrayOfNumberOnly""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.array_of_number_only.ArrayOfNumberOnly() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_array_test.py b/samples/client/petstore/python/test/test_array_test.py index 99c0f4d2b67..d7feb2ac8f4 100644 --- a/samples/client/petstore/python/test/test_array_test.py +++ b/samples/client/petstore/python/test/test_array_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.array_test import ArrayTest # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.array_test import ArrayTest class TestArrayTest(unittest.TestCase): - """ ArrayTest unit test stubs """ + """ArrayTest unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestArrayTest(unittest.TestCase): pass def testArrayTest(self): - """ - Test ArrayTest - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.array_test.ArrayTest() + """Test ArrayTest""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.array_test.ArrayTest() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_capitalization.py b/samples/client/petstore/python/test/test_capitalization.py index f903de14261..4ac874e817c 100644 --- a/samples/client/petstore/python/test/test_capitalization.py +++ b/samples/client/petstore/python/test/test_capitalization.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.capitalization import Capitalization # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.capitalization import Capitalization class TestCapitalization(unittest.TestCase): - """ Capitalization unit test stubs """ + """Capitalization unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestCapitalization(unittest.TestCase): pass def testCapitalization(self): - """ - Test Capitalization - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.capitalization.Capitalization() + """Test Capitalization""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.capitalization.Capitalization() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_cat.py b/samples/client/petstore/python/test/test_cat.py index 39a2d63b147..370f1081383 100644 --- a/samples/client/petstore/python/test/test_cat.py +++ b/samples/client/petstore/python/test/test_cat.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.cat import Cat # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.cat import Cat class TestCat(unittest.TestCase): - """ Cat unit test stubs """ + """Cat unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestCat(unittest.TestCase): pass def testCat(self): - """ - Test Cat - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.cat.Cat() + """Test Cat""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.cat.Cat() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_category.py b/samples/client/petstore/python/test/test_category.py index 87868e6bb8f..7a9e40a1f65 100644 --- a/samples/client/petstore/python/test/test_category.py +++ b/samples/client/petstore/python/test/test_category.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.category import Category # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.category import Category class TestCategory(unittest.TestCase): - """ Category unit test stubs """ + """Category unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestCategory(unittest.TestCase): pass def testCategory(self): - """ - Test Category - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.category.Category() + """Test Category""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.category.Category() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_class_model.py b/samples/client/petstore/python/test/test_class_model.py index b9afda56e48..a42127abf50 100644 --- a/samples/client/petstore/python/test/test_class_model.py +++ b/samples/client/petstore/python/test/test_class_model.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.class_model import ClassModel # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.class_model import ClassModel class TestClassModel(unittest.TestCase): - """ ClassModel unit test stubs """ + """ClassModel unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestClassModel(unittest.TestCase): pass def testClassModel(self): - """ - Test ClassModel - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.class_model.ClassModel() + """Test ClassModel""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.class_model.ClassModel() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_client.py b/samples/client/petstore/python/test/test_client.py index 07af5e40c3a..81df726dbfc 100644 --- a/samples/client/petstore/python/test/test_client.py +++ b/samples/client/petstore/python/test/test_client.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.client import Client # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.client import Client class TestClient(unittest.TestCase): - """ Client unit test stubs """ + """Client unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestClient(unittest.TestCase): pass def testClient(self): - """ - Test Client - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.client.Client() + """Test Client""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.client.Client() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_dog.py b/samples/client/petstore/python/test/test_dog.py index 3f1654ffc88..ae13869b99f 100644 --- a/samples/client/petstore/python/test/test_dog.py +++ b/samples/client/petstore/python/test/test_dog.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.dog import Dog # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.dog import Dog class TestDog(unittest.TestCase): - """ Dog unit test stubs """ + """Dog unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestDog(unittest.TestCase): pass def testDog(self): - """ - Test Dog - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.dog.Dog() + """Test Dog""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.dog.Dog() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_enum_arrays.py b/samples/client/petstore/python/test/test_enum_arrays.py index 844c7f92294..144e48883e5 100644 --- a/samples/client/petstore/python/test/test_enum_arrays.py +++ b/samples/client/petstore/python/test/test_enum_arrays.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.enum_arrays import EnumArrays # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.enum_arrays import EnumArrays class TestEnumArrays(unittest.TestCase): - """ EnumArrays unit test stubs """ + """EnumArrays unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestEnumArrays(unittest.TestCase): pass def testEnumArrays(self): - """ - Test EnumArrays - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.enum_arrays.EnumArrays() + """Test EnumArrays""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.enum_arrays.EnumArrays() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_enum_class.py b/samples/client/petstore/python/test/test_enum_class.py index 71c9461b299..a47581d2820 100644 --- a/samples/client/petstore/python/test/test_enum_class.py +++ b/samples/client/petstore/python/test/test_enum_class.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.enum_class import EnumClass # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.enum_class import EnumClass class TestEnumClass(unittest.TestCase): - """ EnumClass unit test stubs """ + """EnumClass unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestEnumClass(unittest.TestCase): pass def testEnumClass(self): - """ - Test EnumClass - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.enum_class.EnumClass() + """Test EnumClass""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.enum_class.EnumClass() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_enum_test.py b/samples/client/petstore/python/test/test_enum_test.py index 3f3f5f51159..7487efe9fa1 100644 --- a/samples/client/petstore/python/test/test_enum_test.py +++ b/samples/client/petstore/python/test/test_enum_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.enum_test import EnumTest # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.enum_test import EnumTest class TestEnumTest(unittest.TestCase): - """ EnumTest unit test stubs """ + """EnumTest unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestEnumTest(unittest.TestCase): pass def testEnumTest(self): - """ - Test EnumTest - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.enum_test.EnumTest() + """Test EnumTest""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.enum_test.EnumTest() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_fake_api.py b/samples/client/petstore/python/test/test_fake_api.py index 575978dff3f..00473d4a13b 100644 --- a/samples/client/petstore/python/test/test_fake_api.py +++ b/samples/client/petstore/python/test/test_fake_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,45 +13,78 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.fake_api import FakeApi # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.fake_api import FakeApi class TestFakeApi(unittest.TestCase): - """ FakeApi unit test stubs """ + """FakeApi unit test stubs""" def setUp(self): - self.api = petstore_api.apis.fake_api.FakeApi() + self.api = petstore_api.api.fake_api.FakeApi() # noqa: E501 def tearDown(self): pass - def test_test_client_model(self): - """ - Test case for test_client_model + def test_fake_outer_boolean_serialize(self): + """Test case for fake_outer_boolean_serialize - To test \"client\" model + """ + pass + + def test_fake_outer_composite_serialize(self): + """Test case for fake_outer_composite_serialize + + """ + pass + + def test_fake_outer_number_serialize(self): + """Test case for fake_outer_number_serialize + + """ + pass + + def test_fake_outer_string_serialize(self): + """Test case for fake_outer_string_serialize + + """ + pass + + def test_test_client_model(self): + """Test case for test_client_model + + To test \"client\" model # noqa: E501 """ pass def test_test_endpoint_parameters(self): - """ - Test case for test_endpoint_parameters + """Test case for test_endpoint_parameters - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 """ pass def test_test_enum_parameters(self): - """ - Test case for test_enum_parameters + """Test case for test_enum_parameters - To test enum parameters + To test enum parameters # noqa: E501 + """ + pass + + def test_test_inline_additional_properties(self): + """Test case for test_inline_additional_properties + + test inline additionalProperties # noqa: E501 + """ + pass + + def test_test_json_form_data(self): + """Test case for test_json_form_data + + test json serialization of form data # noqa: E501 """ pass diff --git a/samples/client/petstore/python/test/test_fake_classname_tags123_api.py b/samples/client/petstore/python/test/test_fake_classname_tags123_api.py deleted file mode 100644 index 2dab6a38fc5..00000000000 --- a/samples/client/petstore/python/test/test_fake_classname_tags123_api.py +++ /dev/null @@ -1,44 +0,0 @@ -# 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 -""" - - -from __future__ import absolute_import - -import os -import sys -import unittest - -import petstore_api -from petstore_api.rest import ApiException -from petstore_api.apis.fake_classname_tags123_api import FakeClassnameTags123Api - - -class TestFakeClassnameTags123Api(unittest.TestCase): - """ FakeClassnameTags123Api unit test stubs """ - - def setUp(self): - self.api = petstore_api.apis.fake_classname_tags123_api.FakeClassnameTags123Api() - - def tearDown(self): - pass - - def test_test_classname(self): - """ - Test case for test_classname - - To test class name in snake case - """ - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/client/petstore/python/test/test_fake_classname_tags_123_api.py b/samples/client/petstore/python/test/test_fake_classname_tags_123_api.py index 7a11a2378bf..8f40062a929 100644 --- a/samples/client/petstore/python/test/test_fake_classname_tags_123_api.py +++ b/samples/client/petstore/python/test/test_fake_classname_tags_123_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,29 +13,26 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.fake_classname_tags_123_api import FakeClassnameTags123Api # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.fake_classname_tags_123_api import FakeClassnameTags123Api class TestFakeClassnameTags123Api(unittest.TestCase): - """ FakeClassnameTags123Api unit test stubs """ + """FakeClassnameTags123Api unit test stubs""" def setUp(self): - self.api = petstore_api.apis.fake_classname_tags_123_api.FakeClassnameTags123Api() + self.api = petstore_api.api.fake_classname_tags_123_api.FakeClassnameTags123Api() # noqa: E501 def tearDown(self): pass def test_test_classname(self): - """ - Test case for test_classname + """Test case for test_classname - To test class name in snake case + To test class name in snake case # noqa: E501 """ pass diff --git a/samples/client/petstore/python/test/test_format_test.py b/samples/client/petstore/python/test/test_format_test.py index a9e92f0d276..59809b9f442 100644 --- a/samples/client/petstore/python/test/test_format_test.py +++ b/samples/client/petstore/python/test/test_format_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.format_test import FormatTest # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.format_test import FormatTest class TestFormatTest(unittest.TestCase): - """ FormatTest unit test stubs """ + """FormatTest unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestFormatTest(unittest.TestCase): pass def testFormatTest(self): - """ - Test FormatTest - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.format_test.FormatTest() + """Test FormatTest""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.format_test.FormatTest() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_has_only_read_only.py b/samples/client/petstore/python/test/test_has_only_read_only.py index 454a17429c5..26d14aef1f8 100644 --- a/samples/client/petstore/python/test/test_has_only_read_only.py +++ b/samples/client/petstore/python/test/test_has_only_read_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.has_only_read_only import HasOnlyReadOnly # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.has_only_read_only import HasOnlyReadOnly class TestHasOnlyReadOnly(unittest.TestCase): - """ HasOnlyReadOnly unit test stubs """ + """HasOnlyReadOnly unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestHasOnlyReadOnly(unittest.TestCase): pass def testHasOnlyReadOnly(self): - """ - Test HasOnlyReadOnly - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.has_only_read_only.HasOnlyReadOnly() + """Test HasOnlyReadOnly""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.has_only_read_only.HasOnlyReadOnly() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_list.py b/samples/client/petstore/python/test/test_list.py index 1c55f1ae425..c2cca419f37 100644 --- a/samples/client/petstore/python/test/test_list.py +++ b/samples/client/petstore/python/test/test_list.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.list import List # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.list import List class TestList(unittest.TestCase): - """ List unit test stubs """ + """List unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestList(unittest.TestCase): pass def testList(self): - """ - Test List - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.list.List() + """Test List""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.list.List() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_map_test.py b/samples/client/petstore/python/test/test_map_test.py index 5eadb021be1..155797d9b2d 100644 --- a/samples/client/petstore/python/test/test_map_test.py +++ b/samples/client/petstore/python/test/test_map_test.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.map_test import MapTest # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.map_test import MapTest class TestMapTest(unittest.TestCase): - """ MapTest unit test stubs """ + """MapTest unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestMapTest(unittest.TestCase): pass def testMapTest(self): - """ - Test MapTest - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.map_test.MapTest() + """Test MapTest""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.map_test.MapTest() # noqa: E501 pass 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 index 8b2ee454655..12a56764080 100644 --- 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 @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass # noqa: E501 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 """ + """MixedPropertiesAndAdditionalPropertiesClass unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestMixedPropertiesAndAdditionalPropertiesClass(unittest.TestCase): pass def testMixedPropertiesAndAdditionalPropertiesClass(self): - """ - Test MixedPropertiesAndAdditionalPropertiesClass - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.mixed_properties_and_additional_properties_class.MixedPropertiesAndAdditionalPropertiesClass() + """Test MixedPropertiesAndAdditionalPropertiesClass""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.mixed_properties_and_additional_properties_class.MixedPropertiesAndAdditionalPropertiesClass() # noqa: E501 pass 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 c3d0367d39a..f577dd42144 100644 --- a/samples/client/petstore/python/test/test_model_200_response.py +++ b/samples/client/petstore/python/test/test_model_200_response.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.model_200_response import Model200Response # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.model_200_response import Model200Response class TestModel200Response(unittest.TestCase): - """ Model200Response unit test stubs """ + """Model200Response unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestModel200Response(unittest.TestCase): pass def testModel200Response(self): - """ - Test Model200Response - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.model_200_response.Model200Response() + """Test Model200Response""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.model_200_response.Model200Response() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_model_return.py b/samples/client/petstore/python/test/test_model_return.py index 13c683ee46a..64cf27f63ab 100644 --- a/samples/client/petstore/python/test/test_model_return.py +++ b/samples/client/petstore/python/test/test_model_return.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.model_return import ModelReturn # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.model_return import ModelReturn class TestModelReturn(unittest.TestCase): - """ ModelReturn unit test stubs """ + """ModelReturn unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestModelReturn(unittest.TestCase): pass def testModelReturn(self): - """ - Test ModelReturn - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.model_return.ModelReturn() + """Test ModelReturn""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.model_return.ModelReturn() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_name.py b/samples/client/petstore/python/test/test_name.py index 2b972303fb1..beba143f39c 100644 --- a/samples/client/petstore/python/test/test_name.py +++ b/samples/client/petstore/python/test/test_name.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.name import Name # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.name import Name class TestName(unittest.TestCase): - """ Name unit test stubs """ + """Name unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestName(unittest.TestCase): pass def testName(self): - """ - Test Name - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.name.Name() + """Test Name""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.name.Name() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_number_only.py b/samples/client/petstore/python/test/test_number_only.py index a05bfd5ffe2..f2600c79526 100644 --- a/samples/client/petstore/python/test/test_number_only.py +++ b/samples/client/petstore/python/test/test_number_only.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.number_only import NumberOnly # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.number_only import NumberOnly class TestNumberOnly(unittest.TestCase): - """ NumberOnly unit test stubs """ + """NumberOnly unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestNumberOnly(unittest.TestCase): pass def testNumberOnly(self): - """ - Test NumberOnly - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.number_only.NumberOnly() + """Test NumberOnly""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.number_only.NumberOnly() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_order.py b/samples/client/petstore/python/test/test_order.py index cc181aad7da..ed4f8c7d161 100644 --- a/samples/client/petstore/python/test/test_order.py +++ b/samples/client/petstore/python/test/test_order.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.order import Order # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.order import Order class TestOrder(unittest.TestCase): - """ Order unit test stubs """ + """Order unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestOrder(unittest.TestCase): pass def testOrder(self): - """ - Test Order - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.order.Order() + """Test Order""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.order.Order() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_outer_boolean.py b/samples/client/petstore/python/test/test_outer_boolean.py index 082b05cf928..4a7e446693e 100644 --- a/samples/client/petstore/python/test/test_outer_boolean.py +++ b/samples/client/petstore/python/test/test_outer_boolean.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.outer_boolean import OuterBoolean # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.outer_boolean import OuterBoolean class TestOuterBoolean(unittest.TestCase): - """ OuterBoolean unit test stubs """ + """OuterBoolean unit test stubs""" def setUp(self): pass @@ -32,10 +30,10 @@ class TestOuterBoolean(unittest.TestCase): pass def testOuterBoolean(self): - """ - Test OuterBoolean - """ - model = petstore_api.models.outer_boolean.OuterBoolean() + """Test OuterBoolean""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.outer_boolean.OuterBoolean() # noqa: E501 + pass if __name__ == '__main__': diff --git a/samples/client/petstore/python/test/test_outer_composite.py b/samples/client/petstore/python/test/test_outer_composite.py index fa084c04bf2..e444e695fe8 100644 --- a/samples/client/petstore/python/test/test_outer_composite.py +++ b/samples/client/petstore/python/test/test_outer_composite.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.outer_composite import OuterComposite # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.outer_composite import OuterComposite class TestOuterComposite(unittest.TestCase): - """ OuterComposite unit test stubs """ + """OuterComposite unit test stubs""" def setUp(self): pass @@ -32,10 +30,10 @@ class TestOuterComposite(unittest.TestCase): pass def testOuterComposite(self): - """ - Test OuterComposite - """ - model = petstore_api.models.outer_composite.OuterComposite() + """Test OuterComposite""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.outer_composite.OuterComposite() # noqa: E501 + pass if __name__ == '__main__': diff --git a/samples/client/petstore/python/test/test_outer_enum.py b/samples/client/petstore/python/test/test_outer_enum.py index 203212883e5..e3fb15e1b6b 100644 --- a/samples/client/petstore/python/test/test_outer_enum.py +++ b/samples/client/petstore/python/test/test_outer_enum.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.outer_enum import OuterEnum # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.outer_enum import OuterEnum class TestOuterEnum(unittest.TestCase): - """ OuterEnum unit test stubs """ + """OuterEnum unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestOuterEnum(unittest.TestCase): pass def testOuterEnum(self): - """ - Test OuterEnum - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.outer_enum.OuterEnum() + """Test OuterEnum""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.outer_enum.OuterEnum() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_outer_number.py b/samples/client/petstore/python/test/test_outer_number.py index 4019b356bc4..da5d3ceee61 100644 --- a/samples/client/petstore/python/test/test_outer_number.py +++ b/samples/client/petstore/python/test/test_outer_number.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.outer_number import OuterNumber # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.outer_number import OuterNumber class TestOuterNumber(unittest.TestCase): - """ OuterNumber unit test stubs """ + """OuterNumber unit test stubs""" def setUp(self): pass @@ -32,10 +30,10 @@ class TestOuterNumber(unittest.TestCase): pass def testOuterNumber(self): - """ - Test OuterNumber - """ - model = petstore_api.models.outer_number.OuterNumber() + """Test OuterNumber""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.outer_number.OuterNumber() # noqa: E501 + pass if __name__ == '__main__': diff --git a/samples/client/petstore/python/test/test_outer_string.py b/samples/client/petstore/python/test/test_outer_string.py index a23c7815efe..02b4967e3b9 100644 --- a/samples/client/petstore/python/test/test_outer_string.py +++ b/samples/client/petstore/python/test/test_outer_string.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.outer_string import OuterString # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.outer_string import OuterString class TestOuterString(unittest.TestCase): - """ OuterString unit test stubs """ + """OuterString unit test stubs""" def setUp(self): pass @@ -32,10 +30,10 @@ class TestOuterString(unittest.TestCase): pass def testOuterString(self): - """ - Test OuterString - """ - model = petstore_api.models.outer_string.OuterString() + """Test OuterString""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.outer_string.OuterString() # noqa: E501 + pass if __name__ == '__main__': diff --git a/samples/client/petstore/python/test/test_pet.py b/samples/client/petstore/python/test/test_pet.py index 7da7d887e42..d8df24f92b1 100644 --- a/samples/client/petstore/python/test/test_pet.py +++ b/samples/client/petstore/python/test/test_pet.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.pet import Pet # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.pet import Pet class TestPet(unittest.TestCase): - """ Pet unit test stubs """ + """Pet unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestPet(unittest.TestCase): pass def testPet(self): - """ - Test Pet - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.pet.Pet() + """Test Pet""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.pet.Pet() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_pet_api.py b/samples/client/petstore/python/test/test_pet_api.py index 1eafc35b28c..1e2dd1c42b6 100644 --- a/samples/client/petstore/python/test/test_pet_api.py +++ b/samples/client/petstore/python/test/test_pet_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,85 +13,75 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.pet_api import PetApi # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.pet_api import PetApi class TestPetApi(unittest.TestCase): - """ PetApi unit test stubs """ + """PetApi unit test stubs""" def setUp(self): - self.api = petstore_api.apis.pet_api.PetApi() + self.api = petstore_api.api.pet_api.PetApi() # noqa: E501 def tearDown(self): pass def test_add_pet(self): - """ - Test case for add_pet + """Test case for add_pet - Add a new pet to the store + Add a new pet to the store # noqa: E501 """ pass def test_delete_pet(self): - """ - Test case for delete_pet + """Test case for delete_pet - Deletes a pet + Deletes a pet # noqa: E501 """ pass def test_find_pets_by_status(self): - """ - Test case for find_pets_by_status + """Test case for find_pets_by_status - Finds Pets by status + Finds Pets by status # noqa: E501 """ pass def test_find_pets_by_tags(self): - """ - Test case for find_pets_by_tags + """Test case for find_pets_by_tags - Finds Pets by tags + Finds Pets by tags # noqa: E501 """ pass def test_get_pet_by_id(self): - """ - Test case for get_pet_by_id + """Test case for get_pet_by_id - Find pet by ID + Find pet by ID # noqa: E501 """ pass def test_update_pet(self): - """ - Test case for update_pet + """Test case for update_pet - Update an existing pet + Update an existing pet # noqa: E501 """ pass def test_update_pet_with_form(self): - """ - Test case for update_pet_with_form + """Test case for update_pet_with_form - Updates a pet in the store with form data + Updates a pet in the store with form data # noqa: E501 """ pass def test_upload_file(self): - """ - Test case for upload_file + """Test case for upload_file - uploads an image + uploads an image # noqa: E501 """ pass diff --git a/samples/client/petstore/python/test/test_read_only_first.py b/samples/client/petstore/python/test/test_read_only_first.py index 42a402f7658..94bf3d127de 100644 --- a/samples/client/petstore/python/test/test_read_only_first.py +++ b/samples/client/petstore/python/test/test_read_only_first.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.read_only_first import ReadOnlyFirst # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.read_only_first import ReadOnlyFirst class TestReadOnlyFirst(unittest.TestCase): - """ ReadOnlyFirst unit test stubs """ + """ReadOnlyFirst unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestReadOnlyFirst(unittest.TestCase): pass def testReadOnlyFirst(self): - """ - Test ReadOnlyFirst - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.read_only_first.ReadOnlyFirst() + """Test ReadOnlyFirst""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.read_only_first.ReadOnlyFirst() # noqa: E501 pass 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 f6e59a4b3ce..002f660cc26 100644 --- a/samples/client/petstore/python/test/test_special_model_name.py +++ b/samples/client/petstore/python/test/test_special_model_name.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.special_model_name import SpecialModelName # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.special_model_name import SpecialModelName class TestSpecialModelName(unittest.TestCase): - """ SpecialModelName unit test stubs """ + """SpecialModelName unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestSpecialModelName(unittest.TestCase): pass def testSpecialModelName(self): - """ - Test SpecialModelName - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.special_model_name.SpecialModelName() + """Test SpecialModelName""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.special_model_name.SpecialModelName() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_store_api.py b/samples/client/petstore/python/test/test_store_api.py index f131b6068b2..537c1bc03f1 100644 --- a/samples/client/petstore/python/test/test_store_api.py +++ b/samples/client/petstore/python/test/test_store_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,53 +13,47 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.store_api import StoreApi # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.store_api import StoreApi class TestStoreApi(unittest.TestCase): - """ StoreApi unit test stubs """ + """StoreApi unit test stubs""" def setUp(self): - self.api = petstore_api.apis.store_api.StoreApi() + self.api = petstore_api.api.store_api.StoreApi() # noqa: E501 def tearDown(self): pass def test_delete_order(self): - """ - Test case for delete_order + """Test case for delete_order - Delete purchase order by ID + Delete purchase order by ID # noqa: E501 """ pass def test_get_inventory(self): - """ - Test case for get_inventory + """Test case for get_inventory - Returns pet inventories by status + Returns pet inventories by status # noqa: E501 """ pass def test_get_order_by_id(self): - """ - Test case for get_order_by_id + """Test case for get_order_by_id - Find purchase order by ID + Find purchase order by ID # noqa: E501 """ pass def test_place_order(self): - """ - Test case for place_order + """Test case for place_order - Place an order for a pet + Place an order for a pet # noqa: E501 """ pass diff --git a/samples/client/petstore/python/test/test_tag.py b/samples/client/petstore/python/test/test_tag.py index 0975bcf9b67..e9bc1d471d1 100644 --- a/samples/client/petstore/python/test/test_tag.py +++ b/samples/client/petstore/python/test/test_tag.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.tag import Tag # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.tag import Tag class TestTag(unittest.TestCase): - """ Tag unit test stubs """ + """Tag unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestTag(unittest.TestCase): pass def testTag(self): - """ - Test Tag - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.tag.Tag() + """Test Tag""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.tag.Tag() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_user.py b/samples/client/petstore/python/test/test_user.py index a2c2d941d44..3575746c00f 100644 --- a/samples/client/petstore/python/test/test_user.py +++ b/samples/client/petstore/python/test/test_user.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,17 +13,15 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.models.user import User # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.models.user import User class TestUser(unittest.TestCase): - """ User unit test stubs """ + """User unit test stubs""" def setUp(self): pass @@ -32,11 +30,9 @@ class TestUser(unittest.TestCase): pass def testUser(self): - """ - Test User - """ - # FIXME: construct object with required attributes - #model = petstore_api.models.user.User() + """Test User""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.models.user.User() # noqa: E501 pass diff --git a/samples/client/petstore/python/test/test_user_api.py b/samples/client/petstore/python/test/test_user_api.py index 3e0be964a2d..4ebd90f95e2 100644 --- a/samples/client/petstore/python/test/test_user_api.py +++ b/samples/client/petstore/python/test/test_user_api.py @@ -3,7 +3,7 @@ """ Swagger Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -13,85 +13,75 @@ from __future__ import absolute_import -import os -import sys import unittest import petstore_api +from petstore_api.api.user_api import UserApi # noqa: E501 from petstore_api.rest import ApiException -from petstore_api.apis.user_api import UserApi class TestUserApi(unittest.TestCase): - """ UserApi unit test stubs """ + """UserApi unit test stubs""" def setUp(self): - self.api = petstore_api.apis.user_api.UserApi() + self.api = petstore_api.api.user_api.UserApi() # noqa: E501 def tearDown(self): pass def test_create_user(self): - """ - Test case for create_user + """Test case for create_user - Create user + Create user # noqa: E501 """ pass def test_create_users_with_array_input(self): - """ - Test case for create_users_with_array_input + """Test case for create_users_with_array_input - Creates list of users with given input array + Creates list of users with given input array # noqa: E501 """ pass def test_create_users_with_list_input(self): - """ - Test case for create_users_with_list_input + """Test case for create_users_with_list_input - Creates list of users with given input array + Creates list of users with given input array # noqa: E501 """ pass def test_delete_user(self): - """ - Test case for delete_user + """Test case for delete_user - Delete user + Delete user # noqa: E501 """ pass def test_get_user_by_name(self): - """ - Test case for get_user_by_name + """Test case for get_user_by_name - Get user by user name + Get user by user name # noqa: E501 """ pass def test_login_user(self): - """ - Test case for login_user + """Test case for login_user - Logs user into the system + Logs user into the system # noqa: E501 """ pass def test_logout_user(self): - """ - Test case for logout_user + """Test case for logout_user - Logs out current logged in user session + Logs out current logged in user session # noqa: E501 """ pass def test_update_user(self): - """ - Test case for update_user + """Test case for update_user - Updated user + Updated user # noqa: E501 """ pass diff --git a/samples/client/petstore/python/test_python2.sh b/samples/client/petstore/python/test_python2.sh index e2492be49f6..c88094efc2d 100755 --- a/samples/client/petstore/python/test_python2.sh +++ b/samples/client/petstore/python/test_python2.sh @@ -23,6 +23,9 @@ python setup.py develop ### run tests nosetests +### static analysis of code +flake8 --show-source petstore_api/ + ### deactivate virtualenv #if [ $DEACTIVE == true ]; then # deactivate diff --git a/samples/client/petstore/python/test_python2_and_3.sh b/samples/client/petstore/python/test_python2_and_3.sh index b917ecad06a..a224ffe75dc 100755 --- a/samples/client/petstore/python/test_python2_and_3.sh +++ b/samples/client/petstore/python/test_python2_and_3.sh @@ -23,6 +23,9 @@ python setup.py develop ### run tests tox +### static analysis of code +flake8 --show-source petstore_api/ + ### deactivate virtualenv #if [ $DEACTIVE == true ]; then # deactivate diff --git a/samples/client/petstore/python/tests/test_api_client.py b/samples/client/petstore/python/tests/test_api_client.py index 0564a69686b..1e0a83accb1 100644 --- a/samples/client/petstore/python/tests/test_api_client.py +++ b/samples/client/petstore/python/tests/test_api_client.py @@ -1,5 +1,7 @@ # coding: utf-8 +# flake8: noqa + """ Run the tests. $ pip install nose (optional) diff --git a/samples/client/petstore/python/tests/test_api_exception.py b/samples/client/petstore/python/tests/test_api_exception.py index 82c825875d0..931dc34edfa 100644 --- a/samples/client/petstore/python/tests/test_api_exception.py +++ b/samples/client/petstore/python/tests/test_api_exception.py @@ -1,5 +1,7 @@ # coding: utf-8 +# flake8: noqa + """ Run the tests. $ pip install nose (optional) diff --git a/samples/client/petstore/python/tests/test_deserialization.py b/samples/client/petstore/python/tests/test_deserialization.py index 737ed9ea2cf..97d047563df 100644 --- a/samples/client/petstore/python/tests/test_deserialization.py +++ b/samples/client/petstore/python/tests/test_deserialization.py @@ -1,5 +1,7 @@ # coding: utf-8 +# flake8: noqa + """ Run the tests. $ pip install nose (optional) diff --git a/samples/client/petstore/python/tests/test_enum_arrays.py b/samples/client/petstore/python/tests/test_enum_arrays.py index 41e7dcb0a74..2f7e347f9c3 100644 --- a/samples/client/petstore/python/tests/test_enum_arrays.py +++ b/samples/client/petstore/python/tests/test_enum_arrays.py @@ -1,5 +1,7 @@ # coding: utf-8 +# flake8: noqa + """ Run the tests. $ pip install nose (optional) diff --git a/samples/client/petstore/python/tests/test_map_test.py b/samples/client/petstore/python/tests/test_map_test.py index 012b9254b47..a411a4e541b 100644 --- a/samples/client/petstore/python/tests/test_map_test.py +++ b/samples/client/petstore/python/tests/test_map_test.py @@ -1,5 +1,7 @@ # coding: utf-8 +# flake8: noqa + """ Run the tests. $ pip install nose (optional) diff --git a/samples/client/petstore/python/tests/test_order_model.py b/samples/client/petstore/python/tests/test_order_model.py index 710f3c175a9..31dc6e3661c 100644 --- a/samples/client/petstore/python/tests/test_order_model.py +++ b/samples/client/petstore/python/tests/test_order_model.py @@ -1,5 +1,7 @@ # coding: utf-8 +# flake8: noqa + """ Run the tests. $ pip install nose (optional) diff --git a/samples/client/petstore/python/tests/test_pet_api.py b/samples/client/petstore/python/tests/test_pet_api.py index 6dd6dce1d5a..1c5b2739062 100644 --- a/samples/client/petstore/python/tests/test_pet_api.py +++ b/samples/client/petstore/python/tests/test_pet_api.py @@ -1,5 +1,7 @@ # coding: utf-8 +# flake8: noqa + """ Run the tests. $ pip install nose (optional) diff --git a/samples/client/petstore/python/tests/test_pet_model.py b/samples/client/petstore/python/tests/test_pet_model.py index 3ecb5ec85ba..70ab1a007a0 100644 --- a/samples/client/petstore/python/tests/test_pet_model.py +++ b/samples/client/petstore/python/tests/test_pet_model.py @@ -1,5 +1,7 @@ # coding: utf-8 +# flake8: noqa + """ Run the tests. $ pip install nose (optional) diff --git a/samples/client/petstore/python/tests/test_store_api.py b/samples/client/petstore/python/tests/test_store_api.py index b7e80281707..095f5e7b236 100644 --- a/samples/client/petstore/python/tests/test_store_api.py +++ b/samples/client/petstore/python/tests/test_store_api.py @@ -1,5 +1,7 @@ # coding: utf-8 +# flake8: noqa + """ Run the tests. $ pip install nose (optional) diff --git a/samples/client/petstore/python/tests/util.py b/samples/client/petstore/python/tests/util.py index e83ca37a942..113d7dcc547 100644 --- a/samples/client/petstore/python/tests/util.py +++ b/samples/client/petstore/python/tests/util.py @@ -1,3 +1,5 @@ +# flake8: noqa + import random diff --git a/samples/client/petstore/qt5cpp/client/SWGOrder.cpp b/samples/client/petstore/qt5cpp/client/SWGOrder.cpp index 1d947be1914..bf4f09d4647 100644 --- a/samples/client/petstore/qt5cpp/client/SWGOrder.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGOrder.cpp @@ -155,7 +155,7 @@ SWGOrder::setStatus(QString* status) { } bool -SWGOrder::getComplete() { +SWGOrder::isComplete() { return complete; } void diff --git a/samples/client/petstore/qt5cpp/client/SWGOrder.h b/samples/client/petstore/qt5cpp/client/SWGOrder.h index 72b2bf84538..13f1b205f0b 100644 --- a/samples/client/petstore/qt5cpp/client/SWGOrder.h +++ b/samples/client/petstore/qt5cpp/client/SWGOrder.h @@ -58,7 +58,7 @@ public: QString* getStatus(); void setStatus(QString* status); - bool getComplete(); + bool isComplete(); void setComplete(bool complete); diff --git a/samples/client/petstore/r_test/R/ApiResponse.r b/samples/client/petstore/r_test/R/ApiResponse.r index 161a765c0a5..3441c65da1a 100644 --- a/samples/client/petstore/r_test/R/ApiResponse.r +++ b/samples/client/petstore/r_test/R/ApiResponse.r @@ -65,9 +65,9 @@ ApiResponse <- R6::R6Class( toJSONString = function() { sprintf( '{ - "code": "%s", - "type": "%s", - "message": "%s" + "code": %s, + "type": %s, + "message": %s }', self$`code`, self$`type`, diff --git a/samples/client/petstore/r_test/R/Category.r b/samples/client/petstore/r_test/R/Category.r index 826b6410a88..36e2d8b2018 100644 --- a/samples/client/petstore/r_test/R/Category.r +++ b/samples/client/petstore/r_test/R/Category.r @@ -54,7 +54,7 @@ Category <- R6::R6Class( sprintf( '{ "id": %d, - "name": "%s" + "name": %s }', self$`id`, self$`name` diff --git a/samples/client/petstore/r_test/R/Order.r b/samples/client/petstore/r_test/R/Order.r index 73fedcb5f86..a0f2f09c122 100644 --- a/samples/client/petstore/r_test/R/Order.r +++ b/samples/client/petstore/r_test/R/Order.r @@ -102,10 +102,10 @@ Order <- R6::R6Class( '{ "id": %d, "petId": %d, - "quantity": "%s", - "shipDate": "%s", - "status": "%s", - "complete": "%s" + "quantity": %s, + "shipDate": %s, + "status": %s, + "complete": %s }', self$`id`, self$`petId`, diff --git a/samples/client/petstore/r_test/R/Pet.r b/samples/client/petstore/r_test/R/Pet.r index 98ba5d747e5..777589993f5 100644 --- a/samples/client/petstore/r_test/R/Pet.r +++ b/samples/client/petstore/r_test/R/Pet.r @@ -111,10 +111,10 @@ Pet <- R6::R6Class( '{ "id": %d, "category": %s, - "name": "%s", - "photoUrls": ["%s"], + "name": %s, + "photoUrls": [%s], "tags": [%s], - "status": "%s" + "status": %s }', self$`id`, self$`category`$toJSON(), diff --git a/samples/client/petstore/r_test/R/PetApi.r b/samples/client/petstore/r_test/R/PetApi.r index 6fa5c30cfb4..70087af7fad 100644 --- a/samples/client/petstore/r_test/R/PetApi.r +++ b/samples/client/petstore/r_test/R/PetApi.r @@ -59,15 +59,16 @@ PetApi <- R6::R6Class( }, add_pet = function(body, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() + if (!missing(`body`)) { - body <- `body`$toJSON() + body <- `body`$toJSONString() + } else { + body <- NULL } urlPath <- "/pet" - resp <- self$apiClient$callApi(url = paste0(self$apiClient$basePath, urlPath), method = "POST", queryParams = queryParams, @@ -86,9 +87,9 @@ PetApi <- R6::R6Class( }, delete_pet = function(pet_id, api_key, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() + if (!missing(`api_key`)) { headerParams['api_key'] <- `api_key` } @@ -116,15 +117,14 @@ PetApi <- R6::R6Class( }, find_pets_by_status = function(status, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() + if (!missing(`status`)) { queryParams['status'] <- status } urlPath <- "/pet/findByStatus" - resp <- self$apiClient$callApi(url = paste0(self$apiClient$basePath, urlPath), method = "GET", queryParams = queryParams, @@ -145,15 +145,14 @@ PetApi <- R6::R6Class( }, find_pets_by_tags = function(tags, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() + if (!missing(`tags`)) { queryParams['tags'] <- tags } urlPath <- "/pet/findByTags" - resp <- self$apiClient$callApi(url = paste0(self$apiClient$basePath, urlPath), method = "GET", queryParams = queryParams, @@ -174,7 +173,6 @@ PetApi <- R6::R6Class( }, get_pet_by_id = function(pet_id, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() @@ -203,15 +201,16 @@ PetApi <- R6::R6Class( }, update_pet = function(body, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() + if (!missing(`body`)) { - body <- `body`$toJSON() + body <- `body`$toJSONString() + } else { + body <- NULL } urlPath <- "/pet" - resp <- self$apiClient$callApi(url = paste0(self$apiClient$basePath, urlPath), method = "PUT", queryParams = queryParams, @@ -230,13 +229,13 @@ PetApi <- R6::R6Class( }, update_pet_with_form = function(pet_id, name, status, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() + body <- list( "name" = name, "status" = status - ) + ) urlPath <- "/pet/{petId}" if (!missing(`pet_id`)) { @@ -261,13 +260,13 @@ PetApi <- R6::R6Class( }, upload_file = function(pet_id, additional_metadata, file, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() + body <- list( "additionalMetadata" = additional_metadata, "file" = httr::upload_file(file) - ) + ) urlPath <- "/pet/{petId}/uploadImage" if (!missing(`pet_id`)) { diff --git a/samples/client/petstore/r_test/R/StoreApi.r b/samples/client/petstore/r_test/R/StoreApi.r index b03a50e9ae8..cf99c131e04 100644 --- a/samples/client/petstore/r_test/R/StoreApi.r +++ b/samples/client/petstore/r_test/R/StoreApi.r @@ -47,7 +47,6 @@ StoreApi <- R6::R6Class( }, delete_order = function(order_id, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() @@ -74,12 +73,10 @@ StoreApi <- R6::R6Class( }, get_inventory = function(...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() urlPath <- "/store/inventory" - resp <- self$apiClient$callApi(url = paste0(self$apiClient$basePath, urlPath), method = "GET", queryParams = queryParams, @@ -100,7 +97,6 @@ StoreApi <- R6::R6Class( }, get_order_by_id = function(order_id, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() @@ -129,15 +125,16 @@ StoreApi <- R6::R6Class( }, place_order = function(body, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() + if (!missing(`body`)) { - body <- `body`$toJSON() + body <- `body`$toJSONString() + } else { + body <- NULL } urlPath <- "/store/order" - resp <- self$apiClient$callApi(url = paste0(self$apiClient$basePath, urlPath), method = "POST", queryParams = queryParams, diff --git a/samples/client/petstore/r_test/R/Tag.r b/samples/client/petstore/r_test/R/Tag.r index 13501d24f1b..80c7e01e375 100644 --- a/samples/client/petstore/r_test/R/Tag.r +++ b/samples/client/petstore/r_test/R/Tag.r @@ -54,7 +54,7 @@ Tag <- R6::R6Class( sprintf( '{ "id": %d, - "name": "%s" + "name": %s }', self$`id`, self$`name` diff --git a/samples/client/petstore/r_test/R/User.r b/samples/client/petstore/r_test/R/User.r index 4c45fb8c00e..42f3411077c 100644 --- a/samples/client/petstore/r_test/R/User.r +++ b/samples/client/petstore/r_test/R/User.r @@ -126,13 +126,13 @@ User <- R6::R6Class( sprintf( '{ "id": %d, - "username": "%s", - "firstName": "%s", - "lastName": "%s", - "email": "%s", - "password": "%s", - "phone": "%s", - "userStatus": "%s" + "username": %s, + "firstName": %s, + "lastName": %s, + "email": %s, + "password": %s, + "phone": %s, + "userStatus": %s }', self$`id`, self$`username`, diff --git a/samples/client/petstore/r_test/R/UserApi.r b/samples/client/petstore/r_test/R/UserApi.r index 1ed17ab286f..6fe335d7dc7 100644 --- a/samples/client/petstore/r_test/R/UserApi.r +++ b/samples/client/petstore/r_test/R/UserApi.r @@ -59,15 +59,16 @@ UserApi <- R6::R6Class( }, create_user = function(body, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() + if (!missing(`body`)) { - body <- `body`$toJSON() + body <- `body`$toJSONString() + } else { + body <- NULL } urlPath <- "/user" - resp <- self$apiClient$callApi(url = paste0(self$apiClient$basePath, urlPath), method = "POST", queryParams = queryParams, @@ -86,15 +87,16 @@ UserApi <- R6::R6Class( }, create_users_with_array_input = function(body, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() + if (!missing(`body`)) { - body <- `body`$toJSON() + body <- `body`$toJSONString() + } else { + body <- NULL } urlPath <- "/user/createWithArray" - resp <- self$apiClient$callApi(url = paste0(self$apiClient$basePath, urlPath), method = "POST", queryParams = queryParams, @@ -113,15 +115,16 @@ UserApi <- R6::R6Class( }, create_users_with_list_input = function(body, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() + if (!missing(`body`)) { - body <- `body`$toJSON() + body <- `body`$toJSONString() + } else { + body <- NULL } urlPath <- "/user/createWithList" - resp <- self$apiClient$callApi(url = paste0(self$apiClient$basePath, urlPath), method = "POST", queryParams = queryParams, @@ -140,7 +143,6 @@ UserApi <- R6::R6Class( }, delete_user = function(username, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() @@ -167,7 +169,6 @@ UserApi <- R6::R6Class( }, get_user_by_name = function(username, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() @@ -196,18 +197,18 @@ UserApi <- R6::R6Class( }, login_user = function(username, password, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() + if (!missing(`username`)) { queryParams['username'] <- username } + if (!missing(`password`)) { queryParams['password'] <- password } urlPath <- "/user/login" - resp <- self$apiClient$callApi(url = paste0(self$apiClient$basePath, urlPath), method = "GET", queryParams = queryParams, @@ -228,12 +229,10 @@ UserApi <- R6::R6Class( }, logout_user = function(...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() urlPath <- "/user/logout" - resp <- self$apiClient$callApi(url = paste0(self$apiClient$basePath, urlPath), method = "GET", queryParams = queryParams, @@ -252,11 +251,13 @@ UserApi <- R6::R6Class( }, update_user = function(username, body, ...){ args <- list(...) - body <- NULL queryParams <- list() headerParams <- character() + if (!missing(`body`)) { - body <- `body`$toJSON() + body <- `body`$toJSONString() + } else { + body <- NULL } urlPath <- "/user/{username}" diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 4903f762470..84d01e186c4 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -54,17 +54,17 @@ Please follow the [installation](#installation) procedure and then run the follo # Load the gem require 'petstore' -api_instance = Petstore::FakeApi.new +api_instance = Petstore::AnotherFakeApi.new + +body = Petstore::Client.new # Client | client model -opts = { - body: Petstore::OuterBoolean.new # OuterBoolean | Input boolean as post body -} begin - result = api_instance.fake_outer_boolean_serialize(opts) + #To test special tags + result = api_instance.test_special_tags(body) p result rescue Petstore::ApiError => e - puts "Exception when calling FakeApi->fake_outer_boolean_serialize: #{e}" + puts "Exception when calling AnotherFakeApi->test_special_tags: #{e}" end ``` @@ -75,6 +75,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*Petstore::AnotherFakeApi* | [**test_special_tags**](docs/AnotherFakeApi.md#test_special_tags) | **PATCH** /another-fake/dummy | To test special tags *Petstore::FakeApi* | [**fake_outer_boolean_serialize**](docs/FakeApi.md#fake_outer_boolean_serialize) | **POST** /fake/outer/boolean | *Petstore::FakeApi* | [**fake_outer_composite_serialize**](docs/FakeApi.md#fake_outer_composite_serialize) | **POST** /fake/outer/composite | *Petstore::FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | @@ -82,6 +83,7 @@ Class | Method | HTTP request | Description *Petstore::FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model *Petstore::FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *Petstore::FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +*Petstore::FakeApi* | [**test_inline_additional_properties**](docs/FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties *Petstore::FakeApi* | [**test_json_form_data**](docs/FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data *Petstore::FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case *Petstore::PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store diff --git a/samples/client/petstore/ruby/docs/AnotherFakeApi.md b/samples/client/petstore/ruby/docs/AnotherFakeApi.md new file mode 100644 index 00000000000..a198df230eb --- /dev/null +++ b/samples/client/petstore/ruby/docs/AnotherFakeApi.md @@ -0,0 +1,56 @@ +# Petstore::AnotherFakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**test_special_tags**](AnotherFakeApi.md#test_special_tags) | **PATCH** /another-fake/dummy | To test special tags + + +# **test_special_tags** +> Client test_special_tags(body) + +To test special tags + +To test special tags + +### Example +```ruby +# load the gem +require 'petstore' + +api_instance = Petstore::AnotherFakeApi.new + +body = Petstore::Client.new # Client | client model + + +begin + #To test special tags + result = api_instance.test_special_tags(body) + p result +rescue Petstore::ApiError => e + puts "Exception when calling AnotherFakeApi->test_special_tags: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + + diff --git a/samples/client/petstore/ruby/docs/FakeApi.md b/samples/client/petstore/ruby/docs/FakeApi.md index 97c2efb11c2..72aaf8460e4 100644 --- a/samples/client/petstore/ruby/docs/FakeApi.md +++ b/samples/client/petstore/ruby/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model [**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +[**test_inline_additional_properties**](FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**test_json_form_data**](FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data @@ -393,6 +394,52 @@ No authorization required +# **test_inline_additional_properties** +> test_inline_additional_properties(param) + +test inline additionalProperties + + + +### Example +```ruby +# load the gem +require 'petstore' + +api_instance = Petstore::FakeApi.new + +param = nil # Object | request body + + +begin + #test inline additionalProperties + api_instance.test_inline_additional_properties(param) +rescue Petstore::ApiError => e + puts "Exception when calling FakeApi->test_inline_additional_properties: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **Object**| request body | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + + # **test_json_form_data** > test_json_form_data(param, param2) diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index 605e44333dd..e2cafdbe706 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -55,6 +55,7 @@ require 'petstore/models/cat' require 'petstore/models/dog' # APIs +require 'petstore/api/another_fake_api' require 'petstore/api/fake_api' require 'petstore/api/fake_classname_tags123_api' require 'petstore/api/pet_api' diff --git a/samples/client/petstore/ruby/lib/petstore/api/another_fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/another_fake_api.rb new file mode 100644 index 00000000000..5c93e4521c8 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/api/another_fake_api.rb @@ -0,0 +1,78 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git +Swagger Codegen version: 2.3.0-SNAPSHOT + +=end + +require "uri" + +module Petstore + class AnotherFakeApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + + # To test special tags + # To test special tags + # @param body client model + # @param [Hash] opts the optional parameters + # @return [Client] + def test_special_tags(body, opts = {}) + data, _status_code, _headers = test_special_tags_with_http_info(body, opts) + return data + end + + # To test special tags + # To test special tags + # @param body client model + # @param [Hash] opts the optional parameters + # @return [Array<(Client, Fixnum, Hash)>] Client data, response status code and response headers + def test_special_tags_with_http_info(body, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: AnotherFakeApi.test_special_tags ..." + end + # verify the required parameter 'body' is set + if @api_client.config.client_side_validation && body.nil? + fail ArgumentError, "Missing the required parameter 'body' when calling AnotherFakeApi.test_special_tags" + end + # resource path + local_var_path = "/another-fake/dummy" + + # query parameters + query_params = {} + + # header parameters + header_params = {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + # HTTP header 'Content-Type' + header_params['Content-Type'] = @api_client.select_header_content_type(['application/json']) + + # form parameters + form_params = {} + + # http body (model) + post_body = @api_client.object_to_http_body(body) + auth_names = [] + data, status_code, headers = @api_client.call_api(:PATCH, local_var_path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Client') + if @api_client.config.debugging + @api_client.config.logger.debug "API called: AnotherFakeApi#test_special_tags\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end 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 7951ac39df8..56e68e4422b 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -517,6 +517,58 @@ module Petstore return data, status_code, headers end + # test inline additionalProperties + # + # @param param request body + # @param [Hash] opts the optional parameters + # @return [nil] + def test_inline_additional_properties(param, opts = {}) + test_inline_additional_properties_with_http_info(param, opts) + return nil + end + + # test inline additionalProperties + # + # @param param request body + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers + def test_inline_additional_properties_with_http_info(param, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: FakeApi.test_inline_additional_properties ..." + end + # verify the required parameter 'param' is set + if @api_client.config.client_side_validation && param.nil? + fail ArgumentError, "Missing the required parameter 'param' when calling FakeApi.test_inline_additional_properties" + end + # resource path + local_var_path = "/fake/inline-additionalProperties" + + # query parameters + query_params = {} + + # header parameters + header_params = {} + # HTTP header 'Content-Type' + header_params['Content-Type'] = @api_client.select_header_content_type(['application/json']) + + # form parameters + form_params = {} + + # http body (model) + post_body = @api_client.object_to_http_body(param) + auth_names = [] + data, status_code, headers = @api_client.call_api(:POST, local_var_path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_inline_additional_properties\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + # test json serialization of form data # # @param param field1 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 index e5d7fb8f24b..e3d8890b6e2 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb @@ -45,13 +45,13 @@ module Petstore attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} if attributes.has_key?(:'map_property') - if (value = attributes[:'map_property']).is_a?(Array) + if (value = attributes[:'map_property']).is_a?(Hash) self.map_property = value end end if attributes.has_key?(:'map_of_map_property') - if (value = attributes[:'map_of_map_property']).is_a?(Array) + if (value = attributes[:'map_of_map_property']).is_a?(Hash) self.map_of_map_property = value 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 977a572e91c..28ba3616969 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb @@ -23,8 +23,8 @@ module Petstore # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) - consantValues = EnumClass.constants.select{|c| c.to_s == value} - raise "Invalid ENUM value #{value} for class #EnumClass" if consantValues.empty? + constantValues = EnumClass.constants.select{|c| EnumClass::const_get(c) == value} + raise "Invalid ENUM value #{value} for class #EnumClass" if constantValues.empty? value end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/map_test.rb b/samples/client/petstore/ruby/lib/petstore/models/map_test.rb index 9510ce2a93c..7b8f9527797 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/map_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/map_test.rb @@ -66,13 +66,13 @@ module Petstore attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} if attributes.has_key?(:'map_map_of_string') - if (value = attributes[:'map_map_of_string']).is_a?(Array) + if (value = attributes[:'map_map_of_string']).is_a?(Hash) self.map_map_of_string = value end end if attributes.has_key?(:'map_of_enum_string') - if (value = attributes[:'map_of_enum_string']).is_a?(Array) + if (value = attributes[:'map_of_enum_string']).is_a?(Hash) self.map_of_enum_string = value 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 index f16ce716f33..75c9795f479 100644 --- 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 @@ -57,7 +57,7 @@ module Petstore end if attributes.has_key?(:'map') - if (value = attributes[:'map']).is_a?(Array) + if (value = attributes[:'map']).is_a?(Hash) self.map = value end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb index 713498c0aaa..b116798f7fe 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb @@ -23,8 +23,8 @@ module Petstore # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) - consantValues = OuterEnum.constants.select{|c| c.to_s == value} - raise "Invalid ENUM value #{value} for class #OuterEnum" if consantValues.empty? + constantValues = OuterEnum.constants.select{|c| OuterEnum::const_get(c) == value} + raise "Invalid ENUM value #{value} for class #OuterEnum" if constantValues.empty? value end end diff --git a/samples/client/petstore/ruby/spec/api/another_fake_api_spec.rb b/samples/client/petstore/ruby/spec/api/another_fake_api_spec.rb new file mode 100644 index 00000000000..26935923316 --- /dev/null +++ b/samples/client/petstore/ruby/spec/api/another_fake_api_spec.rb @@ -0,0 +1,47 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git +Swagger Codegen version: 2.3.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for Petstore::AnotherFakeApi +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'AnotherFakeApi' do + before do + # run before each test + @instance = Petstore::AnotherFakeApi.new + end + + after do + # run after each test + end + + describe 'test an instance of AnotherFakeApi' do + it 'should create an instance of AnotherFakeApi' do + expect(@instance).to be_instance_of(Petstore::AnotherFakeApi) + end + end + + # unit tests for test_special_tags + # To test special tags + # To test special tags + # @param body client model + # @param [Hash] opts the optional parameters + # @return [Client] + describe 'test_special_tags test' 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/rust/Cargo.toml b/samples/client/petstore/rust/Cargo.toml index 8fe01ecd022..be1bc97c6a4 100644 --- a/samples/client/petstore/rust/Cargo.toml +++ b/samples/client/petstore/rust/Cargo.toml @@ -4,14 +4,14 @@ version = "1.0.0" authors = ["Swagger Codegen team and contributors"] [dependencies] -serde = "*" -serde_derive = "*" -serde_yaml = "*" -serde_json = "*" -base64 = "*" -futures = "*" -hyper = "*" -url = "*" +serde = "1.0" +serde_derive = "1.0" +serde_yaml = "0.7" +serde_json = "1.0" +base64 = "~0.7.0" +futures = "0.1.16" +hyper = "0.11.6" +url = "1.5" [dev-dependencies] tokio-core = "*" diff --git a/samples/client/petstore/rust/src/models/api_response.rs b/samples/client/petstore/rust/src/models/api_response.rs index 91cbb74f7f2..d30f7489c87 100644 --- a/samples/client/petstore/rust/src/models/api_response.rs +++ b/samples/client/petstore/rust/src/models/api_response.rs @@ -10,6 +10,9 @@ /// ApiResponse : Describes the result of uploading an image resource +#[allow(unused_imports)] +use serde_json::Value; + #[derive(Debug, Serialize, Deserialize)] pub struct ApiResponse { #[serde(rename = "code")] diff --git a/samples/client/petstore/rust/src/models/category.rs b/samples/client/petstore/rust/src/models/category.rs index c7c9265e14c..a88f835c37c 100644 --- a/samples/client/petstore/rust/src/models/category.rs +++ b/samples/client/petstore/rust/src/models/category.rs @@ -10,6 +10,9 @@ /// Category : A category for a pet +#[allow(unused_imports)] +use serde_json::Value; + #[derive(Debug, Serialize, Deserialize)] pub struct Category { #[serde(rename = "id")] diff --git a/samples/client/petstore/rust/src/models/order.rs b/samples/client/petstore/rust/src/models/order.rs index 75fce884085..6ece9031449 100644 --- a/samples/client/petstore/rust/src/models/order.rs +++ b/samples/client/petstore/rust/src/models/order.rs @@ -10,6 +10,9 @@ /// Order : An order for a pets from the pet store +#[allow(unused_imports)] +use serde_json::Value; + #[derive(Debug, Serialize, Deserialize)] pub struct Order { #[serde(rename = "id")] diff --git a/samples/client/petstore/rust/src/models/pet.rs b/samples/client/petstore/rust/src/models/pet.rs index 837358a3f3e..b9c7616d8f5 100644 --- a/samples/client/petstore/rust/src/models/pet.rs +++ b/samples/client/petstore/rust/src/models/pet.rs @@ -10,6 +10,9 @@ /// Pet : A pet for sale in the pet store +#[allow(unused_imports)] +use serde_json::Value; + #[derive(Debug, Serialize, Deserialize)] pub struct Pet { #[serde(rename = "id")] diff --git a/samples/client/petstore/rust/src/models/tag.rs b/samples/client/petstore/rust/src/models/tag.rs index 2f328870a6c..64cc5a0d793 100644 --- a/samples/client/petstore/rust/src/models/tag.rs +++ b/samples/client/petstore/rust/src/models/tag.rs @@ -10,6 +10,9 @@ /// Tag : A tag for a pet +#[allow(unused_imports)] +use serde_json::Value; + #[derive(Debug, Serialize, Deserialize)] pub struct Tag { #[serde(rename = "id")] diff --git a/samples/client/petstore/rust/src/models/user.rs b/samples/client/petstore/rust/src/models/user.rs index 095131307a6..cd286c2ecb4 100644 --- a/samples/client/petstore/rust/src/models/user.rs +++ b/samples/client/petstore/rust/src/models/user.rs @@ -10,6 +10,9 @@ /// User : A User who is purchasing from the pet store +#[allow(unused_imports)] +use serde_json::Value; + #[derive(Debug, Serialize, Deserialize)] pub struct User { #[serde(rename = "id")] diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/ApiResponse.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/ApiResponse.scala index a2badb49ae1..220a5e48d9e 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/ApiResponse.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/ApiResponse.scala @@ -14,8 +14,8 @@ package io.swagger.client.model case class ApiResponse ( - code: Option[Integer], - _type: Option[String], - message: Option[String] + code: Option[Integer] = None, + _type: Option[String] = None, + message: Option[String] = None ) diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Category.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Category.scala index e39d097b918..657b90de8a7 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Category.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Category.scala @@ -14,7 +14,7 @@ package io.swagger.client.model case class Category ( - id: Option[Long], - name: Option[String] + id: Option[Long] = None, + name: Option[String] = None ) diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Order.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Order.scala index 84691796eaf..fae3fddacb1 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Order.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Order.scala @@ -15,12 +15,12 @@ package io.swagger.client.model import java.util.Date case class Order ( - id: Option[Long], - petId: Option[Long], - quantity: Option[Integer], - shipDate: Option[Date], + id: Option[Long] = None, + petId: Option[Long] = None, + quantity: Option[Integer] = None, + shipDate: Option[Date] = None, /* Order Status */ - status: Option[String], - complete: Option[Boolean] + status: Option[String] = None, + complete: Option[Boolean] = None ) diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala index baabc18c99f..88c868637e9 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala @@ -14,12 +14,12 @@ package io.swagger.client.model case class Pet ( - id: Option[Long], - category: Option[Category], + id: Option[Long] = None, + category: Option[Category] = None, name: String, photoUrls: List[String], - tags: Option[List[Tag]], + tags: Option[List[Tag]] = None, /* pet status in the store */ - status: Option[String] + status: Option[String] = None ) diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Tag.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Tag.scala index 5ae718fd7e8..ee39797b41c 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Tag.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Tag.scala @@ -14,7 +14,7 @@ package io.swagger.client.model case class Tag ( - id: Option[Long], - name: Option[String] + id: Option[Long] = None, + name: Option[String] = None ) diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/User.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/User.scala index c5bdb386638..46183e94547 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/User.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/User.scala @@ -14,14 +14,14 @@ package io.swagger.client.model case class User ( - id: Option[Long], - username: Option[String], - firstName: Option[String], - lastName: Option[String], - email: Option[String], - password: Option[String], - phone: Option[String], + id: Option[Long] = None, + username: Option[String] = None, + firstName: Option[String] = None, + lastName: Option[String] = None, + email: Option[String] = None, + password: Option[String] = None, + phone: Option[String] = None, /* User Status */ - userStatus: Option[Integer] + userStatus: Option[Integer] = None ) diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java index 9dc45ad5634..ff7faf53bc3 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java @@ -8,9 +8,9 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -20,10 +20,9 @@ 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 org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "Pet", description = "the Pet API") public interface PetApi { @@ -55,7 +54,7 @@ public interface PetApi { produces = "application/json", consumes = "application/json", method = RequestMethod.DELETE) - com.netflix.hystrix.HystrixCommand> deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); + com.netflix.hystrix.HystrixCommand> 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", nickname = "findPetsByStatus", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @@ -71,7 +70,7 @@ public interface PetApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - com.netflix.hystrix.HystrixCommand>> findPetsByStatus( @NotNull@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status); + com.netflix.hystrix.HystrixCommand>> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status); @ApiOperation(value = "Finds Pets by tags", nickname = "findPetsByTags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -87,7 +86,7 @@ public interface PetApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - com.netflix.hystrix.HystrixCommand>> findPetsByTags( @NotNull@ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags); + com.netflix.hystrix.HystrixCommand>> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags); @ApiOperation(value = "Find pet by ID", nickname = "getPetById", notes = "Returns a single pet", response = Pet.class, authorizations = { @@ -101,7 +100,7 @@ public interface PetApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - com.netflix.hystrix.HystrixCommand> getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId); + com.netflix.hystrix.HystrixCommand> getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId); @ApiOperation(value = "Update an existing pet", nickname = "updatePet", notes = "", authorizations = { @@ -133,7 +132,7 @@ public interface PetApi { produces = "application/json", consumes = "application/x-www-form-urlencoded", method = RequestMethod.POST) - com.netflix.hystrix.HystrixCommand> updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "Updated name of the pet" ) @RequestParam(value="name", required=false) String name,@ApiParam(value = "Updated status of the pet" ) @RequestParam(value="status", required=false) String status); + com.netflix.hystrix.HystrixCommand> updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Updated name of the pet" ) @RequestParam(value="name", required=false) String name,@ApiParam(value = "Updated status of the pet" ) @RequestParam(value="status", required=false) String status); @ApiOperation(value = "uploads an image", nickname = "uploadFile", notes = "", response = ModelApiResponse.class, authorizations = { @@ -148,6 +147,6 @@ public interface PetApi { produces = "application/json", consumes = "multipart/form-data", method = RequestMethod.POST) - com.netflix.hystrix.HystrixCommand> uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server" ) @RequestParam(value="additionalMetadata", required=false) String additionalMetadata,@ApiParam(value = "file detail") @RequestParam("file") MultipartFile file); + com.netflix.hystrix.HystrixCommand> uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server" ) @RequestParam(value="additionalMetadata", required=false) String additionalMetadata,@ApiParam(value = "file detail") @RequestParam("file") MultipartFile file); } diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApi.java index a93edffab2d..bd412c2af3d 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApi.java @@ -7,9 +7,9 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -19,10 +19,9 @@ 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 org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "Store", description = "the Store API") public interface StoreApi { @@ -35,7 +34,7 @@ public interface StoreApi { produces = "application/json", consumes = "application/json", method = RequestMethod.DELETE) - com.netflix.hystrix.HystrixCommand> deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId); + com.netflix.hystrix.HystrixCommand> 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", nickname = "getInventory", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @@ -59,7 +58,7 @@ public interface StoreApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - com.netflix.hystrix.HystrixCommand> getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); + com.netflix.hystrix.HystrixCommand> getOrderById(@Min(1) @Max(5) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("orderId") Long orderId); @ApiOperation(value = "Place an order for a pet", nickname = "placeOrder", notes = "", response = Order.class, tags={ "store", }) diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java index cf2a1b89cdc..1d1169ec13d 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java @@ -7,9 +7,9 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -19,10 +19,9 @@ 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 org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "User", description = "the User API") public interface UserApi { @@ -65,7 +64,7 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.DELETE) - com.netflix.hystrix.HystrixCommand> deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username); + com.netflix.hystrix.HystrixCommand> deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username); @ApiOperation(value = "Get user by user name", nickname = "getUserByName", notes = "", response = User.class, tags={ "user", }) @@ -77,7 +76,7 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - com.netflix.hystrix.HystrixCommand> getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username); + com.netflix.hystrix.HystrixCommand> 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", nickname = "loginUser", notes = "", response = String.class, tags={ "user", }) @@ -88,7 +87,7 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - com.netflix.hystrix.HystrixCommand> loginUser( @NotNull@ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, @NotNull@ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password); + com.netflix.hystrix.HystrixCommand> loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password); @ApiOperation(value = "Logs out current logged in user session", nickname = "logoutUser", notes = "", tags={ "user", }) @@ -109,6 +108,6 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.PUT) - com.netflix.hystrix.HystrixCommand> updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body); + com.netflix.hystrix.HystrixCommand> updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body); } 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 index 65fd59009b1..a4a3768817c 100644 --- 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 @@ -8,9 +8,9 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -19,12 +19,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "pet", description = "the pet API") public interface PetApi { @@ -41,7 +39,7 @@ public interface PetApi { 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 ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); @ApiOperation(value = "Deletes a pet", nickname = "deletePet", notes = "", authorizations = { @@ -56,7 +54,7 @@ public interface PetApi { 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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "findPetsByStatus", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @@ -72,7 +70,7 @@ public interface PetApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity> findPetsByStatus( @NotNull@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status); @ApiOperation(value = "Finds Pets by tags", nickname = "findPetsByTags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -88,7 +86,7 @@ public interface PetApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity> findPetsByTags( @NotNull@ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags); @ApiOperation(value = "Find pet by ID", nickname = "getPetById", notes = "Returns a single pet", response = Pet.class, authorizations = { @@ -102,7 +100,7 @@ public interface PetApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId); @ApiOperation(value = "Update an existing pet", nickname = "updatePet", notes = "", authorizations = { @@ -119,7 +117,7 @@ public interface PetApi { 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 ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); @ApiOperation(value = "Updates a pet in the store with form data", nickname = "updatePetWithForm", notes = "", authorizations = { @@ -134,7 +132,7 @@ public interface PetApi { 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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "uploadFile", notes = "", response = ModelApiResponse.class, authorizations = { @@ -149,6 +147,6 @@ public interface PetApi { 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") @Valid @RequestPart("file") MultipartFile file, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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") @Valid @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 index 33fd53aa2e2..7ccfa191a07 100644 --- 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 @@ -7,9 +7,9 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,12 +18,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "store", description = "the store API") public interface StoreApi { @@ -36,7 +34,7 @@ public interface StoreApi { 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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "getInventory", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @@ -48,7 +46,7 @@ public interface StoreApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity> getInventory( @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> getInventory(); @ApiOperation(value = "Find purchase order by ID", nickname = "getOrderById", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @@ -60,7 +58,7 @@ public interface StoreApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity getOrderById(@Min(1) @Max(5) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("orderId") Long orderId); @ApiOperation(value = "Place an order for a pet", nickname = "placeOrder", notes = "", response = Order.class, tags={ "store", }) @@ -71,6 +69,6 @@ public interface StoreApi { produces = "application/json", consumes = "application/json", method = RequestMethod.POST) - ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @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 index d1e1f9e5def..9482597b5da 100644 --- 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 @@ -7,9 +7,9 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,12 +18,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "user", description = "the user API") public interface UserApi { @@ -35,7 +33,7 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.POST) - ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body); @ApiOperation(value = "Creates list of users with given input array", nickname = "createUsersWithArrayInput", notes = "", tags={ "user", }) @@ -45,7 +43,7 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.POST) - ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); @ApiOperation(value = "Creates list of users with given input array", nickname = "createUsersWithListInput", notes = "", tags={ "user", }) @@ -55,7 +53,7 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.POST) - ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); @ApiOperation(value = "Delete user", nickname = "deleteUser", notes = "This can only be done by the logged in user.", tags={ "user", }) @@ -66,7 +64,7 @@ public interface UserApi { 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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username); @ApiOperation(value = "Get user by user name", nickname = "getUserByName", notes = "", response = User.class, tags={ "user", }) @@ -78,7 +76,7 @@ public interface UserApi { 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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "loginUser", notes = "", response = String.class, tags={ "user", }) @@ -89,7 +87,7 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity loginUser( @NotNull@ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, @NotNull@ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password); @ApiOperation(value = "Logs out current logged in user session", nickname = "logoutUser", notes = "", tags={ "user", }) @@ -99,7 +97,7 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity logoutUser( @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity logoutUser(); @ApiOperation(value = "Updated user", nickname = "updateUser", notes = "This can only be done by the logged in user.", tags={ "user", }) @@ -110,6 +108,6 @@ public interface UserApi { 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 ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body); } diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs.swift index be616c7b71d..fe0b1fffd25 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs.swift @@ -32,10 +32,10 @@ open class APIBase { open class RequestBuilder { var credential: URLCredential? var headers: [String:String] - let parameters: Any? - let isBody: Bool - let method: String - let URLString: String + public let parameters: Any? + public let isBody: Bool + public let method: String + public let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((Progress) -> ())? diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift index 2e100b1fdcd..5b97c3c8057 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift @@ -1,5 +1,5 @@ // -// AnotherFakeAPI.swift +// AnotherfakeAPI.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen @@ -9,7 +9,7 @@ import Foundation import Alamofire -open class AnotherFakeAPI: APIBase { +open class AnotherfakeAPI: APIBase { /** To test special tags - parameter body: (body) client model diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift index 4a9748a5ad1..bc4369df7ae 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift @@ -37,7 +37,7 @@ open class Fake_classname_tags123API: APIBase { open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake_classname_test" let URLString = PetstoreClientAPI.basePath + path - let parameters = body.encodeToJSON() as? [String:AnyObject] + let parameters = body.encodeToJSON() let url = NSURLComponents(string: URLString) diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 7eaa9ab093f..6de1f336620 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -70,7 +70,9 @@ open class PetAPI: APIBase { */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -412,7 +414,9 @@ open class PetAPI: APIBase { */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -485,7 +489,9 @@ open class PetAPI: APIBase { */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let formParams: [String:Any?] = [ "name": name, @@ -535,7 +541,9 @@ open class PetAPI: APIBase { */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { var path = "/pet/{petId}/uploadImage" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let formParams: [String:Any?] = [ "additionalMetadata": additionalMetadata, diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 006be5ab186..7d99f10de0c 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -32,7 +32,9 @@ open class StoreAPI: APIBase { */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { var path = "/store/order/{order_id}" - path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let orderIdPreEscape = "\(orderId)" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -130,7 +132,9 @@ open class StoreAPI: APIBase { */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { var path = "/store/order/{order_id}" - path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let orderIdPreEscape = "\(orderId)" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index d4020a0a9c8..b5bd0d0677a 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -128,7 +128,9 @@ open class UserAPI: APIBase { */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -199,7 +201,9 @@ open class UserAPI: APIBase { */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -306,7 +310,9 @@ open class UserAPI: APIBase { */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() diff --git a/samples/client/petstore/swift3/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift3/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift index 87d10dd12e0..f6f87e9e763 100644 --- a/samples/client/petstore/swift3/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift +++ b/samples/client/petstore/swift3/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift @@ -151,4 +151,14 @@ class UserAPITests: XCTestCase { self.waitForExpectations(timeout: testTimeout, handler: nil) } + func testPathParamsAreEscaped() { + // The path for this operation is /user/{userId}. In order to make a usable path, + // then we must make sure that {userId} is percent-escaped when it is substituted + // into the path. So we intentionally introduce a path with spaces. + let userRequestBuilder = UserAPI.getUserByNameWithRequestBuilder(username: "User Name With Spaces") + let urlContainsSpace = userRequestBuilder.URLString.contains(" ") + + XCTAssert(!urlContainsSpace, "Expected URL to be escaped, but it was not.") + } + } diff --git a/samples/client/petstore/swift3/objcCompatible/.gitignore b/samples/client/petstore/swift3/objcCompatible/.gitignore new file mode 100644 index 00000000000..5e5d5cebcf4 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/.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/swift3/objcCompatible/.swagger-codegen-ignore b/samples/client/petstore/swift3/objcCompatible/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/swift3/objcCompatible/.swagger-codegen/VERSION b/samples/client/petstore/swift3/objcCompatible/.swagger-codegen/VERSION new file mode 100644 index 00000000000..f9f7450d135 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift3/objcCompatible/Cartfile b/samples/client/petstore/swift3/objcCompatible/Cartfile new file mode 100644 index 00000000000..3d90db16891 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/Cartfile @@ -0,0 +1 @@ +github "Alamofire/Alamofire" >= 3.1.0 diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient.podspec b/samples/client/petstore/swift3/objcCompatible/PetstoreClient.podspec new file mode 100644 index 00000000000..7a28d478bf8 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient.podspec @@ -0,0 +1,13 @@ +Pod::Spec.new do |s| + s.name = 'PetstoreClient' + s.ios.deployment_target = '9.0' + s.osx.deployment_target = '10.11' + s.version = '0.0.1' + s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' } + s.authors = '' + s.license = 'Proprietary' + s.homepage = 'https://github.com/swagger-api/swagger-codegen' + s.summary = 'PetstoreClient' + s.source_files = 'PetstoreClient/Classes/**/*.swift' + s.dependency 'Alamofire', '~> 4.5.0' +end diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIHelper.swift new file mode 100644 index 00000000000..f5a6b477952 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -0,0 +1,75 @@ +// APIHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +class APIHelper { + static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + var destination = [String:Any]() + for (key, nillableValue) in source { + if let value: Any = nillableValue { + destination[key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + var destination = [String:String]() + for (key, nillableValue) in source { + if let value: Any = nillableValue { + destination[key] = "\(value)" + } + } + return destination + } + + static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + guard let source = source else { + return nil + } + var destination = [String:Any]() + let theTrue = NSNumber(value: true as Bool) + let theFalse = NSNumber(value: false as Bool) + for (key, value) in source { + switch value { + case let x where x as? NSNumber === theTrue || x as? NSNumber === theFalse: + destination[key] = "\(value as! Bool)" as Any? + default: + destination[key] = value + } + } + return destination + } + + static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem]? { + let returnValues = values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> [URLQueryItem] in + if let value = item._value as? Array { + return value.map { (v) -> URLQueryItem in + URLQueryItem( + name: item._key, + value: v + ) + } + } else { + return [URLQueryItem( + name: item._key, + value: "\(item._value!)" + )] + } + } + .flatMap { $0 } + + if returnValues.isEmpty { return nil } + return returnValues + } +} diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs.swift new file mode 100644 index 00000000000..fe0b1fffd25 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs.swift @@ -0,0 +1,77 @@ +// APIs.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +open class PetstoreClientAPI { + open static var basePath = "http://petstore.swagger.io:80/v2" + open static var credential: URLCredential? + open static var customHeaders: [String:String] = [:] + open static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() +} + +open class APIBase { + func toParameters(_ encodable: JSONEncodable?) -> [String: Any]? { + let encoded: Any? = encodable?.encodeToJSON() + + if encoded! is [Any] { + var dictionary = [String:Any]() + for (index, item) in (encoded as! [Any]).enumerated() { + dictionary["\(index)"] = item + } + return dictionary + } else { + return encoded as? [String:Any] + } + } +} + +open class RequestBuilder { + var credential: URLCredential? + var headers: [String:String] + public let parameters: Any? + public let isBody: Bool + public let method: String + public let URLString: String + + /// Optional block to obtain a reference to the request's progress instance when available. + public var onProgressReady: ((Progress) -> ())? + + required public init(method: String, URLString: String, parameters: Any?, isBody: Bool, headers: [String:String] = [:]) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.isBody = isBody + self.headers = headers + + addHeaders(PetstoreClientAPI.customHeaders) + } + + open func addHeaders(_ aHeaders:[String:String]) { + for (header, value) in aHeaders { + addHeader(name: header, value: value) + } + } + + open func execute(_ completion: @escaping (_ response: Response?, _ error: ErrorResponse?) -> Void) { } + + @discardableResult public func addHeader(name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + open func addCredential() -> Self { + self.credential = PetstoreClientAPI.credential + return self + } +} + +public protocol RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift new file mode 100644 index 00000000000..5b97c3c8057 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift @@ -0,0 +1,48 @@ +// +// AnotherfakeAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + + +open class AnotherfakeAPI: APIBase { + /** + To test special tags + - parameter body: (body) client model + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testSpecialTags(body: Client, completion: @escaping ((_ data: Client?, _ error: ErrorResponse?) -> Void)) { + testSpecialTagsWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error) + } + } + + + /** + To test special tags + - PATCH /another-fake/dummy + - To test special tags + + - examples: [{contentType=application/json, example={ + "client" : "client" +}}] + - parameter body: (body) client model + - returns: RequestBuilder + */ + open class func testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { + let path = "/another-fake/dummy" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body.encodeToJSON() + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift new file mode 100644 index 00000000000..dbe5c7ceb6e --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -0,0 +1,424 @@ +// +// FakeAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + + +open class FakeAPI: APIBase { + /** + - parameter body: (body) Input boolean as post body (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterBooleanSerialize(body: OuterBoolean? = nil, completion: @escaping ((_ data: OuterBoolean?, _ error: ErrorResponse?) -> Void)) { + fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error) + } + } + + + /** + - POST /fake/outer/boolean + - Test serialization of outer boolean types + + - examples: [{contentType=application/json, example={ }}] + - parameter body: (body) Input boolean as post body (optional) + - returns: RequestBuilder + */ + open class func fakeOuterBooleanSerializeWithRequestBuilder(body: OuterBoolean? = nil) -> RequestBuilder { + let path = "/fake/outer/boolean" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + - parameter body: (body) Input composite as post body (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?, _ error: ErrorResponse?) -> Void)) { + fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error) + } + } + + + /** + - POST /fake/outer/composite + - Test serialization of object with outer number type + + - examples: [{contentType=application/json, example={ + "my_string" : { }, + "my_number" : { }, + "my_boolean" : { } +}}] + - parameter body: (body) Input composite as post body (optional) + - returns: RequestBuilder + */ + open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { + let path = "/fake/outer/composite" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + - parameter body: (body) Input number as post body (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterNumberSerialize(body: OuterNumber? = nil, completion: @escaping ((_ data: OuterNumber?, _ error: ErrorResponse?) -> Void)) { + fakeOuterNumberSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error) + } + } + + + /** + - POST /fake/outer/number + - Test serialization of outer number types + + - examples: [{contentType=application/json, example={ }}] + - parameter body: (body) Input number as post body (optional) + - returns: RequestBuilder + */ + open class func fakeOuterNumberSerializeWithRequestBuilder(body: OuterNumber? = nil) -> RequestBuilder { + let path = "/fake/outer/number" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + - parameter body: (body) Input string as post body (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterStringSerialize(body: OuterString? = nil, completion: @escaping ((_ data: OuterString?, _ error: ErrorResponse?) -> Void)) { + fakeOuterStringSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error) + } + } + + + /** + - POST /fake/outer/string + - Test serialization of outer string types + + - examples: [{contentType=application/json, example={ }}] + - parameter body: (body) Input string as post body (optional) + - returns: RequestBuilder + */ + open class func fakeOuterStringSerializeWithRequestBuilder(body: OuterString? = nil) -> RequestBuilder { + let path = "/fake/outer/string" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + To test \"client\" model + - parameter body: (body) client model + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testClientModel(body: Client, completion: @escaping ((_ data: Client?, _ error: ErrorResponse?) -> Void)) { + testClientModelWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error) + } + } + + + /** + To test \"client\" model + - PATCH /fake + - To test \"client\" model + + - examples: [{contentType=application/json, example={ + "client" : "client" +}}] + - parameter body: (body) client model + - returns: RequestBuilder + */ + open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { + let path = "/fake" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body.encodeToJSON() + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - parameter number: (form) None + - parameter double: (form) None + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter float: (form) None (optional) + - parameter string: (form) None (optional) + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int32? = nil, int32: Int32? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: ISOFullDate? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (response, error) -> Void in + completion(error) + } + } + + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - POST /fake + - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - BASIC: + - type: basic + - name: http_basic_test + - parameter number: (form) None + - parameter double: (form) None + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter float: (form) None (optional) + - parameter string: (form) None (optional) + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + - returns: RequestBuilder + */ + open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int32? = nil, int32: Int32? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: ISOFullDate? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { + let path = "/fake" + let URLString = PetstoreClientAPI.basePath + path + let formParams: [String:Any?] = [ + "integer": integer?.encodeToJSON(), + "int32": int32?.encodeToJSON(), + "int64": int64?.encodeToJSON(), + "number": number, + "float": float, + "double": double, + "string": string, + "pattern_without_delimiter": patternWithoutDelimiter, + "byte": byte, + "binary": binary, + "date": date?.encodeToJSON(), + "dateTime": dateTime?.encodeToJSON(), + "password": password, + "callback": callback + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + * enum for parameter enumFormStringArray + */ + public enum EnumFormStringArray_testEnumParameters: String { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumFormString + */ + public enum EnumFormString_testEnumParameters: String { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumHeaderStringArray + */ + public enum EnumHeaderStringArray_testEnumParameters: String { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumHeaderString + */ + public enum EnumHeaderString_testEnumParameters: String { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumQueryStringArray + */ + public enum EnumQueryStringArray_testEnumParameters: String { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumQueryString + */ + public enum EnumQueryString_testEnumParameters: String { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumQueryInteger + */ + public enum EnumQueryInteger_testEnumParameters: Int32 { + case _1 = 1 + case number2 = -2 + } + + /** + * enum for parameter enumQueryDouble + */ + public enum EnumQueryDouble_testEnumParameters: Double { + case _11 = 1.1 + case number12 = -1.2 + } + + /** + To test enum parameters + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to -efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to -efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in + completion(error) + } + } + + + /** + To test enum parameters + - GET /fake + - To test enum parameters + + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to -efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to -efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) + - returns: RequestBuilder + */ + open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil) -> RequestBuilder { + let path = "/fake" + let URLString = PetstoreClientAPI.basePath + path + let formParams: [String:Any?] = [ + "enum_form_string_array": enumFormStringArray, + "enum_form_string": enumFormString?.rawValue, + "enum_query_double": enumQueryDouble?.rawValue + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "enum_query_string_array": enumQueryStringArray, + "enum_query_string": enumQueryString?.rawValue, + "enum_query_integer": enumQueryInteger?.rawValue + ]) + let nillableHeaders: [String: Any?] = [ + "enum_header_string_array": enumHeaderStringArray, + "enum_header_string": enumHeaderString?.rawValue + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + } + + /** + test json serialization of form data + - parameter param: (form) field1 + - parameter param2: (form) field2 + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (response, error) -> Void in + completion(error) + } + } + + + /** + test json serialization of form data + - GET /fake/jsonFormData + - + + - parameter param: (form) field1 + - parameter param2: (form) field2 + - returns: RequestBuilder + */ + open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { + let path = "/fake/jsonFormData" + let URLString = PetstoreClientAPI.basePath + path + let formParams: [String:Any?] = [ + "param": param, + "param2": param2 + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + +} diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift new file mode 100644 index 00000000000..bc4369df7ae --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift @@ -0,0 +1,49 @@ +// +// Fake_classname_tags123API.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + + +open class Fake_classname_tags123API: APIBase { + /** + To test class name in snake case + - parameter body: (body) client model + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testClassname(body: Client, completion: @escaping ((_ data: Client?, _ error: ErrorResponse?) -> Void)) { + testClassnameWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error) + } + } + + + /** + To test class name in snake case + - PATCH /fake_classname_test + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query + - examples: [{contentType=application/json, example={ + "client" : "client" +}}] + - parameter body: (body) client model + - returns: RequestBuilder + */ + open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { + let path = "/fake_classname_test" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body.encodeToJSON() + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift new file mode 100644 index 00000000000..6de1f336620 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -0,0 +1,563 @@ +// +// PetAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + + +open class PetAPI: APIBase { + /** + Add a new pet to the store + - parameter body: (body) Pet object that needs to be added to the store + - parameter completion: completion handler to receive the data and the error objects + */ + open class func addPet(body: Pet, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(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 + - returns: RequestBuilder + */ + open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { + let path = "/pet" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body.encodeToJSON() + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + Deletes a pet + - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in + completion(error) + } + } + + + /** + Deletes a pet + - DELETE /pet/{petId} + - + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) + - returns: RequestBuilder + */ + open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { + var path = "/pet/{petId}" + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "api_key": apiKey + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + } + + /** + * enum for parameter status + */ + public enum Status_findPetsByStatus: String { + case available = "available" + case pending = "pending" + case sold = "sold" + } + + /** + Finds Pets by status + - parameter status: (query) Status values that need to be considered for filter + - parameter completion: completion handler to receive the data and the error objects + */ + open class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?, _ error: ErrorResponse?) -> Void)) { + findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in + completion(response?.body, error) + } + } + + + /** + Finds Pets by status + - GET /pet/findByStatus + - Multiple status values can be provided with comma separated strings + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example=[ { + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" +}, { + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" +} ]}] + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example=[ { + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" +}, { + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" +} ]}] + - parameter status: (query) Status values that need to be considered for filter + - returns: RequestBuilder<[Pet]> + */ + open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + let path = "/pet/findByStatus" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "status": status + ]) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Finds Pets by tags + - parameter tags: (query) Tags to filter by + - parameter completion: completion handler to receive the data and the error objects + */ + open class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?, _ error: ErrorResponse?) -> Void)) { + findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in + completion(response?.body, error) + } + } + + + /** + Finds Pets by tags + - GET /pet/findByTags + - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example=[ { + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" +}, { + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" +} ]}] + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example=[ { + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" +}, { + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" +} ]}] + - parameter tags: (query) Tags to filter by + - returns: RequestBuilder<[Pet]> + */ + open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { + let path = "/pet/findByTags" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "tags": tags + ]) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Find pet by ID + - parameter petId: (path) ID of pet to return + - parameter completion: completion handler to receive the data and the error objects + */ + open class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?, _ error: ErrorResponse?) -> Void)) { + getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + completion(response?.body, error) + } + } + + + /** + Find pet by ID + - GET /pet/{petId} + - Returns a single pet + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example={ + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" +}}] + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example={ + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" +}}] + - parameter petId: (path) ID of pet to return + - returns: RequestBuilder + */ + open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { + var path = "/pet/{petId}" + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Update an existing pet + - parameter body: (body) Pet object that needs to be added to the store + - parameter completion: completion handler to receive the data and the error objects + */ + open class func updatePet(body: Pet, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(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 + - returns: RequestBuilder + */ + open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { + let path = "/pet" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body.encodeToJSON() + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, 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 + */ + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in + completion(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 + */ + open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { + var path = "/pet/{petId}" + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let formParams: [String:Any?] = [ + "name": name, + "status": status + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, 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 + */ + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?, _ error: ErrorResponse?) -> Void)) { + uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in + completion(response?.body, error) + } + } + + + /** + uploads an image + - POST /pet/{petId}/uploadImage + - + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{contentType=application/json, example={ + "code" : 0, + "type" : "type", + "message" : "message" +}}] + - 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 + */ + open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { + var path = "/pet/{petId}/uploadImage" + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let formParams: [String:Any?] = [ + "additionalMetadata": additionalMetadata, + "file": file + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + +} diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift new file mode 100644 index 00000000000..7d99f10de0c --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -0,0 +1,210 @@ +// +// StoreAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + + +open 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 + */ + open class func deleteOrder(orderId: String, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + completion(error) + } + } + + + /** + Delete purchase order by ID + - DELETE /store/order/{order_id} + - 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 + */ + open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { + var path = "/store/order/{order_id}" + let orderIdPreEscape = "\(orderId)" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Returns pet inventories by status + - parameter completion: completion handler to receive the data and the error objects + */ + open class func getInventory(completion: @escaping ((_ data: [String:Int32]?, _ error: ErrorResponse?) -> Void)) { + getInventoryWithRequestBuilder().execute { (response, error) -> Void in + completion(response?.body, 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" : 0 +}}] + - returns: RequestBuilder<[String:Int32]> + */ + open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int32]> { + let path = "/store/inventory" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + 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 + */ + open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?, _ error: ErrorResponse?) -> Void)) { + getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + completion(response?.body, error) + } + } + + + /** + Find purchase order by ID + - GET /store/order/{order_id} + - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + + - examples: [{contentType=application/xml, example= + 123456789 + 123456789 + 123 + 2000-01-23T04:56:07.000Z + aeiou + true +}, {contentType=application/json, example={ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" +}}] + - examples: [{contentType=application/xml, example= + 123456789 + 123456789 + 123 + 2000-01-23T04:56:07.000Z + aeiou + true +}, {contentType=application/json, example={ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" +}}] + - parameter orderId: (path) ID of pet that needs to be fetched + - returns: RequestBuilder + */ + open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { + var path = "/store/order/{order_id}" + let orderIdPreEscape = "\(orderId)" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Place an order for a pet + - parameter body: (body) order placed for purchasing the pet + - parameter completion: completion handler to receive the data and the error objects + */ + open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?, _ error: ErrorResponse?) -> Void)) { + placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error) + } + } + + + /** + Place an order for a pet + - POST /store/order + - + + - examples: [{contentType=application/xml, example= + 123456789 + 123456789 + 123 + 2000-01-23T04:56:07.000Z + aeiou + true +}, {contentType=application/json, example={ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" +}}] + - examples: [{contentType=application/xml, example= + 123456789 + 123456789 + 123 + 2000-01-23T04:56:07.000Z + aeiou + true +}, {contentType=application/json, example={ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" +}}] + - parameter body: (body) order placed for purchasing the pet + - returns: RequestBuilder + */ + open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { + let path = "/store/order" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body.encodeToJSON() + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift new file mode 100644 index 00000000000..b5bd0d0677a --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -0,0 +1,326 @@ +// +// UserAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + + +open class UserAPI: APIBase { + /** + Create user + - parameter body: (body) Created user object + - parameter completion: completion handler to receive the data and the error objects + */ + open class func createUser(body: User, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error) + } + } + + + /** + Create user + - POST /user + - This can only be done by the logged in user. + + - parameter body: (body) Created user object + - returns: RequestBuilder + */ + open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { + let path = "/user" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body.encodeToJSON() + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + Creates list of users with given input array + - parameter body: (body) List of user object + - parameter completion: completion handler to receive the data and the error objects + */ + open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error) + } + } + + + /** + Creates list of users with given input array + - POST /user/createWithArray + - + + - parameter body: (body) List of user object + - returns: RequestBuilder + */ + open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { + let path = "/user/createWithArray" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body.encodeToJSON() + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + Creates list of users with given input array + - parameter body: (body) List of user object + - parameter completion: completion handler to receive the data and the error objects + */ + open class func createUsersWithListInput(body: [User], completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error) + } + } + + + /** + Creates list of users with given input array + - POST /user/createWithList + - + + - parameter body: (body) List of user object + - returns: RequestBuilder + */ + open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { + let path = "/user/createWithList" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body.encodeToJSON() + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, 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 + */ + open class func deleteUser(username: String, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in + completion(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 + */ + open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { + var path = "/user/{username}" + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + 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 + */ + open class func getUserByName(username: String, completion: @escaping ((_ data: User?, _ error: ErrorResponse?) -> Void)) { + getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in + completion(response?.body, error) + } + } + + + /** + Get user by user name + - GET /user/{username} + - + + - examples: [{contentType=application/xml, example= + 123456789 + aeiou + aeiou + aeiou + aeiou + aeiou + aeiou + 123 +}, {contentType=application/json, example={ + "firstName" : "firstName", + "lastName" : "lastName", + "password" : "password", + "userStatus" : 6, + "phone" : "phone", + "id" : 0, + "email" : "email", + "username" : "username" +}}] + - examples: [{contentType=application/xml, example= + 123456789 + aeiou + aeiou + aeiou + aeiou + aeiou + aeiou + 123 +}, {contentType=application/json, example={ + "firstName" : "firstName", + "lastName" : "lastName", + "password" : "password", + "userStatus" : 6, + "phone" : "phone", + "id" : 0, + "email" : "email", + "username" : "username" +}}] + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - returns: RequestBuilder + */ + open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { + var path = "/user/{username}" + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Logs user into the system + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + - parameter completion: completion handler to receive the data and the error objects + */ + open class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?, _ error: ErrorResponse?) -> Void)) { + loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in + completion(response?.body, error) + } + } + + + /** + Logs user into the system + - GET /user/login + - + + - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] + - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] + - examples: [{contentType=application/xml, example=aeiou}, {contentType=application/json, example=""}] + - examples: [{contentType=application/xml, example=aeiou}, {contentType=application/json, example=""}] + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + - returns: RequestBuilder + */ + open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { + let path = "/user/login" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "username": username, + "password": password + ]) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Logs out current logged in user session + - parameter completion: completion handler to receive the data and the error objects + */ + open class func logoutUser(completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + logoutUserWithRequestBuilder().execute { (response, error) -> Void in + completion(error) + } + } + + + /** + Logs out current logged in user session + - GET /user/logout + - + + - returns: RequestBuilder + */ + open class func logoutUserWithRequestBuilder() -> RequestBuilder { + let path = "/user/logout" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Updated user + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object + - parameter completion: completion handler to receive the data and the error objects + */ + open class func updateUser(username: String, body: User, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in + completion(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 + - returns: RequestBuilder + */ + open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { + var path = "/user/{username}" + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters = body.encodeToJSON() + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift new file mode 100644 index 00000000000..9e84f215801 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -0,0 +1,380 @@ +// AlamofireImplementations.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + +class AlamofireRequestBuilderFactory: RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type { + return AlamofireRequestBuilder.self + } +} + +private struct SynchronizedDictionary { + + private var dictionary = [K: V]() + private let queue = DispatchQueue( + label: "SynchronizedDictionary", + qos: DispatchQoS.userInitiated, + attributes: [DispatchQueue.Attributes.concurrent], + autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, + target: nil + ) + + public subscript(key: K) -> V? { + get { + var value: V? + + queue.sync { + value = self.dictionary[key] + } + + return value + } + set { + queue.sync(flags: DispatchWorkItemFlags.barrier) { + self.dictionary[key] = newValue + } + } + } + +} + +class JSONEncodingWrapper: ParameterEncoding { + var bodyParameters: Any? + var encoding: JSONEncoding = JSONEncoding() + + public init(parameters: Any?) { + self.bodyParameters = parameters + } + + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + return try encoding.encode(urlRequest, withJSONObject: bodyParameters) + } +} + +// Store manager to retain its reference +private var managerStore = SynchronizedDictionary() + +open class AlamofireRequestBuilder: RequestBuilder { + required public init(method: String, URLString: String, parameters: Any?, isBody: Bool, headers: [String : String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) + } + + /** + May be overridden by a subclass if you want to control the session + configuration. + */ + open func createSessionManager() -> Alamofire.SessionManager { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = buildHeaders() + return Alamofire.SessionManager(configuration: configuration) + } + + /** + May be overridden by a subclass if you want to control the Content-Type + that is given to an uploaded form part. + + Return nil to use the default behavior (inferring the Content-Type from + the file extension). Return the desired Content-Type otherwise. + */ + open func contentTypeForFormPart(fileURL: URL) -> String? { + return nil + } + + /** + May be overridden by a subclass if you want to control the request + configuration (e.g. to override the cache policy). + */ + open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String:String]) -> DataRequest { + return manager.request(URLString, method: method, parameters: parameters as? Parameters, encoding: encoding, headers: headers) + } + + override open func execute(_ completion: @escaping (_ response: Response?, _ error: ErrorResponse?) -> Void) { + let managerId:String = UUID().uuidString + // Create a new manager for each request to customize its request header + let manager = createSessionManager() + managerStore[managerId] = manager + + let encoding:ParameterEncoding = isBody ? JSONEncodingWrapper(parameters: parameters) : URLEncoding() + + let xMethod = Alamofire.HTTPMethod(rawValue: method) + + let param = parameters as? Parameters + let fileKeys = param == nil ? [] : param!.filter { $1 is NSURL } + .map { $0.0 } + + if fileKeys.count > 0 { + manager.upload(multipartFormData: { mpForm in + for (k, v) in param! { + switch v { + case let fileURL as URL: + if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { + mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) + } + else { + mpForm.append(fileURL, withName: k) + } + break + case let string as String: + mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) + break + case let number as NSNumber: + mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k) + break + default: + fatalError("Unprocessable value \(v) with key \(k)") + break + } + } + }, to: URLString, method: xMethod!, headers: nil, encodingCompletion: { encodingResult in + switch encodingResult { + case .success(let upload, _, _): + if let onProgressReady = self.onProgressReady { + onProgressReady(upload.uploadProgress) + } + self.processRequest(request: upload, managerId, completion) + case .failure(let encodingError): + completion(nil, ErrorResponse.HttpError(statusCode: 415, data: nil, error: encodingError)) + } + }) + } else { + let request = makeRequest(manager: manager, method: xMethod!, encoding: encoding, headers: headers) + if let onProgressReady = self.onProgressReady { + onProgressReady(request.progress) + } + processRequest(request: request, managerId, completion) + } + + } + + private func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response?, _ error: ErrorResponse?) -> Void) { + if let credential = self.credential { + request.authenticate(usingCredential: credential) + } + + let cleanupRequest = { + managerStore[managerId] = nil + } + + let validatedRequest = request.validate() + + switch T.self { + case is String.Type: + validatedRequest.responseString(completionHandler: { (stringResponse) in + cleanupRequest() + + if stringResponse.result.isFailure { + completion( + nil, + ErrorResponse.HttpError(statusCode: stringResponse.response?.statusCode ?? 500, data: stringResponse.data, error: stringResponse.result.error as Error!) + ) + return + } + + completion( + Response( + response: stringResponse.response!, + body: ((stringResponse.result.value ?? "") as! T) + ), + nil + ) + }) + case is Void.Type: + validatedRequest.responseData(completionHandler: { (voidResponse) in + cleanupRequest() + + if voidResponse.result.isFailure { + completion( + nil, + ErrorResponse.HttpError(statusCode: voidResponse.response?.statusCode ?? 500, data: voidResponse.data, error: voidResponse.result.error!) + ) + return + } + + completion( + Response( + response: voidResponse.response!, + body: nil), + nil + ) + }) + case is Data.Type: + validatedRequest.responseData(completionHandler: { (dataResponse) in + cleanupRequest() + + if (dataResponse.result.isFailure) { + completion( + nil, + ErrorResponse.HttpError(statusCode: dataResponse.response?.statusCode ?? 500, data: dataResponse.data, error: dataResponse.result.error!) + ) + return + } + + completion( + Response( + response: dataResponse.response!, + body: (dataResponse.data as! T) + ), + nil + ) + }) + case is URL.Type: + validatedRequest.responseData(completionHandler: { (dataResponse) in + cleanupRequest() + + do { + + guard !dataResponse.result.isFailure else { + throw DownloadException.responseFailed + } + + guard let data = dataResponse.data else { + throw DownloadException.responseDataMissing + } + + guard let request = request.request else { + throw DownloadException.requestMissing + } + + let fileManager = FileManager.default + let urlRequest = try request.asURLRequest() + let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let requestURL = try self.getURL(from: urlRequest) + + var requestPath = try self.getPath(from: requestURL) + + if let headerFileName = self.getFileName(fromContentDisposition: dataResponse.response?.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } + + let filePath = documentsDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion( + Response( + response: dataResponse.response!, + body: (filePath as! T) + ), + nil + ) + + } catch let requestParserError as DownloadException { + completion(nil, ErrorResponse.HttpError(statusCode: 400, data: dataResponse.data, error: requestParserError)) + } catch let error { + completion(nil, ErrorResponse.HttpError(statusCode: 400, data: dataResponse.data, error: error)) + } + return + }) + default: + validatedRequest.responseJSON(options: .allowFragments) { response in + cleanupRequest() + + if response.result.isFailure { + completion(nil, ErrorResponse.HttpError(statusCode: response.response?.statusCode ?? 500, data: response.data, error: response.result.error!)) + return + } + + // handle HTTP 204 No Content + // NSNull would crash decoders + if response.response?.statusCode == 204 && response.result.value is NSNull{ + completion(nil, nil) + return + } + + if () is T { + completion(Response(response: response.response!, body: (() as! T)), nil) + return + } + if let json: Any = response.result.value { + let decoded = Decoders.decode(clazz: T.self, source: json as AnyObject, instance: nil) + switch decoded { + case let .success(object): completion(Response(response: response.response!, body: object), nil) + case let .failure(error): completion(nil, ErrorResponse.DecodeError(response: response.data, decodeError: error)) + } + 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!, body: ("" as! T)), nil) + return + } + + completion(nil, ErrorResponse.HttpError(statusCode: 500, data: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"]))) + } + } + } + + open func buildHeaders() -> [String: String] { + var httpHeaders = SessionManager.defaultHTTPHeaders + for (key, value) in self.headers { + httpHeaders[key] = value + } + return httpHeaders + } + + fileprivate func getFileName(fromContentDisposition contentDisposition : String?) -> String? { + + guard let contentDisposition = contentDisposition else { + return nil + } + + let items = contentDisposition.components(separatedBy: ";") + + var filename : String? = nil + + for contentItem in items { + + let filenameKey = "filename=" + guard let range = contentItem.range(of: filenameKey) else { + break + } + + filename = contentItem + return filename? + .replacingCharacters(in: range, with:"") + .replacingOccurrences(of: "\"", with: "") + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + return filename + + } + + fileprivate func getPath(from url : URL) throws -> String { + + guard var path = NSURLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + throw DownloadException.requestMissingPath + } + + if path.hasPrefix("/") { + path.remove(at: path.startIndex) + } + + return path + + } + + fileprivate func getURL(from urlRequest : URLRequest) throws -> URL { + + guard let url = urlRequest.url else { + throw DownloadException.requestMissingURL + } + + return url + } +} + +fileprivate enum DownloadException : Error { + case responseDataMissing + case responseFailed + case requestMissing + case requestMissingPath + case requestMissingURL +} \ No newline at end of file diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Configuration.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Configuration.swift new file mode 100644 index 00000000000..c03a10b930c --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Configuration.swift @@ -0,0 +1,15 @@ +// Configuration.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +open class Configuration { + + // This value is used to configure the date formatter that is used to serialize dates into JSON format. + // You must set it prior to encoding any dates, and it will only be read once. + open static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + +} \ No newline at end of file diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Extensions.swift new file mode 100644 index 00000000000..d310882b908 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -0,0 +1,187 @@ +// Extensions.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + +extension Bool: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Float: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Int: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Int32: JSONEncodable { + func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } +} + +extension Int64: JSONEncodable { + func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } +} + +extension Double: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension String: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +private func encodeIfPossible(_ object: T) -> Any { + if let encodableObject = object as? JSONEncodable { + return encodableObject.encodeToJSON() + } else { + return object as Any + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> Any { + return self.map(encodeIfPossible) + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> Any { + var dictionary = [AnyHashable: Any]() + for (key, value) in self { + dictionary[key as! NSObject] = encodeIfPossible(value) + } + return dictionary as Any + } +} + +extension Data: JSONEncodable { + func encodeToJSON() -> Any { + return self.base64EncodedString(options: Data.Base64EncodingOptions()) + } +} + +private let dateFormatter: DateFormatter = { + let fmt = DateFormatter() + fmt.dateFormat = Configuration.dateFormat + fmt.locale = Locale(identifier: "en_US_POSIX") + return fmt +}() + +extension Date: JSONEncodable { + func encodeToJSON() -> Any { + return dateFormatter.string(from: self) as Any + } +} + +extension UUID: JSONEncodable { + func encodeToJSON() -> Any { + return self.uuidString + } +} + +/// Represents an ISO-8601 full-date (RFC-3339). +/// ex: 12-31-1999 +/// https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14 +public final class ISOFullDate: CustomStringConvertible { + + public let year: Int + public let month: Int + public let day: Int + + public init(year: Int, month: Int, day: Int) { + self.year = year + self.month = month + self.day = day + } + + /** + Converts a Date to an ISOFullDate. Only interested in the year, month, day components. + + - parameter date: The date to convert. + + - returns: An ISOFullDate constructed from the year, month, day of the date. + */ + public static func from(date: Date) -> ISOFullDate? { + let calendar = Calendar(identifier: .gregorian) + + let components = calendar.dateComponents( + [ + .year, + .month, + .day, + ], + from: date + ) + + guard + let year = components.year, + let month = components.month, + let day = components.day + else { + return nil + } + + return ISOFullDate( + year: year, + month: month, + day: day + ) + } + + /** + Converts a ISO-8601 full-date string to an ISOFullDate. + + - parameter string: The ISO-8601 full-date format string to convert. + + - returns: An ISOFullDate constructed from the string. + */ + public static func from(string: String) -> ISOFullDate? { + let components = string + .characters + .split(separator: "-") + .map(String.init) + .flatMap { Int($0) } + guard components.count == 3 else { return nil } + + return ISOFullDate( + year: components[0], + month: components[1], + day: components[2] + ) + } + + /** + Converts the receiver to a Date, in the default time zone. + + - returns: A Date from the components of the receiver, in the default time zone. + */ + public func toDate() -> Date? { + var components = DateComponents() + components.year = year + components.month = month + components.day = day + components.timeZone = TimeZone.ReferenceType.default + let calendar = Calendar(identifier: .gregorian) + return calendar.date(from: components) + } + + // MARK: CustomStringConvertible + + public var description: String { + return "\(year)-\(month)-\(day)" + } + +} + +extension ISOFullDate: JSONEncodable { + public func encodeToJSON() -> Any { + return "\(year)-\(month)-\(day)" + } +} + + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models.swift new file mode 100644 index 00000000000..bc8a01e8844 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models.swift @@ -0,0 +1,1331 @@ +// Models.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +protocol JSONEncodable { + func encodeToJSON() -> Any +} + +public enum ErrorResponse : Error { + case HttpError(statusCode: Int, data: Data?, error: Error) + case DecodeError(response: Data?, decodeError: DecodeError) +} + +open class Response { + open let statusCode: Int + open let header: [String: String] + open 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: HTTPURLResponse, 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) + } +} + +public enum Decoded { + case success(ValueType) + case failure(DecodeError) +} + +public extension Decoded { + var value: ValueType? { + switch self { + case let .success(value): + return value + case .failure: + return nil + } + } +} + +public enum DecodeError { + case typeMismatch(expected: String, actual: String) + case missingKey(key: String) + case parseError(message: String) +} + +private var once = Int() +class Decoders { + static fileprivate var decoders = Dictionary AnyObject)>() + + static func addDecoder(clazz: T.Type, decoder: @escaping ((AnyObject, AnyObject?) -> Decoded)) { + let key = "\(T.self)" + decoders[key] = { decoder($0, $1) as AnyObject } + } + + static func decode(clazz: T.Type, discriminator: String, source: AnyObject) -> Decoded { + let key = discriminator + if let decoder = decoders[key], let value = decoder(source, nil) as? Decoded { + return value + } else { + return .failure(.typeMismatch(expected: String(describing: clazz), actual: String(describing: source))) + } + } + + static func decode(clazz: [T].Type, source: AnyObject) -> Decoded<[T]> { + if let sourceArray = source as? [AnyObject] { + var values = [T]() + for sourceValue in sourceArray { + switch Decoders.decode(clazz: T.self, source: sourceValue, instance: nil) { + case let .success(value): + values.append(value) + case let .failure(error): + return .failure(error) + } + } + return .success(values) + } else { + return .failure(.typeMismatch(expected: String(describing: clazz), actual: String(describing: source))) + } + } + + static func decode(clazz: T.Type, source: AnyObject) -> Decoded { + switch Decoders.decode(clazz: T.self, source: source, instance: nil) { + case let .success(value): + return .success(value) + case let .failure(error): + return .failure(error) + } + } + + static open func decode(clazz: T.Type, source: AnyObject) -> Decoded { + if let value = source as? T.RawValue { + if let enumValue = T.init(rawValue: value) { + return .success(enumValue) + } else { + return .failure(.typeMismatch(expected: "A value from the enumeration \(T.self)", actual: "\(value)")) + } + } else { + return .failure(.typeMismatch(expected: "\(T.RawValue.self) matching a case from the enumeration \(T.self)", actual: String(describing: type(of: source)))) + } + } + + static func decode(clazz: [Key:T].Type, source: AnyObject) -> Decoded<[Key:T]> { + if let sourceDictionary = source as? [Key: AnyObject] { + var dictionary = [Key:T]() + for (key, value) in sourceDictionary { + switch Decoders.decode(clazz: T.self, source: value, instance: nil) { + case let .success(value): + dictionary[key] = value + case let .failure(error): + return .failure(error) + } + } + return .success(dictionary) + } else { + return .failure(.typeMismatch(expected: String(describing: clazz), actual: String(describing: source))) + } + } + + static func decodeOptional(clazz: T.Type, source: AnyObject?) -> Decoded { + guard !(source is NSNull), source != nil else { return .success(nil) } + if let value = source as? T.RawValue { + if let enumValue = T.init(rawValue: value) { + return .success(enumValue) + } else { + return .failure(.typeMismatch(expected: "A value from the enumeration \(T.self)", actual: "\(value)")) + } + } else { + return .failure(.typeMismatch(expected: "\(T.RawValue.self) matching a case from the enumeration \(T.self)", actual: String(describing: type(of: source)))) + } + } + + static func decode(clazz: T.Type, source: AnyObject, instance: AnyObject?) -> Decoded { + initialize() + if let sourceNumber = source as? NSNumber, let value = sourceNumber.int32Value as? T, T.self is Int32.Type { + return .success(value) + } + if let sourceNumber = source as? NSNumber, let value = sourceNumber.int32Value as? T, T.self is Int64.Type { + return .success(value) + } + if let intermediate = source as? String, let value = UUID(uuidString: intermediate) as? T, source is String, T.self is UUID.Type { + return .success(value) + } + if let value = source as? T { + return .success(value) + } + if let intermediate = source as? String, let value = Data(base64Encoded: intermediate) as? T { + return .success(value) + } + + let key = "\(T.self)" + if let decoder = decoders[key], let value = decoder(source, instance) as? Decoded { + return value + } else { + return .failure(.typeMismatch(expected: String(describing: clazz), actual: String(describing: source))) + } + } + + //Convert a Decoded so that its value is optional. DO WE STILL NEED THIS? + static func toOptional(decoded: Decoded) -> Decoded { + return .success(decoded.value) + } + + static func decodeOptional(clazz: T.Type, source: AnyObject?) -> Decoded { + if let source = source, !(source is NSNull) { + switch Decoders.decode(clazz: clazz, source: source, instance: nil) { + case let .success(value): return .success(value) + case let .failure(error): return .failure(error) + } + } else { + return .success(nil) + } + } + + static func decodeOptional(clazz: [T].Type, source: AnyObject?) -> Decoded<[T]?> where T: RawRepresentable { + if let source = source as? [AnyObject] { + var values = [T]() + for sourceValue in source { + switch Decoders.decodeOptional(clazz: T.self, source: sourceValue) { + case let .success(value): if let value = value { values.append(value) } + case let .failure(error): return .failure(error) + } + } + return .success(values) + } else { + return .success(nil) + } + } + + static func decodeOptional(clazz: [T].Type, source: AnyObject?) -> Decoded<[T]?> { + if let source = source as? [AnyObject] { + var values = [T]() + for sourceValue in source { + switch Decoders.decode(clazz: T.self, source: sourceValue, instance: nil) { + case let .success(value): values.append(value) + case let .failure(error): return .failure(error) + } + } + return .success(values) + } else { + return .success(nil) + } + } + + static func decodeOptional(clazz: [Key:T].Type, source: AnyObject?) -> Decoded<[Key:T]?> { + if let sourceDictionary = source as? [Key: AnyObject] { + var dictionary = [Key:T]() + for (key, value) in sourceDictionary { + switch Decoders.decode(clazz: T.self, source: value, instance: nil) { + case let .success(value): dictionary[key] = value + case let .failure(error): return .failure(error) + } + } + return .success(dictionary) + } else { + return .success(nil) + } + } + + static func decodeOptional(clazz: T, source: AnyObject) -> Decoded where T.RawValue == U { + if let value = source as? U { + if let enumValue = T.init(rawValue: value) { + return .success(enumValue) + } else { + return .failure(.typeMismatch(expected: "A value from the enumeration \(T.self)", actual: "\(value)")) + } + } else { + return .failure(.typeMismatch(expected: "String", actual: String(describing: type(of: source)))) + } + } + + + private static var __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", + "yyyy-MM-dd HH:mm:ss" + ].map { (format: String) -> DateFormatter in + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.dateFormat = format + return formatter + } + // Decoder for Date + Decoders.addDecoder(clazz: Date.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceString = source as? String { + for formatter in formatters { + if let date = formatter.date(from: sourceString) { + return .success(date) + } + } + } + if let sourceInt = source as? Int { + // treat as a java date + return .success(Date(timeIntervalSince1970: Double(sourceInt / 1000) )) + } + if source is String || source is Int { + return .failure(.parseError(message: "Could not decode date")) + } else { + return .failure(.typeMismatch(expected: "String or Int", actual: "\(source)")) + } + } + + // Decoder for ISOFullDate + Decoders.addDecoder(clazz: ISOFullDate.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let string = source as? String, + let isoDate = ISOFullDate.from(string: string) { + return .success(isoDate) + } else { + return .failure(.typeMismatch(expected: "ISO date", actual: "\(source)")) + } + } + + // Decoder for [AdditionalPropertiesClass] + Decoders.addDecoder(clazz: [AdditionalPropertiesClass].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[AdditionalPropertiesClass]> in + return Decoders.decode(clazz: [AdditionalPropertiesClass].self, source: source) + } + + // Decoder for AdditionalPropertiesClass + Decoders.addDecoder(clazz: AdditionalPropertiesClass.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? AdditionalPropertiesClass() : instance as! AdditionalPropertiesClass + switch Decoders.decodeOptional(clazz: [String:String].self, source: sourceDictionary["map_property"] as AnyObject?) { + + case let .success(value): _result.mapProperty = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: [String:[String:String]].self, source: sourceDictionary["map_of_map_property"] as AnyObject?) { + + case let .success(value): _result.mapOfMapProperty = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "AdditionalPropertiesClass", actual: "\(source)")) + } + } + // Decoder for [Animal] + Decoders.addDecoder(clazz: [Animal].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[Animal]> in + return Decoders.decode(clazz: [Animal].self, source: source) + } + + // Decoder for Animal + Decoders.addDecoder(clazz: Animal.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + // Check discriminator to support inheritance + if let discriminator = sourceDictionary["className"] as? String, instance == nil && discriminator != "Animal"{ + return Decoders.decode(clazz: Animal.self, discriminator: discriminator, source: source) + } + let _result = instance == nil ? Animal() : instance as! Animal + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["className"] as AnyObject?) { + + case let .success(value): _result.className = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["color"] as AnyObject?) { + + case let .success(value): _result.color = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "Animal", actual: "\(source)")) + } + } + // Decoder for [ApiResponse] + Decoders.addDecoder(clazz: [ApiResponse].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[ApiResponse]> in + return Decoders.decode(clazz: [ApiResponse].self, source: source) + } + + // Decoder for ApiResponse + Decoders.addDecoder(clazz: ApiResponse.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? ApiResponse() : instance as! ApiResponse + switch Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["code"] as AnyObject?) { + + case let .success(value): _result.code = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["type"] as AnyObject?) { + + case let .success(value): _result.type = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["message"] as AnyObject?) { + + case let .success(value): _result.message = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "ApiResponse", actual: "\(source)")) + } + } + // Decoder for [ArrayOfArrayOfNumberOnly] + Decoders.addDecoder(clazz: [ArrayOfArrayOfNumberOnly].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[ArrayOfArrayOfNumberOnly]> in + return Decoders.decode(clazz: [ArrayOfArrayOfNumberOnly].self, source: source) + } + + // Decoder for ArrayOfArrayOfNumberOnly + Decoders.addDecoder(clazz: ArrayOfArrayOfNumberOnly.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? ArrayOfArrayOfNumberOnly() : instance as! ArrayOfArrayOfNumberOnly + switch Decoders.decodeOptional(clazz: [[Double]].self, source: sourceDictionary["ArrayArrayNumber"] as AnyObject?) { + + case let .success(value): _result.arrayArrayNumber = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "ArrayOfArrayOfNumberOnly", actual: "\(source)")) + } + } + // Decoder for [ArrayOfNumberOnly] + Decoders.addDecoder(clazz: [ArrayOfNumberOnly].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[ArrayOfNumberOnly]> in + return Decoders.decode(clazz: [ArrayOfNumberOnly].self, source: source) + } + + // Decoder for ArrayOfNumberOnly + Decoders.addDecoder(clazz: ArrayOfNumberOnly.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? ArrayOfNumberOnly() : instance as! ArrayOfNumberOnly + switch Decoders.decodeOptional(clazz: [Double].self, source: sourceDictionary["ArrayNumber"] as AnyObject?) { + + case let .success(value): _result.arrayNumber = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "ArrayOfNumberOnly", actual: "\(source)")) + } + } + // Decoder for [ArrayTest] + Decoders.addDecoder(clazz: [ArrayTest].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[ArrayTest]> in + return Decoders.decode(clazz: [ArrayTest].self, source: source) + } + + // Decoder for ArrayTest + Decoders.addDecoder(clazz: ArrayTest.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? ArrayTest() : instance as! ArrayTest + switch Decoders.decodeOptional(clazz: [String].self, source: sourceDictionary["array_of_string"] as AnyObject?) { + + case let .success(value): _result.arrayOfString = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: [[Int64]].self, source: sourceDictionary["array_array_of_integer"] as AnyObject?) { + + case let .success(value): _result.arrayArrayOfInteger = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: [[ReadOnlyFirst]].self, source: sourceDictionary["array_array_of_model"] as AnyObject?) { + + case let .success(value): _result.arrayArrayOfModel = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "ArrayTest", actual: "\(source)")) + } + } + // Decoder for [Capitalization] + Decoders.addDecoder(clazz: [Capitalization].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[Capitalization]> in + return Decoders.decode(clazz: [Capitalization].self, source: source) + } + + // Decoder for Capitalization + Decoders.addDecoder(clazz: Capitalization.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? Capitalization() : instance as! Capitalization + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["smallCamel"] as AnyObject?) { + + case let .success(value): _result.smallCamel = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["CapitalCamel"] as AnyObject?) { + + case let .success(value): _result.capitalCamel = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["small_Snake"] as AnyObject?) { + + case let .success(value): _result.smallSnake = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["Capital_Snake"] as AnyObject?) { + + case let .success(value): _result.capitalSnake = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["SCA_ETH_Flow_Points"] as AnyObject?) { + + case let .success(value): _result.sCAETHFlowPoints = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["ATT_NAME"] as AnyObject?) { + + case let .success(value): _result.ATT_NAME = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "Capitalization", actual: "\(source)")) + } + } + // Decoder for [Category] + Decoders.addDecoder(clazz: [Category].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[Category]> in + return Decoders.decode(clazz: [Category].self, source: source) + } + + // Decoder for Category + Decoders.addDecoder(clazz: Category.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? Category() : instance as! Category + switch Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"] as AnyObject?) { + + case let .success(value): _result.id = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"] as AnyObject?) { + + case let .success(value): _result.name = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "Category", actual: "\(source)")) + } + } + // Decoder for [ClassModel] + Decoders.addDecoder(clazz: [ClassModel].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[ClassModel]> in + return Decoders.decode(clazz: [ClassModel].self, source: source) + } + + // Decoder for ClassModel + Decoders.addDecoder(clazz: ClassModel.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? ClassModel() : instance as! ClassModel + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["_class"] as AnyObject?) { + + case let .success(value): _result._class = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "ClassModel", actual: "\(source)")) + } + } + // Decoder for [Client] + Decoders.addDecoder(clazz: [Client].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[Client]> in + return Decoders.decode(clazz: [Client].self, source: source) + } + + // Decoder for Client + Decoders.addDecoder(clazz: Client.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? Client() : instance as! Client + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["client"] as AnyObject?) { + + case let .success(value): _result.client = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "Client", actual: "\(source)")) + } + } + // Decoder for [EnumArrays] + Decoders.addDecoder(clazz: [EnumArrays].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[EnumArrays]> in + return Decoders.decode(clazz: [EnumArrays].self, source: source) + } + + // Decoder for EnumArrays + Decoders.addDecoder(clazz: EnumArrays.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? EnumArrays() : instance as! EnumArrays + switch Decoders.decodeOptional(clazz: EnumArrays.JustSymbol.self, source: sourceDictionary["just_symbol"] as AnyObject?) { + + case let .success(value): _result.justSymbol = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["array_enum"] as AnyObject?) { + + case let .success(value): _result.arrayEnum = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "EnumArrays", actual: "\(source)")) + } + } + // Decoder for [EnumClass] + Decoders.addDecoder(clazz: [EnumClass].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[EnumClass]> in + return Decoders.decode(clazz: [EnumClass].self, source: source) + } + + // Decoder for EnumClass + Decoders.addDecoder(clazz: EnumClass.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + //TODO: I don't think we need this anymore + return Decoders.decode(clazz: EnumClass.self, source: source, instance: instance) + } + // Decoder for [EnumTest] + Decoders.addDecoder(clazz: [EnumTest].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[EnumTest]> in + return Decoders.decode(clazz: [EnumTest].self, source: source) + } + + // Decoder for EnumTest + Decoders.addDecoder(clazz: EnumTest.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? EnumTest() : instance as! EnumTest + switch Decoders.decodeOptional(clazz: EnumTest.EnumString.self, source: sourceDictionary["enum_string"] as AnyObject?) { + + case let .success(value): _result.enumString = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: EnumTest.EnumInteger.self, source: sourceDictionary["enum_integer"] as AnyObject?) { + + case let .success(value): _result.enumInteger = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: EnumTest.EnumNumber.self, source: sourceDictionary["enum_number"] as AnyObject?) { + + case let .success(value): _result.enumNumber = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: OuterEnum.self, source: sourceDictionary["outerEnum"] as AnyObject?) { + + case let .success(value): _result.outerEnum = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "EnumTest", actual: "\(source)")) + } + } + // Decoder for [FormatTest] + Decoders.addDecoder(clazz: [FormatTest].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[FormatTest]> in + return Decoders.decode(clazz: [FormatTest].self, source: source) + } + + // Decoder for FormatTest + Decoders.addDecoder(clazz: FormatTest.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? FormatTest() : instance as! FormatTest + switch Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["integer"] as AnyObject?) { + + case let .success(value): _result.integer = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["int32"] as AnyObject?) { + + case let .success(value): _result.int32 = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["int64"] as AnyObject?) { + + case let .success(value): _result.int64 = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Double.self, source: sourceDictionary["number"] as AnyObject?) { + + case let .success(value): _result.number = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Float.self, source: sourceDictionary["float"] as AnyObject?) { + + case let .success(value): _result.float = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Double.self, source: sourceDictionary["double"] as AnyObject?) { + + case let .success(value): _result.double = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["string"] as AnyObject?) { + + case let .success(value): _result.string = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Data.self, source: sourceDictionary["byte"] as AnyObject?) { + + case let .success(value): _result.byte = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Data.self, source: sourceDictionary["binary"] as AnyObject?) { + + case let .success(value): _result.binary = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: ISOFullDate.self, source: sourceDictionary["date"] as AnyObject?) { + + case let .success(value): _result.date = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Date.self, source: sourceDictionary["dateTime"] as AnyObject?) { + + case let .success(value): _result.dateTime = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: UUID.self, source: sourceDictionary["uuid"] as AnyObject?) { + + case let .success(value): _result.uuid = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["password"] as AnyObject?) { + + case let .success(value): _result.password = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "FormatTest", actual: "\(source)")) + } + } + // Decoder for [HasOnlyReadOnly] + Decoders.addDecoder(clazz: [HasOnlyReadOnly].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[HasOnlyReadOnly]> in + return Decoders.decode(clazz: [HasOnlyReadOnly].self, source: source) + } + + // Decoder for HasOnlyReadOnly + Decoders.addDecoder(clazz: HasOnlyReadOnly.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? HasOnlyReadOnly() : instance as! HasOnlyReadOnly + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["bar"] as AnyObject?) { + + case let .success(value): _result.bar = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["foo"] as AnyObject?) { + + case let .success(value): _result.foo = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "HasOnlyReadOnly", actual: "\(source)")) + } + } + // Decoder for [List] + Decoders.addDecoder(clazz: [List].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[List]> in + return Decoders.decode(clazz: [List].self, source: source) + } + + // Decoder for List + Decoders.addDecoder(clazz: List.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? List() : instance as! List + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["123-list"] as AnyObject?) { + + case let .success(value): _result._123List = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "List", actual: "\(source)")) + } + } + // Decoder for [MapTest] + Decoders.addDecoder(clazz: [MapTest].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[MapTest]> in + return Decoders.decode(clazz: [MapTest].self, source: source) + } + + // Decoder for MapTest + Decoders.addDecoder(clazz: MapTest.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? MapTest() : instance as! MapTest + switch Decoders.decodeOptional(clazz: [String:[String:String]].self, source: sourceDictionary["map_map_of_string"] as AnyObject?) { + + case let .success(value): _result.mapMapOfString = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: MapTest.MapOfEnumString.self, source: sourceDictionary["map_of_enum_string"] as AnyObject?) { + /* + case let .success(value): _result.mapOfEnumString = value + case let .failure(error): break + */ default: break //TODO: handle enum map scenario + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "MapTest", actual: "\(source)")) + } + } + // Decoder for [MixedPropertiesAndAdditionalPropertiesClass] + Decoders.addDecoder(clazz: [MixedPropertiesAndAdditionalPropertiesClass].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[MixedPropertiesAndAdditionalPropertiesClass]> in + return Decoders.decode(clazz: [MixedPropertiesAndAdditionalPropertiesClass].self, source: source) + } + + // Decoder for MixedPropertiesAndAdditionalPropertiesClass + Decoders.addDecoder(clazz: MixedPropertiesAndAdditionalPropertiesClass.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? MixedPropertiesAndAdditionalPropertiesClass() : instance as! MixedPropertiesAndAdditionalPropertiesClass + switch Decoders.decodeOptional(clazz: UUID.self, source: sourceDictionary["uuid"] as AnyObject?) { + + case let .success(value): _result.uuid = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Date.self, source: sourceDictionary["dateTime"] as AnyObject?) { + + case let .success(value): _result.dateTime = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: [String:Animal].self, source: sourceDictionary["map"] as AnyObject?) { + + case let .success(value): _result.map = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "MixedPropertiesAndAdditionalPropertiesClass", actual: "\(source)")) + } + } + // Decoder for [Model200Response] + Decoders.addDecoder(clazz: [Model200Response].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[Model200Response]> in + return Decoders.decode(clazz: [Model200Response].self, source: source) + } + + // Decoder for Model200Response + Decoders.addDecoder(clazz: Model200Response.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? Model200Response() : instance as! Model200Response + switch Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["name"] as AnyObject?) { + + case let .success(value): _result.name = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["class"] as AnyObject?) { + + case let .success(value): _result._class = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "Model200Response", actual: "\(source)")) + } + } + // Decoder for [Name] + Decoders.addDecoder(clazz: [Name].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[Name]> in + return Decoders.decode(clazz: [Name].self, source: source) + } + + // Decoder for Name + Decoders.addDecoder(clazz: Name.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? Name() : instance as! Name + switch Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["name"] as AnyObject?) { + + case let .success(value): _result.name = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["snake_case"] as AnyObject?) { + + case let .success(value): _result.snakeCase = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["property"] as AnyObject?) { + + case let .success(value): _result.property = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["123Number"] as AnyObject?) { + + case let .success(value): _result._123Number = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "Name", actual: "\(source)")) + } + } + // Decoder for [NumberOnly] + Decoders.addDecoder(clazz: [NumberOnly].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[NumberOnly]> in + return Decoders.decode(clazz: [NumberOnly].self, source: source) + } + + // Decoder for NumberOnly + Decoders.addDecoder(clazz: NumberOnly.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? NumberOnly() : instance as! NumberOnly + switch Decoders.decodeOptional(clazz: Double.self, source: sourceDictionary["JustNumber"] as AnyObject?) { + + case let .success(value): _result.justNumber = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "NumberOnly", actual: "\(source)")) + } + } + // Decoder for [Order] + Decoders.addDecoder(clazz: [Order].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[Order]> in + return Decoders.decode(clazz: [Order].self, source: source) + } + + // Decoder for Order + Decoders.addDecoder(clazz: Order.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? Order() : instance as! Order + switch Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"] as AnyObject?) { + + case let .success(value): _result.id = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["petId"] as AnyObject?) { + + case let .success(value): _result.petId = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["quantity"] as AnyObject?) { + + case let .success(value): _result.quantity = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Date.self, source: sourceDictionary["shipDate"] as AnyObject?) { + + case let .success(value): _result.shipDate = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Order.Status.self, source: sourceDictionary["status"] as AnyObject?) { + + case let .success(value): _result.status = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["complete"] as AnyObject?) { + + case let .success(value): _result.complete = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "Order", actual: "\(source)")) + } + } + // Decoder for [OuterBoolean] + Decoders.addDecoder(clazz: [OuterBoolean].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[OuterBoolean]> in + return Decoders.decode(clazz: [OuterBoolean].self, source: source) + } + + // Decoder for OuterBoolean + Decoders.addDecoder(clazz: OuterBoolean.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let source = source as? OuterBoolean { + return .success(source) + } else { + return .failure(.typeMismatch(expected: "Typealias OuterBoolean", actual: "\(source)")) + } + } + // Decoder for [OuterComposite] + Decoders.addDecoder(clazz: [OuterComposite].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[OuterComposite]> in + return Decoders.decode(clazz: [OuterComposite].self, source: source) + } + + // Decoder for OuterComposite + Decoders.addDecoder(clazz: OuterComposite.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? OuterComposite() : instance as! OuterComposite + switch Decoders.decodeOptional(clazz: OuterNumber.self, source: sourceDictionary["my_number"] as AnyObject?) { + + case let .success(value): _result.myNumber = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: OuterString.self, source: sourceDictionary["my_string"] as AnyObject?) { + + case let .success(value): _result.myString = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: OuterBoolean.self, source: sourceDictionary["my_boolean"] as AnyObject?) { + + case let .success(value): _result.myBoolean = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "OuterComposite", actual: "\(source)")) + } + } + // Decoder for [OuterEnum] + Decoders.addDecoder(clazz: [OuterEnum].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[OuterEnum]> in + return Decoders.decode(clazz: [OuterEnum].self, source: source) + } + + // Decoder for OuterEnum + Decoders.addDecoder(clazz: OuterEnum.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + //TODO: I don't think we need this anymore + return Decoders.decode(clazz: OuterEnum.self, source: source, instance: instance) + } + // Decoder for [OuterNumber] + Decoders.addDecoder(clazz: [OuterNumber].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[OuterNumber]> in + return Decoders.decode(clazz: [OuterNumber].self, source: source) + } + + // Decoder for OuterNumber + Decoders.addDecoder(clazz: OuterNumber.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let source = source as? OuterNumber { + return .success(source) + } else { + return .failure(.typeMismatch(expected: "Typealias OuterNumber", actual: "\(source)")) + } + } + // Decoder for [OuterString] + Decoders.addDecoder(clazz: [OuterString].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[OuterString]> in + return Decoders.decode(clazz: [OuterString].self, source: source) + } + + // Decoder for OuterString + Decoders.addDecoder(clazz: OuterString.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let source = source as? OuterString { + return .success(source) + } else { + return .failure(.typeMismatch(expected: "Typealias OuterString", actual: "\(source)")) + } + } + // Decoder for [Pet] + Decoders.addDecoder(clazz: [Pet].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[Pet]> in + return Decoders.decode(clazz: [Pet].self, source: source) + } + + // Decoder for Pet + Decoders.addDecoder(clazz: Pet.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? Pet() : instance as! Pet + switch Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"] as AnyObject?) { + + case let .success(value): _result.id = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Category.self, source: sourceDictionary["category"] as AnyObject?) { + + case let .success(value): _result.category = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"] as AnyObject?) { + + case let .success(value): _result.name = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: [String].self, source: sourceDictionary["photoUrls"] as AnyObject?) { + + case let .success(value): _result.photoUrls = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: [Tag].self, source: sourceDictionary["tags"] as AnyObject?) { + + case let .success(value): _result.tags = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Pet.Status.self, source: sourceDictionary["status"] as AnyObject?) { + + case let .success(value): _result.status = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "Pet", actual: "\(source)")) + } + } + // Decoder for [ReadOnlyFirst] + Decoders.addDecoder(clazz: [ReadOnlyFirst].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[ReadOnlyFirst]> in + return Decoders.decode(clazz: [ReadOnlyFirst].self, source: source) + } + + // Decoder for ReadOnlyFirst + Decoders.addDecoder(clazz: ReadOnlyFirst.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? ReadOnlyFirst() : instance as! ReadOnlyFirst + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["bar"] as AnyObject?) { + + case let .success(value): _result.bar = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["baz"] as AnyObject?) { + + case let .success(value): _result.baz = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "ReadOnlyFirst", actual: "\(source)")) + } + } + // Decoder for [Return] + Decoders.addDecoder(clazz: [Return].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[Return]> in + return Decoders.decode(clazz: [Return].self, source: source) + } + + // Decoder for Return + Decoders.addDecoder(clazz: Return.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? Return() : instance as! Return + switch Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["return"] as AnyObject?) { + + case let .success(value): _result._return = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "Return", actual: "\(source)")) + } + } + // Decoder for [SpecialModelName] + Decoders.addDecoder(clazz: [SpecialModelName].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[SpecialModelName]> in + return Decoders.decode(clazz: [SpecialModelName].self, source: source) + } + + // Decoder for SpecialModelName + Decoders.addDecoder(clazz: SpecialModelName.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? SpecialModelName() : instance as! SpecialModelName + switch Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["$special[property.name]"] as AnyObject?) { + + case let .success(value): _result.specialPropertyName = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "SpecialModelName", actual: "\(source)")) + } + } + // Decoder for [Tag] + Decoders.addDecoder(clazz: [Tag].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[Tag]> in + return Decoders.decode(clazz: [Tag].self, source: source) + } + + // Decoder for Tag + Decoders.addDecoder(clazz: Tag.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? Tag() : instance as! Tag + switch Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"] as AnyObject?) { + + case let .success(value): _result.id = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"] as AnyObject?) { + + case let .success(value): _result.name = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "Tag", actual: "\(source)")) + } + } + // Decoder for [User] + Decoders.addDecoder(clazz: [User].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[User]> in + return Decoders.decode(clazz: [User].self, source: source) + } + + // Decoder for User + Decoders.addDecoder(clazz: User.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? User() : instance as! User + switch Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"] as AnyObject?) { + + case let .success(value): _result.id = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["username"] as AnyObject?) { + + case let .success(value): _result.username = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["firstName"] as AnyObject?) { + + case let .success(value): _result.firstName = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["lastName"] as AnyObject?) { + + case let .success(value): _result.lastName = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["email"] as AnyObject?) { + + case let .success(value): _result.email = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["password"] as AnyObject?) { + + case let .success(value): _result.password = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["phone"] as AnyObject?) { + + case let .success(value): _result.phone = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["userStatus"] as AnyObject?) { + + case let .success(value): _result.userStatus = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "User", actual: "\(source)")) + } + } + // Decoder for [Cat] + Decoders.addDecoder(clazz: [Cat].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[Cat]> in + return Decoders.decode(clazz: [Cat].self, source: source) + } + + // Decoder for Cat + Decoders.addDecoder(clazz: Cat.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? Cat() : instance as! Cat + if decoders["\(Animal.self)"] != nil { + _ = Decoders.decode(clazz: Animal.self, source: source, instance: _result) + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["className"] as AnyObject?) { + + case let .success(value): _result.className = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["color"] as AnyObject?) { + + case let .success(value): _result.color = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["declawed"] as AnyObject?) { + + case let .success(value): _result.declawed = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "Cat", actual: "\(source)")) + } + } + // Decoder for [Dog] + Decoders.addDecoder(clazz: [Dog].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[Dog]> in + return Decoders.decode(clazz: [Dog].self, source: source) + } + + // Decoder for Dog + Decoders.addDecoder(clazz: Dog.self) { (source: AnyObject, instance: AnyObject?) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + let _result = instance == nil ? Dog() : instance as! Dog + if decoders["\(Animal.self)"] != nil { + _ = Decoders.decode(clazz: Animal.self, source: source, instance: _result) + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["className"] as AnyObject?) { + + case let .success(value): _result.className = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["color"] as AnyObject?) { + + case let .success(value): _result.color = value + case let .failure(error): break + + } + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["breed"] as AnyObject?) { + + case let .success(value): _result.breed = value + case let .failure(error): break + + } + return .success(_result) + } else { + return .failure(.typeMismatch(expected: "Dog", actual: "\(source)")) + } + } + }() + + static fileprivate func initialize() { + _ = Decoders.__once + } +} diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift new file mode 100644 index 00000000000..fe333aaafa7 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift @@ -0,0 +1,28 @@ +// +// AdditionalPropertiesClass.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class AdditionalPropertiesClass: JSONEncodable { + + public var mapProperty: [String:String]? + public var mapOfMapProperty: [String:[String:String]]? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["map_property"] = self.mapProperty?.encodeToJSON() + nillableDictionary["map_of_map_property"] = self.mapOfMapProperty?.encodeToJSON() + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Animal.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Animal.swift new file mode 100644 index 00000000000..f9fd0e865c0 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Animal.swift @@ -0,0 +1,28 @@ +// +// Animal.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Animal: JSONEncodable { + + public var className: String? + public var color: String? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["className"] = self.className + nillableDictionary["color"] = self.color + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/AnimalFarm.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/AnimalFarm.swift new file mode 100644 index 00000000000..68308364894 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/AnimalFarm.swift @@ -0,0 +1,11 @@ +// +// AnimalFarm.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift new file mode 100644 index 00000000000..70144a1d7c6 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift @@ -0,0 +1,35 @@ +// +// ApiResponse.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ApiResponse: JSONEncodable { + + public var code: Int32? + public var codeNum: NSNumber? { + get { + return code.map({ return NSNumber(value: $0) }) + } + } + public var type: String? + public var message: String? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["code"] = self.code?.encodeToJSON() + nillableDictionary["type"] = self.type + nillableDictionary["message"] = self.message + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift new file mode 100644 index 00000000000..d7870d7c01f --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift @@ -0,0 +1,26 @@ +// +// ArrayOfArrayOfNumberOnly.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ArrayOfArrayOfNumberOnly: JSONEncodable { + + public var arrayArrayNumber: [[Double]]? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["ArrayArrayNumber"] = self.arrayArrayNumber?.encodeToJSON() + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift new file mode 100644 index 00000000000..01d3b173384 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift @@ -0,0 +1,26 @@ +// +// ArrayOfNumberOnly.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ArrayOfNumberOnly: JSONEncodable { + + public var arrayNumber: [Double]? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["ArrayNumber"] = self.arrayNumber?.encodeToJSON() + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift new file mode 100644 index 00000000000..ef7b15bccd0 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift @@ -0,0 +1,30 @@ +// +// ArrayTest.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ArrayTest: JSONEncodable { + + public var arrayOfString: [String]? + public var arrayArrayOfInteger: [[Int64]]? + public var arrayArrayOfModel: [[ReadOnlyFirst]]? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["array_of_string"] = self.arrayOfString?.encodeToJSON() + nillableDictionary["array_array_of_integer"] = self.arrayArrayOfInteger?.encodeToJSON() + nillableDictionary["array_array_of_model"] = self.arrayArrayOfModel?.encodeToJSON() + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift new file mode 100644 index 00000000000..6b7796e65e2 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift @@ -0,0 +1,37 @@ +// +// Capitalization.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Capitalization: JSONEncodable { + + public var smallCamel: String? + public var capitalCamel: String? + public var smallSnake: String? + public var capitalSnake: String? + public var sCAETHFlowPoints: String? + /** Name of the pet */ + public var ATT_NAME: String? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["smallCamel"] = self.smallCamel + nillableDictionary["CapitalCamel"] = self.capitalCamel + nillableDictionary["small_Snake"] = self.smallSnake + nillableDictionary["Capital_Snake"] = self.capitalSnake + nillableDictionary["SCA_ETH_Flow_Points"] = self.sCAETHFlowPoints + nillableDictionary["ATT_NAME"] = self.ATT_NAME + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Cat.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Cat.swift new file mode 100644 index 00000000000..2b31a56b665 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Cat.swift @@ -0,0 +1,31 @@ +// +// Cat.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Cat: Animal { + + public var declawed: Bool? + public var declawedNum: NSNumber? { + get { + return declawed.map({ return NSNumber(value: $0) }) + } + } + + + + // MARK: JSONEncodable + override open func encodeToJSON() -> Any { + var nillableDictionary = super.encodeToJSON() as? [String:Any?] ?? [String:Any?]() + nillableDictionary["declawed"] = self.declawed + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Category.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Category.swift new file mode 100644 index 00000000000..36c98074d05 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Category.swift @@ -0,0 +1,33 @@ +// +// Category.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Category: JSONEncodable { + + public var id: Int64? + public var idNum: NSNumber? { + get { + return id.map({ return NSNumber(value: $0) }) + } + } + public var name: String? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["name"] = self.name + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift new file mode 100644 index 00000000000..0423f522ed1 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift @@ -0,0 +1,27 @@ +// +// ClassModel.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing model with \"_class\" property */ +open class ClassModel: JSONEncodable { + + public var _class: String? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["_class"] = self._class + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Client.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Client.swift new file mode 100644 index 00000000000..d7a70386702 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Client.swift @@ -0,0 +1,26 @@ +// +// Client.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Client: JSONEncodable { + + public var client: String? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["client"] = self.client + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Dog.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Dog.swift new file mode 100644 index 00000000000..36ea9b97b68 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Dog.swift @@ -0,0 +1,26 @@ +// +// Dog.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Dog: Animal { + + public var breed: String? + + + + // MARK: JSONEncodable + override open func encodeToJSON() -> Any { + var nillableDictionary = super.encodeToJSON() as? [String:Any?] ?? [String:Any?]() + nillableDictionary["breed"] = self.breed + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift new file mode 100644 index 00000000000..9bfe63ce1d7 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift @@ -0,0 +1,36 @@ +// +// EnumArrays.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class EnumArrays: JSONEncodable { + + public enum JustSymbol: String { + case greaterThanOrEqualTo = ">=" + case dollar = "$" + } + public enum ArrayEnum: String { + case fish = "fish" + case crab = "crab" + } + public var justSymbol: JustSymbol? + public var arrayEnum: [ArrayEnum]? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["just_symbol"] = self.justSymbol?.rawValue + nillableDictionary["array_enum"] = self.arrayEnum?.map({$0.rawValue}).encodeToJSON() + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/EnumClass.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/EnumClass.swift new file mode 100644 index 00000000000..c72feaabbd5 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/EnumClass.swift @@ -0,0 +1,17 @@ +// +// EnumClass.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public enum EnumClass: String { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + + func encodeToJSON() -> Any { return self.rawValue } +} diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift new file mode 100644 index 00000000000..2607822cb94 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -0,0 +1,45 @@ +// +// EnumTest.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class EnumTest: JSONEncodable { + + public enum EnumString: String { + case upper = "UPPER" + case lower = "lower" + case empty = "" + } + public enum EnumInteger: Int32 { + case _1 = 1 + case number1 = -1 + } + public enum EnumNumber: Double { + case _11 = 1.1 + case number12 = -1.2 + } + public var enumString: EnumString? + public var enumInteger: EnumInteger? + public var enumNumber: EnumNumber? + public var outerEnum: OuterEnum? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["enum_string"] = self.enumString?.rawValue + nillableDictionary["enum_integer"] = self.enumInteger?.rawValue + nillableDictionary["enum_number"] = self.enumNumber?.rawValue + nillableDictionary["outerEnum"] = self.outerEnum?.encodeToJSON() + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift new file mode 100644 index 00000000000..41e0c1998ee --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift @@ -0,0 +1,80 @@ +// +// FormatTest.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class FormatTest: JSONEncodable { + + public var integer: Int32? + public var integerNum: NSNumber? { + get { + return integer.map({ return NSNumber(value: $0) }) + } + } + public var int32: Int32? + public var int32Num: NSNumber? { + get { + return int32.map({ return NSNumber(value: $0) }) + } + } + public var int64: Int64? + public var int64Num: NSNumber? { + get { + return int64.map({ return NSNumber(value: $0) }) + } + } + public var number: Double? + public var numberNum: NSNumber? { + get { + return number.map({ return NSNumber(value: $0) }) + } + } + public var float: Float? + public var floatNum: NSNumber? { + get { + return float.map({ return NSNumber(value: $0) }) + } + } + public var double: Double? + public var doubleNum: NSNumber? { + get { + return double.map({ return NSNumber(value: $0) }) + } + } + public var string: String? + public var byte: Data? + public var binary: Data? + public var date: ISOFullDate? + public var dateTime: Date? + public var uuid: UUID? + public var password: String? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["integer"] = self.integer?.encodeToJSON() + nillableDictionary["int32"] = self.int32?.encodeToJSON() + nillableDictionary["int64"] = self.int64?.encodeToJSON() + nillableDictionary["number"] = self.number + nillableDictionary["float"] = self.float + nillableDictionary["double"] = self.double + nillableDictionary["string"] = self.string + nillableDictionary["byte"] = self.byte?.encodeToJSON() + nillableDictionary["binary"] = self.binary?.encodeToJSON() + nillableDictionary["date"] = self.date?.encodeToJSON() + nillableDictionary["dateTime"] = self.dateTime?.encodeToJSON() + nillableDictionary["uuid"] = self.uuid?.encodeToJSON() + nillableDictionary["password"] = self.password + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift new file mode 100644 index 00000000000..fc41604fc8f --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift @@ -0,0 +1,28 @@ +// +// HasOnlyReadOnly.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class HasOnlyReadOnly: JSONEncodable { + + public var bar: String? + public var foo: String? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["bar"] = self.bar + nillableDictionary["foo"] = self.foo + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/List.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/List.swift new file mode 100644 index 00000000000..bc30aa7469d --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/List.swift @@ -0,0 +1,26 @@ +// +// List.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class List: JSONEncodable { + + public var _123List: String? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["123-list"] = self._123List + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/MapTest.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/MapTest.swift new file mode 100644 index 00000000000..d2191dae660 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/MapTest.swift @@ -0,0 +1,31 @@ +// +// MapTest.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class MapTest: JSONEncodable { + + public enum MapOfEnumString: String { + case upper = "UPPER" + case lower = "lower" + } + public var mapMapOfString: [String:[String:String]]? + public var mapOfEnumString: [String:String]? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["map_map_of_string"] = self.mapMapOfString?.encodeToJSON()//TODO: handle enum map scenario + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift new file mode 100644 index 00000000000..c5a588c833f --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -0,0 +1,30 @@ +// +// MixedPropertiesAndAdditionalPropertiesClass.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class MixedPropertiesAndAdditionalPropertiesClass: JSONEncodable { + + public var uuid: UUID? + public var dateTime: Date? + public var map: [String:Animal]? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["uuid"] = self.uuid?.encodeToJSON() + nillableDictionary["dateTime"] = self.dateTime?.encodeToJSON() + nillableDictionary["map"] = self.map?.encodeToJSON() + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift new file mode 100644 index 00000000000..7b5bbeec298 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift @@ -0,0 +1,34 @@ +// +// Model200Response.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing model name starting with number */ +open class Model200Response: JSONEncodable { + + public var name: Int32? + public var nameNum: NSNumber? { + get { + return name.map({ return NSNumber(value: $0) }) + } + } + public var _class: String? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["name"] = self.name?.encodeToJSON() + nillableDictionary["class"] = self._class + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Name.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Name.swift new file mode 100644 index 00000000000..4194f829b02 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Name.swift @@ -0,0 +1,48 @@ +// +// Name.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing model name same as property name */ +open class Name: JSONEncodable { + + public var name: Int32? + public var nameNum: NSNumber? { + get { + return name.map({ return NSNumber(value: $0) }) + } + } + public var snakeCase: Int32? + public var snakeCaseNum: NSNumber? { + get { + return snakeCase.map({ return NSNumber(value: $0) }) + } + } + public var property: String? + public var _123Number: Int32? + public var _123NumberNum: NSNumber? { + get { + return _123Number.map({ return NSNumber(value: $0) }) + } + } + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["name"] = self.name?.encodeToJSON() + nillableDictionary["snake_case"] = self.snakeCase?.encodeToJSON() + nillableDictionary["property"] = self.property + nillableDictionary["123Number"] = self._123Number?.encodeToJSON() + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift new file mode 100644 index 00000000000..5cdb89991dc --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift @@ -0,0 +1,31 @@ +// +// NumberOnly.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class NumberOnly: JSONEncodable { + + public var justNumber: Double? + public var justNumberNum: NSNumber? { + get { + return justNumber.map({ return NSNumber(value: $0) }) + } + } + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["JustNumber"] = self.justNumber + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Order.swift new file mode 100644 index 00000000000..735fad0fac6 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -0,0 +1,62 @@ +// +// Order.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Order: JSONEncodable { + + public enum Status: String { + case placed = "placed" + case approved = "approved" + case delivered = "delivered" + } + public var id: Int64? + public var idNum: NSNumber? { + get { + return id.map({ return NSNumber(value: $0) }) + } + } + public var petId: Int64? + public var petIdNum: NSNumber? { + get { + return petId.map({ return NSNumber(value: $0) }) + } + } + public var quantity: Int32? + public var quantityNum: NSNumber? { + get { + return quantity.map({ return NSNumber(value: $0) }) + } + } + public var shipDate: Date? + /** Order Status */ + public var status: Status? + public var complete: Bool? + public var completeNum: NSNumber? { + get { + return complete.map({ return NSNumber(value: $0) }) + } + } + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + 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:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterBoolean.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterBoolean.swift new file mode 100644 index 00000000000..a24f9f6b14a --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterBoolean.swift @@ -0,0 +1,24 @@ +// +// OuterBoolean.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class OuterBoolean: JSONEncodable { + + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift new file mode 100644 index 00000000000..ddf86622451 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift @@ -0,0 +1,30 @@ +// +// OuterComposite.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class OuterComposite: JSONEncodable { + + public var myNumber: OuterNumber? + public var myString: OuterString? + public var myBoolean: OuterBoolean? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["my_number"] = self.myNumber?.encodeToJSON() + nillableDictionary["my_string"] = self.myString?.encodeToJSON() + nillableDictionary["my_boolean"] = self.myBoolean?.encodeToJSON() + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterEnum.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterEnum.swift new file mode 100644 index 00000000000..3f6e50251e6 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterEnum.swift @@ -0,0 +1,17 @@ +// +// OuterEnum.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public enum OuterEnum: String { + case placed = "placed" + case approved = "approved" + case delivered = "delivered" + + func encodeToJSON() -> Any { return self.rawValue } +} diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterNumber.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterNumber.swift new file mode 100644 index 00000000000..64d8da6440f --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterNumber.swift @@ -0,0 +1,24 @@ +// +// OuterNumber.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class OuterNumber: JSONEncodable { + + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterString.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterString.swift new file mode 100644 index 00000000000..a6ea38c804b --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/OuterString.swift @@ -0,0 +1,24 @@ +// +// OuterString.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class OuterString: JSONEncodable { + + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Pet.swift new file mode 100644 index 00000000000..be675c6a17d --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -0,0 +1,47 @@ +// +// Pet.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Pet: JSONEncodable { + + public enum Status: String { + case available = "available" + case pending = "pending" + case sold = "sold" + } + public var id: Int64? + public var idNum: NSNumber? { + get { + return id.map({ return NSNumber(value: $0) }) + } + } + 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 + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + 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:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift new file mode 100644 index 00000000000..ca4945617a5 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift @@ -0,0 +1,28 @@ +// +// ReadOnlyFirst.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ReadOnlyFirst: JSONEncodable { + + public var bar: String? + public var baz: String? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["bar"] = self.bar + nillableDictionary["baz"] = self.baz + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Return.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Return.swift new file mode 100644 index 00000000000..250769f71c9 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Return.swift @@ -0,0 +1,32 @@ +// +// Return.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing reserved words */ +open class Return: JSONEncodable { + + public var _return: Int32? + public var _returnNum: NSNumber? { + get { + return _return.map({ return NSNumber(value: $0) }) + } + } + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["return"] = self._return?.encodeToJSON() + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift new file mode 100644 index 00000000000..ad8f30341ae --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift @@ -0,0 +1,31 @@ +// +// SpecialModelName.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class SpecialModelName: JSONEncodable { + + public var specialPropertyName: Int64? + public var specialPropertyNameNum: NSNumber? { + get { + return specialPropertyName.map({ return NSNumber(value: $0) }) + } + } + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["$special[property.name]"] = self.specialPropertyName?.encodeToJSON() + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Tag.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Tag.swift new file mode 100644 index 00000000000..d734712fc44 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/Tag.swift @@ -0,0 +1,33 @@ +// +// Tag.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Tag: JSONEncodable { + + public var id: Int64? + public var idNum: NSNumber? { + get { + return id.map({ return NSNumber(value: $0) }) + } + } + public var name: String? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["name"] = self.name + + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/User.swift b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/User.swift new file mode 100644 index 00000000000..68cda8599b3 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/PetstoreClient/Classes/Swaggers/Models/User.swift @@ -0,0 +1,51 @@ +// +// User.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class User: JSONEncodable { + + public var id: Int64? + public var idNum: NSNumber? { + get { + return id.map({ return NSNumber(value: $0) }) + } + } + 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 var userStatusNum: NSNumber? { + get { + return userStatus.map({ return NSNumber(value: $0) }) + } + } + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + 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:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} + diff --git a/samples/client/petstore/swift3/objcCompatible/git_push.sh b/samples/client/petstore/swift3/objcCompatible/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore/swift3/objcCompatible/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git 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/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift index be616c7b71d..fe0b1fffd25 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift @@ -32,10 +32,10 @@ open class APIBase { open class RequestBuilder { var credential: URLCredential? var headers: [String:String] - let parameters: Any? - let isBody: Bool - let method: String - let URLString: String + public let parameters: Any? + public let isBody: Bool + public let method: String + public let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((Progress) -> ())? diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift index 82e9b8fac64..1954ace81d5 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift @@ -1,5 +1,5 @@ // -// AnotherFakeAPI.swift +// AnotherfakeAPI.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen @@ -10,7 +10,7 @@ import Alamofire import PromiseKit -open class AnotherFakeAPI: APIBase { +open class AnotherfakeAPI: APIBase { /** To test special tags - parameter body: (body) client model diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift index 7f6f14e4067..3b7ba8e4837 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift @@ -54,7 +54,7 @@ open class Fake_classname_tags123API: APIBase { open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake_classname_test" let URLString = PetstoreClientAPI.basePath + path - let parameters = body.encodeToJSON() as? [String:AnyObject] + let parameters = body.encodeToJSON() let url = NSURLComponents(string: URLString) diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 09da8f6f1fe..27aa7ad8684 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -104,7 +104,9 @@ open class PetAPI: APIBase { */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -494,7 +496,9 @@ open class PetAPI: APIBase { */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -601,7 +605,9 @@ open class PetAPI: APIBase { */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let formParams: [String:Any?] = [ "name": name, @@ -669,7 +675,9 @@ open class PetAPI: APIBase { */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { var path = "/pet/{petId}/uploadImage" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let formParams: [String:Any?] = [ "additionalMetadata": additionalMetadata, diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 599711ea67d..4b47025d3f3 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -49,7 +49,9 @@ open class StoreAPI: APIBase { */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { var path = "/store/order/{order_id}" - path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let orderIdPreEscape = "\(orderId)" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -178,7 +180,9 @@ open class StoreAPI: APIBase { */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { var path = "/store/order/{order_id}" - path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let orderIdPreEscape = "\(orderId)" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 6ec966a9567..577a8bef6d5 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -193,7 +193,9 @@ open class UserAPI: APIBase { */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -280,7 +282,9 @@ open class UserAPI: APIBase { */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -436,7 +440,9 @@ open class UserAPI: APIBase { */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() diff --git a/samples/client/petstore/swift3/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift3/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift index f172e732513..ec8631589c2 100644 --- a/samples/client/petstore/swift3/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift +++ b/samples/client/petstore/swift3/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift @@ -102,4 +102,14 @@ class UserAPITests: XCTestCase { self.waitForExpectations(timeout: testTimeout, handler: nil) } + func testPathParamsAreEscaped() { + // The path for this operation is /user/{userId}. In order to make a usable path, + // then we must make sure that {userId} is percent-escaped when it is substituted + // into the path. So we intentionally introduce a path with spaces. + let userRequestBuilder = UserAPI.getUserByNameWithRequestBuilder(username: "User Name With Spaces") + let urlContainsSpace = userRequestBuilder.URLString.contains(" ") + + XCTAssert(!urlContainsSpace, "Expected URL to be escaped, but it was not.") + } + } diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift index be616c7b71d..fe0b1fffd25 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift @@ -32,10 +32,10 @@ open class APIBase { open class RequestBuilder { var credential: URLCredential? var headers: [String:String] - let parameters: Any? - let isBody: Bool - let method: String - let URLString: String + public let parameters: Any? + public let isBody: Bool + public let method: String + public let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((Progress) -> ())? diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift index b37257eb955..9406527ad41 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift @@ -1,5 +1,5 @@ // -// AnotherFakeAPI.swift +// AnotherfakeAPI.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen @@ -10,7 +10,7 @@ import Alamofire import RxSwift -open class AnotherFakeAPI: APIBase { +open class AnotherfakeAPI: APIBase { /** To test special tags - parameter body: (body) client model diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift index ef1a4d58f48..9ea10ff4439 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift @@ -56,7 +56,7 @@ open class Fake_classname_tags123API: APIBase { open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake_classname_test" let URLString = PetstoreClientAPI.basePath + path - let parameters = body.encodeToJSON() as? [String:AnyObject] + let parameters = body.encodeToJSON() let url = NSURLComponents(string: URLString) diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index ecd41c83355..3733e2cb16f 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -108,7 +108,9 @@ open class PetAPI: APIBase { */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -504,7 +506,9 @@ open class PetAPI: APIBase { */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -615,7 +619,9 @@ open class PetAPI: APIBase { */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let formParams: [String:Any?] = [ "name": name, @@ -685,7 +691,9 @@ open class PetAPI: APIBase { */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { var path = "/pet/{petId}/uploadImage" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let formParams: [String:Any?] = [ "additionalMetadata": additionalMetadata, diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 3a6112402d8..29ed72ba960 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -51,7 +51,9 @@ open class StoreAPI: APIBase { */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { var path = "/store/order/{order_id}" - path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let orderIdPreEscape = "\(orderId)" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -184,7 +186,9 @@ open class StoreAPI: APIBase { */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { var path = "/store/order/{order_id}" - path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let orderIdPreEscape = "\(orderId)" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 99a91b910f4..65789ede6ef 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -201,7 +201,9 @@ open class UserAPI: APIBase { */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -290,7 +292,9 @@ open class UserAPI: APIBase { */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -452,7 +456,9 @@ open class UserAPI: APIBase { */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() diff --git a/samples/client/petstore/swift3/rxswift/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift3/rxswift/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift index 4159baa1754..dca3e169ebf 100644 --- a/samples/client/petstore/swift3/rxswift/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift +++ b/samples/client/petstore/swift3/rxswift/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift @@ -160,4 +160,14 @@ class UserAPITests: XCTestCase { self.waitForExpectations(timeout: testTimeout, handler: nil) } + func testPathParamsAreEscaped() { + // The path for this operation is /user/{userId}. In order to make a usable path, + // then we must make sure that {userId} is percent-escaped when it is substituted + // into the path. So we intentionally introduce a path with spaces. + let userRequestBuilder = UserAPI.getUserByNameWithRequestBuilder(username: "User Name With Spaces") + let urlContainsSpace = userRequestBuilder.URLString.contains(" ") + + XCTAssert(!urlContainsSpace, "Expected URL to be escaped, but it was not.") + } + } diff --git a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs.swift index be616c7b71d..fe0b1fffd25 100644 --- a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs.swift @@ -32,10 +32,10 @@ open class APIBase { open class RequestBuilder { var credential: URLCredential? var headers: [String:String] - let parameters: Any? - let isBody: Bool - let method: String - let URLString: String + public let parameters: Any? + public let isBody: Bool + public let method: String + public let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((Progress) -> ())? diff --git a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift index 2e100b1fdcd..5b97c3c8057 100644 --- a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/AnotherFakeAPI.swift @@ -1,5 +1,5 @@ // -// AnotherFakeAPI.swift +// AnotherfakeAPI.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen @@ -9,7 +9,7 @@ import Foundation import Alamofire -open class AnotherFakeAPI: APIBase { +open class AnotherfakeAPI: APIBase { /** To test special tags - parameter body: (body) client model diff --git a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift index 4a9748a5ad1..bc4369df7ae 100644 --- a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift +++ b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift @@ -37,7 +37,7 @@ open class Fake_classname_tags123API: APIBase { open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake_classname_test" let URLString = PetstoreClientAPI.basePath + path - let parameters = body.encodeToJSON() as? [String:AnyObject] + let parameters = body.encodeToJSON() let url = NSURLComponents(string: URLString) diff --git a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 7eaa9ab093f..6de1f336620 100644 --- a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -70,7 +70,9 @@ open class PetAPI: APIBase { */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -412,7 +414,9 @@ open class PetAPI: APIBase { */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -485,7 +489,9 @@ open class PetAPI: APIBase { */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let formParams: [String:Any?] = [ "name": name, @@ -535,7 +541,9 @@ open class PetAPI: APIBase { */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { var path = "/pet/{petId}/uploadImage" - path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let petIdPreEscape = "\(petId)" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let formParams: [String:Any?] = [ "additionalMetadata": additionalMetadata, diff --git a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 006be5ab186..7d99f10de0c 100644 --- a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -32,7 +32,9 @@ open class StoreAPI: APIBase { */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { var path = "/store/order/{order_id}" - path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let orderIdPreEscape = "\(orderId)" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -130,7 +132,9 @@ open class StoreAPI: APIBase { */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { var path = "/store/order/{order_id}" - path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let orderIdPreEscape = "\(orderId)" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil diff --git a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index d4020a0a9c8..b5bd0d0677a 100644 --- a/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/unwraprequired/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -128,7 +128,9 @@ open class UserAPI: APIBase { */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -199,7 +201,9 @@ open class UserAPI: APIBase { */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String:Any]? = nil @@ -306,7 +310,9 @@ open class UserAPI: APIBase { */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { var path = "/user/{username}" - path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let usernamePreEscape = "\(username)" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift index 9c135bdce3a..1d439bf0089 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/AnotherfakeAPI.swift @@ -1,5 +1,5 @@ // -// AnotherfakeAPI.swift +// AnotherFakeAPI.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen @@ -10,7 +10,7 @@ import Alamofire -open class AnotherfakeAPI { +open class AnotherFakeAPI { /** To test special tags diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index a111760bee0..660dd6b02f5 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -404,6 +404,41 @@ open class FakeAPI { return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) } + /** + test inline additionalProperties + + - parameter param: (body) request body + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testInlineAdditionalProperties(param: Any, completion: @escaping ((_ error: Error?) -> Void)) { + testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (response, error) -> Void in + completion(error); + } + } + + + /** + test inline additionalProperties + - POST /fake/inline-additionalProperties + - + + - parameter param: (body) request body + + - returns: RequestBuilder + */ + open class func testInlineAdditionalPropertiesWithRequestBuilder(param: Any) -> RequestBuilder { + let path = "/fake/inline-additionalProperties" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + /** test json serialization of form data diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/CodableHelper.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/CodableHelper.swift index d56cb0e7348..befa0594f6a 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/CodableHelper.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/CodableHelper.swift @@ -11,14 +11,20 @@ public typealias EncodeResult = (data: Data?, error: Error?) open class CodableHelper { + open static var dateformatter: DateFormatter? + open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T : Decodable { var returnedDecodable: T? = nil var returnedError: Error? = nil let decoder = JSONDecoder() - decoder.dataDecodingStrategy = .base64 - if #available(iOS 10.0, *) { - decoder.dateDecodingStrategy = .iso8601 + if let df = self.dateformatter { + decoder.dateDecodingStrategy = .formatted(df) + } else { + decoder.dataDecodingStrategy = .base64 + if #available(iOS 10.0, *) { + decoder.dateDecodingStrategy = .iso8601 + } } do { diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift index bb7960a7577..7836b9cbfab 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift @@ -43,7 +43,7 @@ open class EnumArrays: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: String.self) - justSymbol = try container.decodeIfPresent(String.self, forKey: "just_symbol") + justSymbol = try container.decodeIfPresent(JustSymbol.self, forKey: "just_symbol") arrayEnum = try container.decodeArrayIfPresent(String.self, forKey: "array_enum") } } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift index 023f9a8209c..d21e2becc66 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -54,9 +54,9 @@ open class EnumTest: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: String.self) - enumString = try container.decodeIfPresent(String.self, forKey: "enum_string") - enumInteger = try container.decodeIfPresent(Int.self, forKey: "enum_integer") - enumNumber = try container.decodeIfPresent(Double.self, forKey: "enum_number") + enumString = try container.decodeIfPresent(EnumString.self, forKey: "enum_string") + enumInteger = try container.decodeIfPresent(EnumInteger.self, forKey: "enum_integer") + enumNumber = try container.decodeIfPresent(EnumNumber.self, forKey: "enum_number") outerEnum = try container.decodeIfPresent(OuterEnum.self, forKey: "outerEnum") } } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Order.swift index fee9d6c9192..58c3ad96e86 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Order.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -57,7 +57,7 @@ open class Order: Codable { petId = try container.decodeIfPresent(Int64.self, forKey: "petId") quantity = try container.decodeIfPresent(Int.self, forKey: "quantity") shipDate = try container.decodeIfPresent(Date.self, forKey: "shipDate") - status = try container.decodeIfPresent(String.self, forKey: "status") + status = try container.decodeIfPresent(Status.self, forKey: "status") complete = try container.decodeIfPresent(Bool.self, forKey: "complete") } } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift index 0622c110fd4..fd15806dfbf 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -58,7 +58,7 @@ open class Pet: Codable { name = try container.decode(String.self, forKey: "name") photoUrls = try container.decodeArray(String.self, forKey: "photoUrls") tags = try container.decodeArrayIfPresent(Tag.self, forKey: "tags") - status = try container.decodeIfPresent(String.self, forKey: "status") + status = try container.decodeIfPresent(Status.self, forKey: "status") } } diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/CodableHelper.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/CodableHelper.swift index d56cb0e7348..befa0594f6a 100644 --- a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/CodableHelper.swift +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/CodableHelper.swift @@ -11,14 +11,20 @@ public typealias EncodeResult = (data: Data?, error: Error?) open class CodableHelper { + open static var dateformatter: DateFormatter? + open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T : Decodable { var returnedDecodable: T? = nil var returnedError: Error? = nil let decoder = JSONDecoder() - decoder.dataDecodingStrategy = .base64 - if #available(iOS 10.0, *) { - decoder.dateDecodingStrategy = .iso8601 + if let df = self.dateformatter { + decoder.dateDecodingStrategy = .formatted(df) + } else { + decoder.dataDecodingStrategy = .base64 + if #available(iOS 10.0, *) { + decoder.dateDecodingStrategy = .iso8601 + } } do { diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/CodableHelper.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/CodableHelper.swift index d56cb0e7348..befa0594f6a 100644 --- a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/CodableHelper.swift +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/CodableHelper.swift @@ -11,14 +11,20 @@ public typealias EncodeResult = (data: Data?, error: Error?) open class CodableHelper { + open static var dateformatter: DateFormatter? + open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T : Decodable { var returnedDecodable: T? = nil var returnedError: Error? = nil let decoder = JSONDecoder() - decoder.dataDecodingStrategy = .base64 - if #available(iOS 10.0, *) { - decoder.dateDecodingStrategy = .iso8601 + if let df = self.dateformatter { + decoder.dateDecodingStrategy = .formatted(df) + } else { + decoder.dataDecodingStrategy = .base64 + if #available(iOS 10.0, *) { + decoder.dateDecodingStrategy = .iso8601 + } } do { diff --git a/samples/client/petstore/typescript-angular-v2/default/api.module.ts b/samples/client/petstore/typescript-angular-v2/default/api.module.ts index dcce0dbd628..4b290cd5a49 100644 --- a/samples/client/petstore/typescript-angular-v2/default/api.module.ts +++ b/samples/client/petstore/typescript-angular-v2/default/api.module.ts @@ -1,4 +1,4 @@ -import { NgModule, ModuleWithProviders } from '@angular/core'; +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HttpModule } from '@angular/http'; import { Configuration } from './configuration'; @@ -11,13 +11,22 @@ import { UserService } from './api/user.service'; imports: [ CommonModule, HttpModule ], declarations: [], exports: [], - providers: [ PetService, StoreService, UserService ] + providers: [ + PetService, + StoreService, + UserService ] }) export class ApiModule { - public static forConfig(configurationFactory: () => Configuration): ModuleWithProviders { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { return { ngModule: ApiModule, - providers: [ {provide: Configuration, useFactory: configurationFactory}] + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + } + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import your base AppModule only.'); } } } diff --git a/samples/client/petstore/typescript-angular-v2/default/api/pet.service.ts b/samples/client/petstore/typescript-angular-v2/default/api/pet.service.ts index 11a1b603831..4435de468a2 100644 --- a/samples/client/petstore/typescript-angular-v2/default/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v2/default/api/pet.service.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - /* tslint:disable:no-unused-variable member-ordering */ import { Inject, Injectable, Optional } from '@angular/core'; @@ -59,7 +58,6 @@ export class PetService { return false; } - /** * * @summary Add a new pet to the store @@ -214,7 +212,25 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -254,6 +270,20 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, @@ -292,6 +322,20 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -331,6 +375,20 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -362,6 +420,20 @@ export class PetService { headers.set('api_key', this.configuration.apiKeys["api_key"]); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -395,7 +467,25 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, @@ -433,10 +523,21 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + // to determine the Content-Type header let consumes: string[] = [ 'application/x-www-form-urlencoded' ]; + const canConsumeForm = this.canConsumeForm(consumes); let formParams: { append(param: string, value: any): void; }; @@ -452,8 +553,6 @@ export class PetService { headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } - - if (name !== undefined) { formParams.append('name', name); } @@ -497,10 +596,20 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + // to determine the Content-Type header let consumes: string[] = [ 'multipart/form-data' ]; + const canConsumeForm = this.canConsumeForm(consumes); let formParams: { append(param: string, value: any): void; }; @@ -519,8 +628,6 @@ export class PetService { headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } - - if (additionalMetadata !== undefined) { formParams.append('additionalMetadata', additionalMetadata); } diff --git a/samples/client/petstore/typescript-angular-v2/default/api/store.service.ts b/samples/client/petstore/typescript-angular-v2/default/api/store.service.ts index 393d291ba3d..3eb043313ff 100644 --- a/samples/client/petstore/typescript-angular-v2/default/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v2/default/api/store.service.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - /* tslint:disable:no-unused-variable member-ordering */ import { Inject, Injectable, Optional } from '@angular/core'; @@ -58,7 +57,6 @@ export class StoreService { return false; } - /** * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @summary Delete purchase order by ID @@ -135,6 +133,20 @@ export class StoreService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, @@ -161,6 +173,19 @@ export class StoreService { headers.set('api_key', this.configuration.apiKeys["api_key"]); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -186,6 +211,20 @@ export class StoreService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -211,7 +250,23 @@ export class StoreService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, diff --git a/samples/client/petstore/typescript-angular-v2/default/api/user.service.ts b/samples/client/petstore/typescript-angular-v2/default/api/user.service.ts index f495f1f9d39..7fd15126b81 100644 --- a/samples/client/petstore/typescript-angular-v2/default/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v2/default/api/user.service.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - /* tslint:disable:no-unused-variable member-ordering */ import { Inject, Injectable, Optional } from '@angular/core'; @@ -58,7 +57,6 @@ export class UserService { return false; } - /** * This can only be done by the logged in user. * @summary Create user @@ -201,7 +199,23 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -229,7 +243,23 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -257,7 +287,23 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -285,6 +331,20 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, @@ -310,6 +370,20 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -347,6 +421,20 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -369,6 +457,20 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -398,7 +500,23 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, diff --git a/samples/client/petstore/typescript-angular-v2/default/configuration.ts b/samples/client/petstore/typescript-angular-v2/default/configuration.ts index 005c3a26df3..d486fc9f97d 100644 --- a/samples/client/petstore/typescript-angular-v2/default/configuration.ts +++ b/samples/client/petstore/typescript-angular-v2/default/configuration.ts @@ -23,4 +23,57 @@ export class Configuration { this.basePath = configurationParameters.basePath; this.withCredentials = configurationParameters.withCredentials; } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param {string[]} contentTypes - the array of content types that are available for selection + * @returns {string} the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string { + if (contentTypes.length == 0) { + return undefined; + } + + let type = contentTypes.find(x => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param {string[]} accepts - the array of content types that are available for selection. + * @returns {string} the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string { + if (accepts.length == 0) { + return undefined; + } + + let type = accepts.find(x => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param {string} mime - MIME (Multipurpose Internet Mail Extensions) + * @return {boolean} True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime != null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } } diff --git a/samples/client/petstore/typescript-angular-v2/default/model/ApiResponse.ts b/samples/client/petstore/typescript-angular-v2/default/model/ApiResponse.ts index 3af781cf580..eac4208f022 100644 --- a/samples/client/petstore/typescript-angular-v2/default/model/ApiResponse.ts +++ b/samples/client/petstore/typescript-angular-v2/default/model/ApiResponse.ts @@ -11,15 +11,11 @@ */ - /** * Describes the result of uploading an image resource */ export interface ApiResponse { code?: number; - type?: string; - message?: string; - } diff --git a/samples/client/petstore/typescript-angular-v2/default/model/category.ts b/samples/client/petstore/typescript-angular-v2/default/model/category.ts index d09f8d7b265..5040d1db915 100644 --- a/samples/client/petstore/typescript-angular-v2/default/model/category.ts +++ b/samples/client/petstore/typescript-angular-v2/default/model/category.ts @@ -11,13 +11,10 @@ */ - /** * A category for a pet */ export interface Category { id?: number; - name?: string; - } diff --git a/samples/client/petstore/typescript-angular-v2/default/model/order.ts b/samples/client/petstore/typescript-angular-v2/default/model/order.ts index 4639b8c2949..33b60bb6e16 100644 --- a/samples/client/petstore/typescript-angular-v2/default/model/order.ts +++ b/samples/client/petstore/typescript-angular-v2/default/model/order.ts @@ -11,27 +11,25 @@ */ - /** * An order for a pets from the pet store */ export interface Order { id?: number; - petId?: number; - quantity?: number; - shipDate?: Date; - /** * Order Status */ status?: Order.StatusEnum; - complete?: boolean; - } export namespace Order { export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum + } } diff --git a/samples/client/petstore/typescript-angular-v2/default/model/pet.ts b/samples/client/petstore/typescript-angular-v2/default/model/pet.ts index ce6c535b867..342ab5f8e75 100644 --- a/samples/client/petstore/typescript-angular-v2/default/model/pet.ts +++ b/samples/client/petstore/typescript-angular-v2/default/model/pet.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - import { Category } from './category'; import { Tag } from './tag'; @@ -19,21 +18,20 @@ import { Tag } from './tag'; */ export interface Pet { id?: number; - category?: Category; - name: string; - photoUrls: Array; - tags?: Array; - /** * pet status in the store */ status?: Pet.StatusEnum; - } export namespace Pet { export type StatusEnum = 'available' | 'pending' | 'sold'; + export const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum + } } diff --git a/samples/client/petstore/typescript-angular-v2/default/model/tag.ts b/samples/client/petstore/typescript-angular-v2/default/model/tag.ts index 3ed1eeff8f3..c7524000357 100644 --- a/samples/client/petstore/typescript-angular-v2/default/model/tag.ts +++ b/samples/client/petstore/typescript-angular-v2/default/model/tag.ts @@ -11,13 +11,10 @@ */ - /** * A tag for a pet */ export interface Tag { id?: number; - name?: string; - } diff --git a/samples/client/petstore/typescript-angular-v2/default/model/user.ts b/samples/client/petstore/typescript-angular-v2/default/model/user.ts index f4914ae2608..a0261a6f37d 100644 --- a/samples/client/petstore/typescript-angular-v2/default/model/user.ts +++ b/samples/client/petstore/typescript-angular-v2/default/model/user.ts @@ -11,28 +11,19 @@ */ - /** * A User who is purchasing from the pet store */ export interface User { id?: number; - username?: string; - firstName?: string; - lastName?: string; - email?: string; - password?: string; - phone?: string; - /** * User Status */ userStatus?: number; - } diff --git a/samples/client/petstore/typescript-angular-v2/npm/README.md b/samples/client/petstore/typescript-angular-v2/npm/README.md index 038fd51491c..afa7807e82a 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/README.md +++ b/samples/client/petstore/typescript-angular-v2/npm/README.md @@ -40,36 +40,77 @@ In your project: npm link @swagger/angular2-typescript-petstore@0.0.1 ``` -In your angular2 project: +In your Angular project: + ``` -import { DefaultApi } from '@swagger/angular2-typescript-petstore/api/api'; +// without configuring providers +import { ApiModule } from '@swagger/angular2-typescript-petstore'; + @NgModule({ - imports: [], - declarations: [], - exports: [], - providers: [AppModule] + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] }) -export class CoreModule {} +export class AppModule {} ``` + ``` -import { DefaultApi } from '@swagger/angular2-typescript-petstore/api/api'; +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from '@swagger/angular2-typescript-petstore'; + +export function apiConfigFactory (): Configuration => { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from '@swagger/angular2-typescript-petstore'; export class AppComponent { constructor(private apiGateway: DefaultApi) { } } ``` +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + ### Set service base path If different than the generated base path, during app bootstrap, you can provide the base path to your service. ``` -import { BASE_PATH } from './path-to-swagger-gen-service/index'; +import { BASE_PATH } from '@swagger/angular2-typescript-petstore'; bootstrap(AppComponent, [ { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, ]); ``` +or + +``` +import { BASE_PATH } from '@swagger/angular2-typescript-petstore'; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + #### Using @angular/cli First extend your `src/environments/*.ts` files by adding the corresponding base path: @@ -88,11 +129,11 @@ import { environment } from '../environments/environment'; @NgModule({ declarations: [ - AppComponent, + AppComponent ], imports: [ ], - providers: [{ provide: BASE_PATH, useValue: useValue: environment.API_BASE_PATH }], - bootstrap: [AppComponent] + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] }) export class AppModule { } ``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v2/npm/api.module.ts b/samples/client/petstore/typescript-angular-v2/npm/api.module.ts index dcce0dbd628..4b290cd5a49 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/api.module.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/api.module.ts @@ -1,4 +1,4 @@ -import { NgModule, ModuleWithProviders } from '@angular/core'; +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HttpModule } from '@angular/http'; import { Configuration } from './configuration'; @@ -11,13 +11,22 @@ import { UserService } from './api/user.service'; imports: [ CommonModule, HttpModule ], declarations: [], exports: [], - providers: [ PetService, StoreService, UserService ] + providers: [ + PetService, + StoreService, + UserService ] }) export class ApiModule { - public static forConfig(configurationFactory: () => Configuration): ModuleWithProviders { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { return { ngModule: ApiModule, - providers: [ {provide: Configuration, useFactory: configurationFactory}] + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + } + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import your base AppModule only.'); } } } diff --git a/samples/client/petstore/typescript-angular-v2/npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v2/npm/api/pet.service.ts index 11a1b603831..4435de468a2 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/api/pet.service.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - /* tslint:disable:no-unused-variable member-ordering */ import { Inject, Injectable, Optional } from '@angular/core'; @@ -59,7 +58,6 @@ export class PetService { return false; } - /** * * @summary Add a new pet to the store @@ -214,7 +212,25 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -254,6 +270,20 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, @@ -292,6 +322,20 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -331,6 +375,20 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -362,6 +420,20 @@ export class PetService { headers.set('api_key', this.configuration.apiKeys["api_key"]); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -395,7 +467,25 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, @@ -433,10 +523,21 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + // to determine the Content-Type header let consumes: string[] = [ 'application/x-www-form-urlencoded' ]; + const canConsumeForm = this.canConsumeForm(consumes); let formParams: { append(param: string, value: any): void; }; @@ -452,8 +553,6 @@ export class PetService { headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } - - if (name !== undefined) { formParams.append('name', name); } @@ -497,10 +596,20 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + // to determine the Content-Type header let consumes: string[] = [ 'multipart/form-data' ]; + const canConsumeForm = this.canConsumeForm(consumes); let formParams: { append(param: string, value: any): void; }; @@ -519,8 +628,6 @@ export class PetService { headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } - - if (additionalMetadata !== undefined) { formParams.append('additionalMetadata', additionalMetadata); } diff --git a/samples/client/petstore/typescript-angular-v2/npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v2/npm/api/store.service.ts index 393d291ba3d..3eb043313ff 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/api/store.service.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - /* tslint:disable:no-unused-variable member-ordering */ import { Inject, Injectable, Optional } from '@angular/core'; @@ -58,7 +57,6 @@ export class StoreService { return false; } - /** * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @summary Delete purchase order by ID @@ -135,6 +133,20 @@ export class StoreService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, @@ -161,6 +173,19 @@ export class StoreService { headers.set('api_key', this.configuration.apiKeys["api_key"]); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -186,6 +211,20 @@ export class StoreService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -211,7 +250,23 @@ export class StoreService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, diff --git a/samples/client/petstore/typescript-angular-v2/npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v2/npm/api/user.service.ts index f495f1f9d39..7fd15126b81 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/api/user.service.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - /* tslint:disable:no-unused-variable member-ordering */ import { Inject, Injectable, Optional } from '@angular/core'; @@ -58,7 +57,6 @@ export class UserService { return false; } - /** * This can only be done by the logged in user. * @summary Create user @@ -201,7 +199,23 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -229,7 +243,23 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -257,7 +287,23 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -285,6 +331,20 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, @@ -310,6 +370,20 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -347,6 +421,20 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -369,6 +457,20 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -398,7 +500,23 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, diff --git a/samples/client/petstore/typescript-angular-v2/npm/configuration.ts b/samples/client/petstore/typescript-angular-v2/npm/configuration.ts index 005c3a26df3..d486fc9f97d 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/configuration.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/configuration.ts @@ -23,4 +23,57 @@ export class Configuration { this.basePath = configurationParameters.basePath; this.withCredentials = configurationParameters.withCredentials; } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param {string[]} contentTypes - the array of content types that are available for selection + * @returns {string} the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string { + if (contentTypes.length == 0) { + return undefined; + } + + let type = contentTypes.find(x => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param {string[]} accepts - the array of content types that are available for selection. + * @returns {string} the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string { + if (accepts.length == 0) { + return undefined; + } + + let type = accepts.find(x => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param {string} mime - MIME (Multipurpose Internet Mail Extensions) + * @return {boolean} True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime != null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } } diff --git a/samples/client/petstore/typescript-angular-v2/npm/model/ApiResponse.ts b/samples/client/petstore/typescript-angular-v2/npm/model/ApiResponse.ts index 3af781cf580..eac4208f022 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/model/ApiResponse.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/model/ApiResponse.ts @@ -11,15 +11,11 @@ */ - /** * Describes the result of uploading an image resource */ export interface ApiResponse { code?: number; - type?: string; - message?: string; - } diff --git a/samples/client/petstore/typescript-angular-v2/npm/model/category.ts b/samples/client/petstore/typescript-angular-v2/npm/model/category.ts index d09f8d7b265..5040d1db915 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/model/category.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/model/category.ts @@ -11,13 +11,10 @@ */ - /** * A category for a pet */ export interface Category { id?: number; - name?: string; - } diff --git a/samples/client/petstore/typescript-angular-v2/npm/model/order.ts b/samples/client/petstore/typescript-angular-v2/npm/model/order.ts index 4639b8c2949..33b60bb6e16 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/model/order.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/model/order.ts @@ -11,27 +11,25 @@ */ - /** * An order for a pets from the pet store */ export interface Order { id?: number; - petId?: number; - quantity?: number; - shipDate?: Date; - /** * Order Status */ status?: Order.StatusEnum; - complete?: boolean; - } export namespace Order { export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum + } } diff --git a/samples/client/petstore/typescript-angular-v2/npm/model/pet.ts b/samples/client/petstore/typescript-angular-v2/npm/model/pet.ts index ce6c535b867..342ab5f8e75 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/model/pet.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/model/pet.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - import { Category } from './category'; import { Tag } from './tag'; @@ -19,21 +18,20 @@ import { Tag } from './tag'; */ export interface Pet { id?: number; - category?: Category; - name: string; - photoUrls: Array; - tags?: Array; - /** * pet status in the store */ status?: Pet.StatusEnum; - } export namespace Pet { export type StatusEnum = 'available' | 'pending' | 'sold'; + export const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum + } } diff --git a/samples/client/petstore/typescript-angular-v2/npm/model/tag.ts b/samples/client/petstore/typescript-angular-v2/npm/model/tag.ts index 3ed1eeff8f3..c7524000357 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/model/tag.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/model/tag.ts @@ -11,13 +11,10 @@ */ - /** * A tag for a pet */ export interface Tag { id?: number; - name?: string; - } diff --git a/samples/client/petstore/typescript-angular-v2/npm/model/user.ts b/samples/client/petstore/typescript-angular-v2/npm/model/user.ts index f4914ae2608..a0261a6f37d 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/model/user.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/model/user.ts @@ -11,28 +11,19 @@ */ - /** * A User who is purchasing from the pet store */ export interface User { id?: number; - username?: string; - firstName?: string; - lastName?: string; - email?: string; - password?: string; - phone?: string; - /** * User Status */ userStatus?: number; - } diff --git a/samples/client/petstore/typescript-angular-v2/npm/package.json b/samples/client/petstore/typescript-angular-v2/npm/package.json index d6aee04c589..0e363919a9b 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/package.json +++ b/samples/client/petstore/typescript-angular-v2/npm/package.json @@ -35,6 +35,6 @@ "typescript": "^2.1.5" }, "publishConfig": { - "registry":"https://skimdb.npmjs.com/registry" + "registry": "https://skimdb.npmjs.com/registry" } } diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/README.md b/samples/client/petstore/typescript-angular-v2/with-interfaces/README.md new file mode 100644 index 00000000000..afa7807e82a --- /dev/null +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/README.md @@ -0,0 +1,139 @@ +## @swagger/angular2-typescript-petstore@0.0.1 + +### 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 @swagger/angular2-typescript-petstore@0.0.1 --save +``` + +_unPublished (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE --save +``` + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE: +``` +npm link +``` + +In your project: +``` +npm link @swagger/angular2-typescript-petstore@0.0.1 +``` + +In your Angular project: + + +``` +// without configuring providers +import { ApiModule } from '@swagger/angular2-typescript-petstore'; + +@NgModule({ + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from '@swagger/angular2-typescript-petstore'; + +export function apiConfigFactory (): Configuration => { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from '@swagger/angular2-typescript-petstore'; + +export class AppComponent { + constructor(private apiGateway: DefaultApi) { } +} +``` + +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + +### Set service base path +If different than the generated base path, during app bootstrap, you can provide the base path to your service. + +``` +import { BASE_PATH } from '@swagger/angular2-typescript-petstore'; + +bootstrap(AppComponent, [ + { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, +]); +``` +or + +``` +import { BASE_PATH } from '@swagger/angular2-typescript-petstore'; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + + +#### Using @angular/cli +First extend your `src/environments/*.ts` files by adding the corresponding base path: + +``` +export const environment = { + production: false, + API_BASE_PATH: 'http://127.0.0.1:8080' +}; +``` + +In the src/app/app.module.ts: +``` +import { BASE_PATH } from '@swagger/angular2-typescript-petstore'; +import { environment } from '../environments/environment'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ ], + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] +}) +export class AppModule { } +``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/api.module.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/api.module.ts index dcce0dbd628..4b290cd5a49 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/api.module.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/api.module.ts @@ -1,4 +1,4 @@ -import { NgModule, ModuleWithProviders } from '@angular/core'; +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HttpModule } from '@angular/http'; import { Configuration } from './configuration'; @@ -11,13 +11,22 @@ import { UserService } from './api/user.service'; imports: [ CommonModule, HttpModule ], declarations: [], exports: [], - providers: [ PetService, StoreService, UserService ] + providers: [ + PetService, + StoreService, + UserService ] }) export class ApiModule { - public static forConfig(configurationFactory: () => Configuration): ModuleWithProviders { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { return { ngModule: ApiModule, - providers: [ {provide: Configuration, useFactory: configurationFactory}] + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + } + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import your base AppModule only.'); } } } diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/pet.service.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/pet.service.ts index 8ff5eda659d..8f606901d00 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/pet.service.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - /* tslint:disable:no-unused-variable member-ordering */ import { Inject, Injectable, Optional } from '@angular/core'; @@ -60,7 +59,6 @@ export class PetService implements PetServiceInterface { return false; } - /** * * @summary Add a new pet to the store @@ -215,7 +213,25 @@ export class PetService implements PetServiceInterface { headers.set('Authorization', 'Bearer ' + accessToken); } - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -255,6 +271,20 @@ export class PetService implements PetServiceInterface { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, @@ -293,6 +323,20 @@ export class PetService implements PetServiceInterface { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -332,6 +376,20 @@ export class PetService implements PetServiceInterface { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -363,6 +421,20 @@ export class PetService implements PetServiceInterface { headers.set('api_key', this.configuration.apiKeys["api_key"]); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -396,7 +468,25 @@ export class PetService implements PetServiceInterface { headers.set('Authorization', 'Bearer ' + accessToken); } - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, @@ -434,10 +524,21 @@ export class PetService implements PetServiceInterface { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + // to determine the Content-Type header let consumes: string[] = [ 'application/x-www-form-urlencoded' ]; + const canConsumeForm = this.canConsumeForm(consumes); let formParams: { append(param: string, value: any): void; }; @@ -453,8 +554,6 @@ export class PetService implements PetServiceInterface { headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } - - if (name !== undefined) { formParams.append('name', name); } @@ -498,10 +597,20 @@ export class PetService implements PetServiceInterface { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + // to determine the Content-Type header let consumes: string[] = [ 'multipart/form-data' ]; + const canConsumeForm = this.canConsumeForm(consumes); let formParams: { append(param: string, value: any): void; }; @@ -520,8 +629,6 @@ export class PetService implements PetServiceInterface { headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } - - if (additionalMetadata !== undefined) { formParams.append('additionalMetadata', additionalMetadata); } diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/pet.serviceInterface.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/pet.serviceInterface.ts index 5ee39b3ab69..968ed61c846 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/pet.serviceInterface.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/pet.serviceInterface.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - import { Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/store.service.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/store.service.ts index 1297e638d43..30d37ccf381 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/store.service.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - /* tslint:disable:no-unused-variable member-ordering */ import { Inject, Injectable, Optional } from '@angular/core'; @@ -59,7 +58,6 @@ export class StoreService implements StoreServiceInterface { return false; } - /** * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @summary Delete purchase order by ID @@ -136,6 +134,20 @@ export class StoreService implements StoreServiceInterface { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, @@ -162,6 +174,19 @@ export class StoreService implements StoreServiceInterface { headers.set('api_key', this.configuration.apiKeys["api_key"]); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -187,6 +212,20 @@ export class StoreService implements StoreServiceInterface { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -212,7 +251,23 @@ export class StoreService implements StoreServiceInterface { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/store.serviceInterface.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/store.serviceInterface.ts index a40dcc47b83..f7fdf5fb0d9 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/store.serviceInterface.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/store.serviceInterface.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - import { Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.service.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.service.ts index 480d00b3bb6..17b1d6311bd 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.service.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - /* tslint:disable:no-unused-variable member-ordering */ import { Inject, Injectable, Optional } from '@angular/core'; @@ -59,7 +58,6 @@ export class UserService implements UserServiceInterface { return false; } - /** * This can only be done by the logged in user. * @summary Create user @@ -202,7 +200,23 @@ export class UserService implements UserServiceInterface { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -230,7 +244,23 @@ export class UserService implements UserServiceInterface { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -258,7 +288,23 @@ export class UserService implements UserServiceInterface { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -286,6 +332,20 @@ export class UserService implements UserServiceInterface { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, @@ -311,6 +371,20 @@ export class UserService implements UserServiceInterface { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -348,6 +422,20 @@ export class UserService implements UserServiceInterface { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -370,6 +458,20 @@ export class UserService implements UserServiceInterface { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -399,7 +501,23 @@ export class UserService implements UserServiceInterface { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.serviceInterface.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.serviceInterface.ts index 3cab3a9c64b..f68e221df9a 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.serviceInterface.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.serviceInterface.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - import { Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/configuration.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/configuration.ts index 005c3a26df3..d486fc9f97d 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/configuration.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/configuration.ts @@ -23,4 +23,57 @@ export class Configuration { this.basePath = configurationParameters.basePath; this.withCredentials = configurationParameters.withCredentials; } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param {string[]} contentTypes - the array of content types that are available for selection + * @returns {string} the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string { + if (contentTypes.length == 0) { + return undefined; + } + + let type = contentTypes.find(x => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param {string[]} accepts - the array of content types that are available for selection. + * @returns {string} the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string { + if (accepts.length == 0) { + return undefined; + } + + let type = accepts.find(x => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param {string} mime - MIME (Multipurpose Internet Mail Extensions) + * @return {boolean} True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime != null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } } diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/model/Category.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/model/Category.ts index d09f8d7b265..5040d1db915 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/model/Category.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/model/Category.ts @@ -11,13 +11,10 @@ */ - /** * A category for a pet */ export interface Category { id?: number; - name?: string; - } diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/model/Order.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/model/Order.ts index 4639b8c2949..33b60bb6e16 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/model/Order.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/model/Order.ts @@ -11,27 +11,25 @@ */ - /** * An order for a pets from the pet store */ export interface Order { id?: number; - petId?: number; - quantity?: number; - shipDate?: Date; - /** * Order Status */ status?: Order.StatusEnum; - complete?: boolean; - } export namespace Order { export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum + } } diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/model/Pet.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/model/Pet.ts index ce6c535b867..342ab5f8e75 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/model/Pet.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/model/Pet.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - import { Category } from './category'; import { Tag } from './tag'; @@ -19,21 +18,20 @@ import { Tag } from './tag'; */ export interface Pet { id?: number; - category?: Category; - name: string; - photoUrls: Array; - tags?: Array; - /** * pet status in the store */ status?: Pet.StatusEnum; - } export namespace Pet { export type StatusEnum = 'available' | 'pending' | 'sold'; + export const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum + } } diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/model/Tag.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/model/Tag.ts index 3ed1eeff8f3..c7524000357 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/model/Tag.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/model/Tag.ts @@ -11,13 +11,10 @@ */ - /** * A tag for a pet */ export interface Tag { id?: number; - name?: string; - } diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/model/User.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/model/User.ts index f4914ae2608..a0261a6f37d 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/model/User.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/model/User.ts @@ -11,28 +11,19 @@ */ - /** * A User who is purchasing from the pet store */ export interface User { id?: number; - username?: string; - firstName?: string; - lastName?: string; - email?: string; - password?: string; - phone?: string; - /** * User Status */ userStatus?: number; - } diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/model/apiResponse.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/model/apiResponse.ts index 3af781cf580..eac4208f022 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/model/apiResponse.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/model/apiResponse.ts @@ -11,15 +11,11 @@ */ - /** * Describes the result of uploading an image resource */ export interface ApiResponse { code?: number; - type?: string; - message?: string; - } diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/package.json b/samples/client/petstore/typescript-angular-v2/with-interfaces/package.json new file mode 100644 index 00000000000..d6aee04c589 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/package.json @@ -0,0 +1,40 @@ +{ + "name": "@swagger/angular2-typescript-petstore", + "version": "0.0.1", + "description": "swagger client for @swagger/angular2-typescript-petstore", + "author": "Swagger Codegen Contributors", + "keywords": [ + "swagger-client" + ], + "license": "Unlicense", + "main": "dist/index.js", + "typings": "dist/index.d.ts", + "scripts": { + "build": "tsc --outDir dist/", + "postinstall": "npm run build" + }, + "peerDependencies": { + "@angular/core": "^2.0.0", + "@angular/http": "^2.0.0", + "@angular/common": "^2.0.0", + "@angular/compiler": "^2.0.0", + "core-js": "^2.4.0", + "reflect-metadata": "^0.1.3", + "rxjs": "^5.4.0", + "zone.js": "^0.7.6" + }, + "devDependencies": { + "@angular/core": "^2.0.0", + "@angular/http": "^2.0.0", + "@angular/common": "^2.0.0", + "@angular/compiler": "^2.0.0", + "@angular/platform-browser": "^2.0.0", + "reflect-metadata": "^0.1.3", + "rxjs": "^5.4.0", + "zone.js": "^0.7.6", + "typescript": "^2.1.5" + }, + "publishConfig": { + "registry":"https://skimdb.npmjs.com/registry" + } +} diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/tsconfig.json b/samples/client/petstore/typescript-angular-v2/with-interfaces/tsconfig.json new file mode 100644 index 00000000000..a6e9096bbf7 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "noImplicitAny": false, + "suppressImplicitAnyIndexErrors": true, + "target": "es5", + "module": "es6", + "moduleResolution": "node", + "removeComments": true, + "sourceMap": true, + "outDir": "./dist", + "noLib": false, + "declaration": true, + "lib": [ "es6", "dom" ] + }, + "exclude": [ + "node_modules", + "dist" + ], + "filesGlob": [ + "./model/*.ts", + "./api/*.ts" + ] +} diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/typings.json b/samples/client/petstore/typescript-angular-v2/with-interfaces/typings.json new file mode 100644 index 00000000000..507c40e5cbe --- /dev/null +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/typings.json @@ -0,0 +1,5 @@ +{ + "globalDependencies": { + "core-js": "registry:dt/core-js#0.0.0+20160725163759" + } +} diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/README.md b/samples/client/petstore/typescript-angular-v4.3/npm/README.md index 038fd51491c..afa7807e82a 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/README.md +++ b/samples/client/petstore/typescript-angular-v4.3/npm/README.md @@ -40,36 +40,77 @@ In your project: npm link @swagger/angular2-typescript-petstore@0.0.1 ``` -In your angular2 project: +In your Angular project: + ``` -import { DefaultApi } from '@swagger/angular2-typescript-petstore/api/api'; +// without configuring providers +import { ApiModule } from '@swagger/angular2-typescript-petstore'; + @NgModule({ - imports: [], - declarations: [], - exports: [], - providers: [AppModule] + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] }) -export class CoreModule {} +export class AppModule {} ``` + ``` -import { DefaultApi } from '@swagger/angular2-typescript-petstore/api/api'; +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from '@swagger/angular2-typescript-petstore'; + +export function apiConfigFactory (): Configuration => { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from '@swagger/angular2-typescript-petstore'; export class AppComponent { constructor(private apiGateway: DefaultApi) { } } ``` +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + ### Set service base path If different than the generated base path, during app bootstrap, you can provide the base path to your service. ``` -import { BASE_PATH } from './path-to-swagger-gen-service/index'; +import { BASE_PATH } from '@swagger/angular2-typescript-petstore'; bootstrap(AppComponent, [ { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, ]); ``` +or + +``` +import { BASE_PATH } from '@swagger/angular2-typescript-petstore'; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + #### Using @angular/cli First extend your `src/environments/*.ts` files by adding the corresponding base path: @@ -88,11 +129,11 @@ import { environment } from '../environments/environment'; @NgModule({ declarations: [ - AppComponent, + AppComponent ], imports: [ ], - providers: [{ provide: BASE_PATH, useValue: useValue: environment.API_BASE_PATH }], - bootstrap: [AppComponent] + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] }) export class AppModule { } ``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/api.module.ts b/samples/client/petstore/typescript-angular-v4.3/npm/api.module.ts index dcce0dbd628..b18695a280a 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/api.module.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/api.module.ts @@ -1,6 +1,6 @@ -import { NgModule, ModuleWithProviders } from '@angular/core'; +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; import { CommonModule } from '@angular/common'; -import { HttpModule } from '@angular/http'; +import { HttpClientModule } from '@angular/common/http'; import { Configuration } from './configuration'; import { PetService } from './api/pet.service'; @@ -8,16 +8,25 @@ import { StoreService } from './api/store.service'; import { UserService } from './api/user.service'; @NgModule({ - imports: [ CommonModule, HttpModule ], + imports: [ CommonModule, HttpClientModule ], declarations: [], exports: [], - providers: [ PetService, StoreService, UserService ] + providers: [ + PetService, + StoreService, + UserService ] }) export class ApiModule { - public static forConfig(configurationFactory: () => Configuration): ModuleWithProviders { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { return { ngModule: ApiModule, - providers: [ {provide: Configuration, useFactory: configurationFactory}] + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + } + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import your base AppModule only.'); } } } diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v4.3/npm/api/pet.service.ts index ee44df243de..e6dbfc38628 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/api/pet.service.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - /* tslint:disable:no-unused-variable member-ordering */ import { Inject, Injectable, Optional } from '@angular/core'; @@ -58,7 +57,6 @@ export class PetService { } - /** * Add a new pet to the store * @@ -79,11 +77,33 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - return this.httpClient.post(`${this.basePath}/pet`, body, - { - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers = headers.set("Content-Type", httpContentTypeSelected); + } + + return this.httpClient.post(`${this.basePath}/pet`, + body, + { + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } /** @@ -110,11 +130,26 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - return this.httpClient.delete(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, - { - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + return this.httpClient.delete(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, + { + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } /** @@ -142,12 +177,27 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - return this.httpClient.get(`${this.basePath}/pet/findByStatus`, - { - params: queryParameters, - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + return this.httpClient.get(`${this.basePath}/pet/findByStatus`, + { + params: queryParameters, + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } /** @@ -175,12 +225,27 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - return this.httpClient.get(`${this.basePath}/pet/findByTags`, - { - params: queryParameters, - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + return this.httpClient.get(`${this.basePath}/pet/findByTags`, + { + params: queryParameters, + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } /** @@ -200,11 +265,26 @@ export class PetService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - return this.httpClient.get(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, - { - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + return this.httpClient.get(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, + { + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } /** @@ -227,11 +307,33 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - return this.httpClient.put(`${this.basePath}/pet`, body, - { - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers = headers.set("Content-Type", httpContentTypeSelected); + } + + return this.httpClient.put(`${this.basePath}/pet`, + body, + { + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } /** @@ -256,10 +358,21 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + // to determine the Content-Type header let consumes: string[] = [ 'application/x-www-form-urlencoded' ]; + const canConsumeForm = this.canConsumeForm(consumes); let formParams: { append(param: string, value: any): void; }; @@ -271,8 +384,6 @@ export class PetService { formParams = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); } - - if (name !== undefined) { formParams = formParams.append('name', name) || formParams; } @@ -280,11 +391,13 @@ export class PetService { formParams = formParams.append('status', status) || formParams; } - return this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, - convertFormParamsToString ? formParams.toString() : formParams, { - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + return this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, + convertFormParamsToString ? formParams.toString() : formParams, + { + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } /** @@ -309,10 +422,20 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + // to determine the Content-Type header let consumes: string[] = [ 'multipart/form-data' ]; + const canConsumeForm = this.canConsumeForm(consumes); let formParams: { append(param: string, value: any): void; }; @@ -327,8 +450,6 @@ export class PetService { formParams = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); } - - if (additionalMetadata !== undefined) { formParams = formParams.append('additionalMetadata', additionalMetadata) || formParams; } @@ -336,11 +457,13 @@ export class PetService { formParams = formParams.append('file', file) || formParams; } - return this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, - convertFormParamsToString ? formParams.toString() : formParams, { - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + return this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, + convertFormParamsToString ? formParams.toString() : formParams, + { + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } } diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v4.3/npm/api/store.service.ts index f0cf7dbc1cb..e381873818a 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/api/store.service.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - /* tslint:disable:no-unused-variable member-ordering */ import { Inject, Injectable, Optional } from '@angular/core'; @@ -57,7 +56,6 @@ export class StoreService { } - /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -70,11 +68,26 @@ export class StoreService { let headers = this.defaultHeaders; - return this.httpClient.delete(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, - { - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + return this.httpClient.delete(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + { + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } /** @@ -90,11 +103,25 @@ export class StoreService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - return this.httpClient.get(`${this.basePath}/store/inventory`, - { - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + return this.httpClient.get(`${this.basePath}/store/inventory`, + { + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } /** @@ -109,11 +136,26 @@ export class StoreService { let headers = this.defaultHeaders; - return this.httpClient.get(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, - { - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + return this.httpClient.get(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + { + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } /** @@ -128,11 +170,31 @@ export class StoreService { let headers = this.defaultHeaders; - return this.httpClient.post(`${this.basePath}/store/order`, body, - { - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers = headers.set("Content-Type", httpContentTypeSelected); + } + + return this.httpClient.post(`${this.basePath}/store/order`, + body, + { + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } } diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v4.3/npm/api/user.service.ts index d67fb448fc3..55fb2bb500b 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/api/user.service.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - /* tslint:disable:no-unused-variable member-ordering */ import { Inject, Injectable, Optional } from '@angular/core'; @@ -57,7 +56,6 @@ export class UserService { } - /** * Create user * This can only be done by the logged in user. @@ -70,11 +68,31 @@ export class UserService { let headers = this.defaultHeaders; - return this.httpClient.post(`${this.basePath}/user`, body, - { - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers = headers.set("Content-Type", httpContentTypeSelected); + } + + return this.httpClient.post(`${this.basePath}/user`, + body, + { + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } /** @@ -89,11 +107,31 @@ export class UserService { let headers = this.defaultHeaders; - return this.httpClient.post(`${this.basePath}/user/createWithArray`, body, - { - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers = headers.set("Content-Type", httpContentTypeSelected); + } + + return this.httpClient.post(`${this.basePath}/user/createWithArray`, + body, + { + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } /** @@ -108,11 +146,31 @@ export class UserService { let headers = this.defaultHeaders; - return this.httpClient.post(`${this.basePath}/user/createWithList`, body, - { - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers = headers.set("Content-Type", httpContentTypeSelected); + } + + return this.httpClient.post(`${this.basePath}/user/createWithList`, + body, + { + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } /** @@ -127,11 +185,26 @@ export class UserService { let headers = this.defaultHeaders; - return this.httpClient.delete(`${this.basePath}/user/${encodeURIComponent(String(username))}`, - { - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + return this.httpClient.delete(`${this.basePath}/user/${encodeURIComponent(String(username))}`, + { + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } /** @@ -146,11 +219,26 @@ export class UserService { let headers = this.defaultHeaders; - return this.httpClient.get(`${this.basePath}/user/${encodeURIComponent(String(username))}`, - { - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + return this.httpClient.get(`${this.basePath}/user/${encodeURIComponent(String(username))}`, + { + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } /** @@ -177,12 +265,27 @@ export class UserService { let headers = this.defaultHeaders; - return this.httpClient.get(`${this.basePath}/user/login`, - { - params: queryParameters, - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + return this.httpClient.get(`${this.basePath}/user/login`, + { + params: queryParameters, + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } /** @@ -193,11 +296,26 @@ export class UserService { let headers = this.defaultHeaders; - return this.httpClient.get(`${this.basePath}/user/logout`, - { - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + return this.httpClient.get(`${this.basePath}/user/logout`, + { + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } /** @@ -216,11 +334,31 @@ export class UserService { let headers = this.defaultHeaders; - return this.httpClient.put(`${this.basePath}/user/${encodeURIComponent(String(username))}`, body, - { - headers: headers, - withCredentials: this.configuration.withCredentials, - }); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers = headers.set("Content-Type", httpContentTypeSelected); + } + + return this.httpClient.put(`${this.basePath}/user/${encodeURIComponent(String(username))}`, + body, + { + headers: headers, + withCredentials: this.configuration.withCredentials, + } + ); } } diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/configuration.ts b/samples/client/petstore/typescript-angular-v4.3/npm/configuration.ts index 005c3a26df3..d486fc9f97d 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/configuration.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/configuration.ts @@ -23,4 +23,57 @@ export class Configuration { this.basePath = configurationParameters.basePath; this.withCredentials = configurationParameters.withCredentials; } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param {string[]} contentTypes - the array of content types that are available for selection + * @returns {string} the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string { + if (contentTypes.length == 0) { + return undefined; + } + + let type = contentTypes.find(x => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param {string[]} accepts - the array of content types that are available for selection. + * @returns {string} the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string { + if (accepts.length == 0) { + return undefined; + } + + let type = accepts.find(x => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param {string} mime - MIME (Multipurpose Internet Mail Extensions) + * @return {boolean} True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime != null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } } diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/model/apiResponse.ts b/samples/client/petstore/typescript-angular-v4.3/npm/model/apiResponse.ts index 3af781cf580..eac4208f022 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/model/apiResponse.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/model/apiResponse.ts @@ -11,15 +11,11 @@ */ - /** * Describes the result of uploading an image resource */ export interface ApiResponse { code?: number; - type?: string; - message?: string; - } diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/model/category.ts b/samples/client/petstore/typescript-angular-v4.3/npm/model/category.ts index d09f8d7b265..5040d1db915 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/model/category.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/model/category.ts @@ -11,13 +11,10 @@ */ - /** * A category for a pet */ export interface Category { id?: number; - name?: string; - } diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/model/order.ts b/samples/client/petstore/typescript-angular-v4.3/npm/model/order.ts index 402a86689c8..33b60bb6e16 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/model/order.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/model/order.ts @@ -11,31 +11,25 @@ */ - /** * An order for a pets from the pet store */ export interface Order { id?: number; - petId?: number; - quantity?: number; - shipDate?: Date; - /** * Order Status */ status?: Order.StatusEnum; - complete?: boolean; - } export namespace Order { - export enum StatusEnum { - Placed = 'placed', - Approved = 'approved', - Delivered = 'delivered' + export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum } } diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/model/pet.ts b/samples/client/petstore/typescript-angular-v4.3/npm/model/pet.ts index 0d6137d02cf..342ab5f8e75 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/model/pet.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/model/pet.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - import { Category } from './category'; import { Tag } from './tag'; @@ -19,25 +18,20 @@ import { Tag } from './tag'; */ 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 enum StatusEnum { - Available = 'available', - Pending = 'pending', - Sold = 'sold' + export type StatusEnum = 'available' | 'pending' | 'sold'; + export const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum } } diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/model/tag.ts b/samples/client/petstore/typescript-angular-v4.3/npm/model/tag.ts index 3ed1eeff8f3..c7524000357 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/model/tag.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/model/tag.ts @@ -11,13 +11,10 @@ */ - /** * A tag for a pet */ export interface Tag { id?: number; - name?: string; - } diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/model/user.ts b/samples/client/petstore/typescript-angular-v4.3/npm/model/user.ts index f4914ae2608..a0261a6f37d 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/model/user.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/model/user.ts @@ -11,28 +11,19 @@ */ - /** * A User who is purchasing from the pet store */ export interface User { id?: number; - username?: string; - firstName?: string; - lastName?: string; - email?: string; - password?: string; - phone?: string; - /** * User Status */ userStatus?: number; - } diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/package-lock.json b/samples/client/petstore/typescript-angular-v4.3/npm/package-lock.json new file mode 100644 index 00000000000..a7f42957533 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v4.3/npm/package-lock.json @@ -0,0 +1,73 @@ +{ + "name": "@swagger/angular2-typescript-petstore", + "version": "0.0.1", + "lockfileVersion": 1, + "dependencies": { + "@angular/common": { + "version": "4.4.6", + "resolved": "https://registry.npmjs.org/@angular/common/-/common-4.4.6.tgz", + "integrity": "sha1-S4FCByTggooOg5uVpV6xp+g5GPI=", + "dev": true + }, + "@angular/compiler": { + "version": "4.4.6", + "resolved": "https://registry.npmjs.org/@angular/compiler/-/compiler-4.4.6.tgz", + "integrity": "sha1-LuH68lt1fh0SiXkHS+f65SmzvCA=", + "dev": true + }, + "@angular/core": { + "version": "4.4.6", + "resolved": "https://registry.npmjs.org/@angular/core/-/core-4.4.6.tgz", + "integrity": "sha1-EwMf0Q3P5DiHVBmzjyESCVi8I1Q=", + "dev": true + }, + "@angular/http": { + "version": "4.4.6", + "resolved": "https://registry.npmjs.org/@angular/http/-/http-4.4.6.tgz", + "integrity": "sha1-CvaAxnEL3AJtlA4iXP0PalwAXQw=", + "dev": true + }, + "@angular/platform-browser": { + "version": "4.4.6", + "resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-4.4.6.tgz", + "integrity": "sha1-qYOcVH4bZU+h0kqJeAyLpquNzOA=", + "dev": true + }, + "reflect-metadata": { + "version": "0.1.10", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.10.tgz", + "integrity": "sha1-tPg3BEFqytiZiMmxVjXUfgO5NEo=", + "dev": true + }, + "rxjs": { + "version": "5.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-5.5.2.tgz", + "integrity": "sha512-oRYoIKWBU3Ic37fLA5VJu31VqQO4bWubRntcHSJ+cwaDQBwdnZ9x4zmhJfm/nFQ2E82/I4loSioHnACamrKGgA==", + "dev": true + }, + "symbol-observable": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-1.0.4.tgz", + "integrity": "sha1-Kb9hXUqnEhvdiYsi1LP5vE4qoD0=", + "dev": true + }, + "tslib": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.8.0.tgz", + "integrity": "sha512-ymKWWZJST0/CkgduC2qkzjMOWr4bouhuURNXCn/inEX0L57BnRG6FhX76o7FOnsjHazCjfU2LKeSrlS2sIKQJg==", + "dev": true + }, + "typescript": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-2.5.3.tgz", + "integrity": "sha512-ptLSQs2S4QuS6/OD1eAKG+S5G8QQtrU5RT32JULdZQtM1L3WTi34Wsu48Yndzi8xsObRAB9RPt/KhA9wlpEF6w==", + "dev": true + }, + "zone.js": { + "version": "0.7.8", + "resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.7.8.tgz", + "integrity": "sha1-Tz/og01EWX8mOQU6D6Q43zT//e0=", + "dev": true + } + } +} diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/package.json b/samples/client/petstore/typescript-angular-v4.3/npm/package.json index 40157c62927..05887c323e6 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/package.json +++ b/samples/client/petstore/typescript-angular-v4.3/npm/package.json @@ -35,6 +35,6 @@ "typescript": "^2.1.5" }, "publishConfig": { - "registry":"https://skimdb.npmjs.com/registry" + "registry": "https://skimdb.npmjs.com/registry" } } diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/pom.xml b/samples/client/petstore/typescript-angular-v4.3/npm/pom.xml new file mode 100644 index 00000000000..060f2ad4582 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v4.3/npm/pom.xml @@ -0,0 +1,60 @@ + + 4.0.0 + com.wordnik + TSAngular43PestoreTest + pom + 1.0-SNAPSHOT + TS Angular4.3 Pettore Test + + + + 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 + integration-test + + exec + + + npm + + run + build + + + + + + + + diff --git a/samples/client/petstore/typescript-angular-v4/npm/README.md b/samples/client/petstore/typescript-angular-v4/npm/README.md index 038fd51491c..afa7807e82a 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/README.md +++ b/samples/client/petstore/typescript-angular-v4/npm/README.md @@ -40,36 +40,77 @@ In your project: npm link @swagger/angular2-typescript-petstore@0.0.1 ``` -In your angular2 project: +In your Angular project: + ``` -import { DefaultApi } from '@swagger/angular2-typescript-petstore/api/api'; +// without configuring providers +import { ApiModule } from '@swagger/angular2-typescript-petstore'; + @NgModule({ - imports: [], - declarations: [], - exports: [], - providers: [AppModule] + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] }) -export class CoreModule {} +export class AppModule {} ``` + ``` -import { DefaultApi } from '@swagger/angular2-typescript-petstore/api/api'; +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from '@swagger/angular2-typescript-petstore'; + +export function apiConfigFactory (): Configuration => { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from '@swagger/angular2-typescript-petstore'; export class AppComponent { constructor(private apiGateway: DefaultApi) { } } ``` +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + ### Set service base path If different than the generated base path, during app bootstrap, you can provide the base path to your service. ``` -import { BASE_PATH } from './path-to-swagger-gen-service/index'; +import { BASE_PATH } from '@swagger/angular2-typescript-petstore'; bootstrap(AppComponent, [ { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, ]); ``` +or + +``` +import { BASE_PATH } from '@swagger/angular2-typescript-petstore'; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + #### Using @angular/cli First extend your `src/environments/*.ts` files by adding the corresponding base path: @@ -88,11 +129,11 @@ import { environment } from '../environments/environment'; @NgModule({ declarations: [ - AppComponent, + AppComponent ], imports: [ ], - providers: [{ provide: BASE_PATH, useValue: useValue: environment.API_BASE_PATH }], - bootstrap: [AppComponent] + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] }) export class AppModule { } ``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v4/npm/api.module.ts b/samples/client/petstore/typescript-angular-v4/npm/api.module.ts index dcce0dbd628..4b290cd5a49 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/api.module.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/api.module.ts @@ -1,4 +1,4 @@ -import { NgModule, ModuleWithProviders } from '@angular/core'; +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HttpModule } from '@angular/http'; import { Configuration } from './configuration'; @@ -11,13 +11,22 @@ import { UserService } from './api/user.service'; imports: [ CommonModule, HttpModule ], declarations: [], exports: [], - providers: [ PetService, StoreService, UserService ] + providers: [ + PetService, + StoreService, + UserService ] }) export class ApiModule { - public static forConfig(configurationFactory: () => Configuration): ModuleWithProviders { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { return { ngModule: ApiModule, - providers: [ {provide: Configuration, useFactory: configurationFactory}] + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + } + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import your base AppModule only.'); } } } diff --git a/samples/client/petstore/typescript-angular-v4/npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v4/npm/api/pet.service.ts index 11a1b603831..4435de468a2 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/api/pet.service.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - /* tslint:disable:no-unused-variable member-ordering */ import { Inject, Injectable, Optional } from '@angular/core'; @@ -59,7 +58,6 @@ export class PetService { return false; } - /** * * @summary Add a new pet to the store @@ -214,7 +212,25 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -254,6 +270,20 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, @@ -292,6 +322,20 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -331,6 +375,20 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -362,6 +420,20 @@ export class PetService { headers.set('api_key', this.configuration.apiKeys["api_key"]); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -395,7 +467,25 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, @@ -433,10 +523,21 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + // to determine the Content-Type header let consumes: string[] = [ 'application/x-www-form-urlencoded' ]; + const canConsumeForm = this.canConsumeForm(consumes); let formParams: { append(param: string, value: any): void; }; @@ -452,8 +553,6 @@ export class PetService { headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } - - if (name !== undefined) { formParams.append('name', name); } @@ -497,10 +596,20 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + // to determine the Content-Type header let consumes: string[] = [ 'multipart/form-data' ]; + const canConsumeForm = this.canConsumeForm(consumes); let formParams: { append(param: string, value: any): void; }; @@ -519,8 +628,6 @@ export class PetService { headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); } - - if (additionalMetadata !== undefined) { formParams.append('additionalMetadata', additionalMetadata); } diff --git a/samples/client/petstore/typescript-angular-v4/npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v4/npm/api/store.service.ts index 393d291ba3d..3eb043313ff 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/api/store.service.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - /* tslint:disable:no-unused-variable member-ordering */ import { Inject, Injectable, Optional } from '@angular/core'; @@ -58,7 +57,6 @@ export class StoreService { return false; } - /** * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @summary Delete purchase order by ID @@ -135,6 +133,20 @@ export class StoreService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, @@ -161,6 +173,19 @@ export class StoreService { headers.set('api_key', this.configuration.apiKeys["api_key"]); } + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -186,6 +211,20 @@ export class StoreService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -211,7 +250,23 @@ export class StoreService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, diff --git a/samples/client/petstore/typescript-angular-v4/npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v4/npm/api/user.service.ts index f495f1f9d39..7fd15126b81 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/api/user.service.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - /* tslint:disable:no-unused-variable member-ordering */ import { Inject, Injectable, Optional } from '@angular/core'; @@ -58,7 +57,6 @@ export class UserService { return false; } - /** * This can only be done by the logged in user. * @summary Create user @@ -201,7 +199,23 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -229,7 +243,23 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -257,7 +287,23 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -285,6 +331,20 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, @@ -310,6 +370,20 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -347,6 +421,20 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -369,6 +457,20 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -398,7 +500,23 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - headers.set('Content-Type', 'application/json'); + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + let httpHeaderAcceptSelected: string = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers.set("Accept", httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + let httpContentTypeSelected:string = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers.set('Content-Type', httpContentTypeSelected); + } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, diff --git a/samples/client/petstore/typescript-angular-v4/npm/configuration.ts b/samples/client/petstore/typescript-angular-v4/npm/configuration.ts index 005c3a26df3..d486fc9f97d 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/configuration.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/configuration.ts @@ -23,4 +23,57 @@ export class Configuration { this.basePath = configurationParameters.basePath; this.withCredentials = configurationParameters.withCredentials; } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param {string[]} contentTypes - the array of content types that are available for selection + * @returns {string} the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string { + if (contentTypes.length == 0) { + return undefined; + } + + let type = contentTypes.find(x => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param {string[]} accepts - the array of content types that are available for selection. + * @returns {string} the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string { + if (accepts.length == 0) { + return undefined; + } + + let type = accepts.find(x => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param {string} mime - MIME (Multipurpose Internet Mail Extensions) + * @return {boolean} True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime != null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } } diff --git a/samples/client/petstore/typescript-angular-v4/npm/model/apiResponse.ts b/samples/client/petstore/typescript-angular-v4/npm/model/apiResponse.ts index 3af781cf580..eac4208f022 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/model/apiResponse.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/model/apiResponse.ts @@ -11,15 +11,11 @@ */ - /** * Describes the result of uploading an image resource */ export interface ApiResponse { code?: number; - type?: string; - message?: string; - } diff --git a/samples/client/petstore/typescript-angular-v4/npm/model/category.ts b/samples/client/petstore/typescript-angular-v4/npm/model/category.ts index d09f8d7b265..5040d1db915 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/model/category.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/model/category.ts @@ -11,13 +11,10 @@ */ - /** * A category for a pet */ export interface Category { id?: number; - name?: string; - } diff --git a/samples/client/petstore/typescript-angular-v4/npm/model/order.ts b/samples/client/petstore/typescript-angular-v4/npm/model/order.ts index 4639b8c2949..33b60bb6e16 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/model/order.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/model/order.ts @@ -11,27 +11,25 @@ */ - /** * An order for a pets from the pet store */ export interface Order { id?: number; - petId?: number; - quantity?: number; - shipDate?: Date; - /** * Order Status */ status?: Order.StatusEnum; - complete?: boolean; - } export namespace Order { export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum + } } diff --git a/samples/client/petstore/typescript-angular-v4/npm/model/pet.ts b/samples/client/petstore/typescript-angular-v4/npm/model/pet.ts index ce6c535b867..342ab5f8e75 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/model/pet.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/model/pet.ts @@ -9,7 +9,6 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - import { Category } from './category'; import { Tag } from './tag'; @@ -19,21 +18,20 @@ import { Tag } from './tag'; */ export interface Pet { id?: number; - category?: Category; - name: string; - photoUrls: Array; - tags?: Array; - /** * pet status in the store */ status?: Pet.StatusEnum; - } export namespace Pet { export type StatusEnum = 'available' | 'pending' | 'sold'; + export const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum + } } diff --git a/samples/client/petstore/typescript-angular-v4/npm/model/tag.ts b/samples/client/petstore/typescript-angular-v4/npm/model/tag.ts index 3ed1eeff8f3..c7524000357 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/model/tag.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/model/tag.ts @@ -11,13 +11,10 @@ */ - /** * A tag for a pet */ export interface Tag { id?: number; - name?: string; - } diff --git a/samples/client/petstore/typescript-angular-v4/npm/model/user.ts b/samples/client/petstore/typescript-angular-v4/npm/model/user.ts index f4914ae2608..a0261a6f37d 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/model/user.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/model/user.ts @@ -11,28 +11,19 @@ */ - /** * A User who is purchasing from the pet store */ export interface User { id?: number; - username?: string; - firstName?: string; - lastName?: string; - email?: string; - password?: string; - phone?: string; - /** * User Status */ userStatus?: number; - } diff --git a/samples/client/petstore/typescript-angular-v4/npm/package.json b/samples/client/petstore/typescript-angular-v4/npm/package.json index af9c5d898e6..b33b2586f0f 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/package.json +++ b/samples/client/petstore/typescript-angular-v4/npm/package.json @@ -35,6 +35,6 @@ "typescript": "^2.1.5" }, "publishConfig": { - "registry":"https://skimdb.npmjs.com/registry" + "registry": "https://skimdb.npmjs.com/registry" } } diff --git a/samples/client/petstore/typescript-fetch/builds/default/api.ts b/samples/client/petstore/typescript-fetch/builds/default/api.ts index b31bd51457e..524623e31c8 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/api.ts @@ -1,3 +1,4 @@ +/// // tslint:disable /** * Swagger Petstore @@ -13,7 +14,7 @@ import * as url from "url"; -import * as isomorphicFetch from "isomorphic-fetch"; +import * as portableFetch from "portable-fetch"; import { Configuration } from "./configuration"; const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); @@ -56,7 +57,7 @@ export interface FetchArgs { export class BaseAPI { protected configuration: Configuration; - constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected fetch: FetchAPI = isomorphicFetch) { + constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected fetch: FetchAPI = portableFetch) { if (configuration) { this.configuration = configuration; this.basePath = configuration.basePath || this.basePath; @@ -338,32 +339,32 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) if (body === null || body === undefined) { throw new RequiredError('body','Required parameter body was null or undefined when calling addPet.'); } - const path = `/pet`; - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'POST' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarPath = `/pet`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const accessTokenValue = typeof configuration.accessToken === 'function' + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) : configuration.accessToken; - headerParameter["Authorization"] = "Bearer " + accessTokenValue; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } - headerParameter['Content-Type'] = 'application/json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); - requestOptions.body = JSON.stringify(body || {}); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + localVarRequestOptions.body = JSON.stringify(body || {}); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, /** @@ -379,34 +380,34 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) if (petId === null || petId === undefined) { throw new RequiredError('petId','Required parameter petId was null or undefined when calling deletePet.'); } - const path = `/pet/{petId}` + const localVarPath = `/pet/{petId}` .replace(`{${"petId"}}`, encodeURIComponent(String(petId))); - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'DELETE' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'DELETE' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const accessTokenValue = typeof configuration.accessToken === 'function' + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) : configuration.accessToken; - headerParameter["Authorization"] = "Bearer " + accessTokenValue; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } if (apiKey !== undefined && apiKey !== null) { - headerParameter['api_key'] = String(apiKey); + localVarHeaderParameter['api_key'] = String(apiKey); } - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, /** @@ -421,33 +422,33 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) if (status === null || status === undefined) { throw new RequiredError('status','Required parameter status was null or undefined when calling findPetsByStatus.'); } - const path = `/pet/findByStatus`; - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'GET' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarPath = `/pet/findByStatus`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const accessTokenValue = typeof configuration.accessToken === 'function' + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) : configuration.accessToken; - headerParameter["Authorization"] = "Bearer " + accessTokenValue; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } if (status) { - queryParameter['status'] = status.join(COLLECTION_FORMATS["csv"]); + localVarQueryParameter['status'] = status.join(COLLECTION_FORMATS["csv"]); } - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, /** @@ -462,33 +463,33 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) if (tags === null || tags === undefined) { throw new RequiredError('tags','Required parameter tags was null or undefined when calling findPetsByTags.'); } - const path = `/pet/findByTags`; - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'GET' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarPath = `/pet/findByTags`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const accessTokenValue = typeof configuration.accessToken === 'function' + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) : configuration.accessToken; - headerParameter["Authorization"] = "Bearer " + accessTokenValue; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } if (tags) { - queryParameter['tags'] = tags.join(COLLECTION_FORMATS["csv"]); + localVarQueryParameter['tags'] = tags.join(COLLECTION_FORMATS["csv"]); } - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, /** @@ -503,29 +504,29 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) if (petId === null || petId === undefined) { throw new RequiredError('petId','Required parameter petId was null or undefined when calling getPetById.'); } - const path = `/pet/{petId}` + const localVarPath = `/pet/{petId}` .replace(`{${"petId"}}`, encodeURIComponent(String(petId))); - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'GET' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; // authentication api_key required if (configuration && configuration.apiKey) { - const apiKeyValue = typeof configuration.apiKey === 'function' + const localVarApiKeyValue = typeof configuration.apiKey === 'function' ? configuration.apiKey("api_key") : configuration.apiKey; - headerParameter["api_key"] = apiKeyValue; + localVarHeaderParameter["api_key"] = localVarApiKeyValue; } - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, /** @@ -540,32 +541,32 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) if (body === null || body === undefined) { throw new RequiredError('body','Required parameter body was null or undefined when calling updatePet.'); } - const path = `/pet`; - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'PUT' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarPath = `/pet`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'PUT' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const accessTokenValue = typeof configuration.accessToken === 'function' + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) : configuration.accessToken; - headerParameter["Authorization"] = "Bearer " + accessTokenValue; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } - headerParameter['Content-Type'] = 'application/json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); - requestOptions.body = JSON.stringify(body || {}); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + localVarRequestOptions.body = JSON.stringify(body || {}); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, /** @@ -582,42 +583,42 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) if (petId === null || petId === undefined) { throw new RequiredError('petId','Required parameter petId was null or undefined when calling updatePetWithForm.'); } - const path = `/pet/{petId}` + const localVarPath = `/pet/{petId}` .replace(`{${"petId"}}`, encodeURIComponent(String(petId))); - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'POST' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; - const formParams = new url.URLSearchParams(); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + const localVarFormParams = new url.URLSearchParams(); // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const accessTokenValue = typeof configuration.accessToken === 'function' + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) : configuration.accessToken; - headerParameter["Authorization"] = "Bearer " + accessTokenValue; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } if (name !== undefined) { - formParams.set('name', name as any); + localVarFormParams.set('name', name as any); } if (status !== undefined) { - formParams.set('status', status as any); + localVarFormParams.set('status', status as any); } - headerParameter['Content-Type'] = 'application/x-www-form-urlencoded'; + localVarHeaderParameter['Content-Type'] = 'application/x-www-form-urlencoded'; - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); - requestOptions.body = formParams.toString(); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + localVarRequestOptions.body = localVarFormParams.toString(); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, /** @@ -634,42 +635,42 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) if (petId === null || petId === undefined) { throw new RequiredError('petId','Required parameter petId was null or undefined when calling uploadFile.'); } - const path = `/pet/{petId}/uploadImage` + const localVarPath = `/pet/{petId}/uploadImage` .replace(`{${"petId"}}`, encodeURIComponent(String(petId))); - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'POST' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; - const formParams = new url.URLSearchParams(); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + const localVarFormParams = new url.URLSearchParams(); // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const accessTokenValue = typeof configuration.accessToken === 'function' + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) : configuration.accessToken; - headerParameter["Authorization"] = "Bearer " + accessTokenValue; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } if (additionalMetadata !== undefined) { - formParams.set('additionalMetadata', additionalMetadata as any); + localVarFormParams.set('additionalMetadata', additionalMetadata as any); } if (file !== undefined) { - formParams.set('file', file as any); + localVarFormParams.set('file', file as any); } - headerParameter['Content-Type'] = 'application/x-www-form-urlencoded'; + localVarHeaderParameter['Content-Type'] = 'application/x-www-form-urlencoded'; - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); - requestOptions.body = formParams.toString(); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + localVarRequestOptions.body = localVarFormParams.toString(); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, } @@ -689,9 +690,9 @@ export const PetApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ addPet(body: Pet, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreator(configuration).addPet(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).addPet(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; } else { @@ -709,9 +710,9 @@ export const PetApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ deletePet(petId: number, apiKey?: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreator(configuration).deletePet(petId, apiKey, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).deletePet(petId, apiKey, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; } else { @@ -728,9 +729,9 @@ export const PetApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ findPetsByStatus(status: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise> { - const fetchArgs = PetApiFetchParamCreator(configuration).findPetsByStatus(status, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).findPetsByStatus(status, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); } else { @@ -747,9 +748,9 @@ export const PetApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ findPetsByTags(tags: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise> { - const fetchArgs = PetApiFetchParamCreator(configuration).findPetsByTags(tags, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).findPetsByTags(tags, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); } else { @@ -766,9 +767,9 @@ export const PetApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ getPetById(petId: number, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreator(configuration).getPetById(petId, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).getPetById(petId, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); } else { @@ -785,9 +786,9 @@ export const PetApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ updatePet(body: Pet, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreator(configuration).updatePet(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).updatePet(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; } else { @@ -806,9 +807,9 @@ export const PetApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ updatePetWithForm(petId: number, name?: string, status?: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreator(configuration).updatePetWithForm(petId, name, status, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).updatePetWithForm(petId, name, status, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; } else { @@ -827,9 +828,9 @@ export const PetApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreator(configuration).uploadFile(petId, additionalMetadata, file, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).uploadFile(petId, additionalMetadata, file, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); } else { @@ -1063,21 +1064,21 @@ export const StoreApiFetchParamCreator = function (configuration?: Configuration if (orderId === null || orderId === undefined) { throw new RequiredError('orderId','Required parameter orderId was null or undefined when calling deleteOrder.'); } - const path = `/store/order/{orderId}` + const localVarPath = `/store/order/{orderId}` .replace(`{${"orderId"}}`, encodeURIComponent(String(orderId))); - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'DELETE' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'DELETE' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, /** @@ -1087,28 +1088,28 @@ export const StoreApiFetchParamCreator = function (configuration?: Configuration * @throws {RequiredError} */ getInventory(options: any = {}): FetchArgs { - const path = `/store/inventory`; - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'GET' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarPath = `/store/inventory`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; // authentication api_key required if (configuration && configuration.apiKey) { - const apiKeyValue = typeof configuration.apiKey === 'function' + const localVarApiKeyValue = typeof configuration.apiKey === 'function' ? configuration.apiKey("api_key") : configuration.apiKey; - headerParameter["api_key"] = apiKeyValue; + localVarHeaderParameter["api_key"] = localVarApiKeyValue; } - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, /** @@ -1123,21 +1124,21 @@ export const StoreApiFetchParamCreator = function (configuration?: Configuration if (orderId === null || orderId === undefined) { throw new RequiredError('orderId','Required parameter orderId was null or undefined when calling getOrderById.'); } - const path = `/store/order/{orderId}` + const localVarPath = `/store/order/{orderId}` .replace(`{${"orderId"}}`, encodeURIComponent(String(orderId))); - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'GET' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, /** @@ -1152,23 +1153,23 @@ export const StoreApiFetchParamCreator = function (configuration?: Configuration if (body === null || body === undefined) { throw new RequiredError('body','Required parameter body was null or undefined when calling placeOrder.'); } - const path = `/store/order`; - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'POST' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarPath = `/store/order`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; - headerParameter['Content-Type'] = 'application/json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); - requestOptions.body = JSON.stringify(body || {}); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + localVarRequestOptions.body = JSON.stringify(body || {}); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, } @@ -1188,9 +1189,9 @@ export const StoreApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ deleteOrder(orderId: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreator(configuration).deleteOrder(orderId, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = StoreApiFetchParamCreator(configuration).deleteOrder(orderId, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; } else { @@ -1206,9 +1207,9 @@ export const StoreApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ getInventory(options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { - const fetchArgs = StoreApiFetchParamCreator(configuration).getInventory(options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = StoreApiFetchParamCreator(configuration).getInventory(options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); } else { @@ -1225,9 +1226,9 @@ export const StoreApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ getOrderById(orderId: number, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreator(configuration).getOrderById(orderId, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = StoreApiFetchParamCreator(configuration).getOrderById(orderId, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); } else { @@ -1244,9 +1245,9 @@ export const StoreApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ placeOrder(body: Order, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreator(configuration).placeOrder(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = StoreApiFetchParamCreator(configuration).placeOrder(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); } else { @@ -1380,23 +1381,23 @@ export const UserApiFetchParamCreator = function (configuration?: Configuration) if (body === null || body === undefined) { throw new RequiredError('body','Required parameter body was null or undefined when calling createUser.'); } - const path = `/user`; - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'POST' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarPath = `/user`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; - headerParameter['Content-Type'] = 'application/json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); - requestOptions.body = JSON.stringify(body || {}); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + localVarRequestOptions.body = JSON.stringify(body || {}); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, /** @@ -1411,23 +1412,23 @@ export const UserApiFetchParamCreator = function (configuration?: Configuration) if (body === null || body === undefined) { throw new RequiredError('body','Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } - const path = `/user/createWithArray`; - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'POST' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarPath = `/user/createWithArray`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; - headerParameter['Content-Type'] = 'application/json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); - requestOptions.body = JSON.stringify(body || {}); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + localVarRequestOptions.body = JSON.stringify(body || {}); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, /** @@ -1442,23 +1443,23 @@ export const UserApiFetchParamCreator = function (configuration?: Configuration) if (body === null || body === undefined) { throw new RequiredError('body','Required parameter body was null or undefined when calling createUsersWithListInput.'); } - const path = `/user/createWithList`; - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'POST' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarPath = `/user/createWithList`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; - headerParameter['Content-Type'] = 'application/json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); - requestOptions.body = JSON.stringify(body || {}); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + localVarRequestOptions.body = JSON.stringify(body || {}); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, /** @@ -1473,21 +1474,21 @@ export const UserApiFetchParamCreator = function (configuration?: Configuration) if (username === null || username === undefined) { throw new RequiredError('username','Required parameter username was null or undefined when calling deleteUser.'); } - const path = `/user/{username}` + const localVarPath = `/user/{username}` .replace(`{${"username"}}`, encodeURIComponent(String(username))); - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'DELETE' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'DELETE' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, /** @@ -1502,21 +1503,21 @@ export const UserApiFetchParamCreator = function (configuration?: Configuration) if (username === null || username === undefined) { throw new RequiredError('username','Required parameter username was null or undefined when calling getUserByName.'); } - const path = `/user/{username}` + const localVarPath = `/user/{username}` .replace(`{${"username"}}`, encodeURIComponent(String(username))); - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'GET' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, /** @@ -1536,28 +1537,28 @@ export const UserApiFetchParamCreator = function (configuration?: Configuration) if (password === null || password === undefined) { throw new RequiredError('password','Required parameter password was null or undefined when calling loginUser.'); } - const path = `/user/login`; - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'GET' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarPath = `/user/login`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; if (username !== undefined) { - queryParameter['username'] = username; + localVarQueryParameter['username'] = username; } if (password !== undefined) { - queryParameter['password'] = password; + localVarQueryParameter['password'] = password; } - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, /** @@ -1567,20 +1568,20 @@ export const UserApiFetchParamCreator = function (configuration?: Configuration) * @throws {RequiredError} */ logoutUser(options: any = {}): FetchArgs { - const path = `/user/logout`; - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'GET' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarPath = `/user/logout`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, /** @@ -1600,24 +1601,24 @@ export const UserApiFetchParamCreator = function (configuration?: Configuration) if (body === null || body === undefined) { throw new RequiredError('body','Required parameter body was null or undefined when calling updateUser.'); } - const path = `/user/{username}` + const localVarPath = `/user/{username}` .replace(`{${"username"}}`, encodeURIComponent(String(username))); - const urlObj = url.parse(path, true); - const requestOptions = Object.assign({ method: 'PUT' }, options); - const headerParameter = {} as any; - const queryParameter = {} as any; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'PUT' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; - headerParameter['Content-Type'] = 'application/json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; - urlObj.query = Object.assign({}, urlObj.query, queryParameter, options.query); + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 - delete urlObj.search; - requestOptions.headers = Object.assign({}, headerParameter, options.headers); - requestOptions.body = JSON.stringify(body || {}); + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + localVarRequestOptions.body = JSON.stringify(body || {}); return { - url: url.format(urlObj), - options: requestOptions, + url: url.format(localVarUrlObj), + options: localVarRequestOptions, }; }, } @@ -1637,9 +1638,9 @@ export const UserApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ createUser(body: User, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreator(configuration).createUser(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUser(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; } else { @@ -1656,9 +1657,9 @@ export const UserApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ createUsersWithArrayInput(body: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreator(configuration).createUsersWithArrayInput(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUsersWithArrayInput(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; } else { @@ -1675,9 +1676,9 @@ export const UserApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ createUsersWithListInput(body: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreator(configuration).createUsersWithListInput(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUsersWithListInput(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; } else { @@ -1694,9 +1695,9 @@ export const UserApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ deleteUser(username: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreator(configuration).deleteUser(username, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).deleteUser(username, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; } else { @@ -1713,9 +1714,9 @@ export const UserApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ getUserByName(username: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreator(configuration).getUserByName(username, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).getUserByName(username, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); } else { @@ -1733,9 +1734,9 @@ export const UserApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ loginUser(username: string, password: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreator(configuration).loginUser(username, password, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).loginUser(username, password, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); } else { @@ -1751,9 +1752,9 @@ export const UserApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ logoutUser(options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreator(configuration).logoutUser(options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).logoutUser(options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; } else { @@ -1771,9 +1772,9 @@ export const UserApiFp = function(configuration?: Configuration) { * @throws {RequiredError} */ updateUser(username: string, body: User, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreator(configuration).updateUser(username, body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { - return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).updateUser(username, body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; } else { diff --git a/samples/client/petstore/typescript-fetch/builds/default/custom.d.ts b/samples/client/petstore/typescript-fetch/builds/default/custom.d.ts new file mode 100644 index 00000000000..02f969575e3 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/default/custom.d.ts @@ -0,0 +1 @@ +declare module 'portable-fetch'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts index 16f039fab86..524623e31c8 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts @@ -1,3 +1,4 @@ +/// // tslint:disable /** * Swagger Petstore @@ -13,7 +14,7 @@ import * as url from "url"; -import * as isomorphicFetch from "isomorphic-fetch"; +import * as portableFetch from "portable-fetch"; import { Configuration } from "./configuration"; const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); @@ -56,7 +57,7 @@ export interface FetchArgs { export class BaseAPI { protected configuration: Configuration; - constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected fetch: FetchAPI = isomorphicFetch) { + constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected fetch: FetchAPI = portableFetch) { if (configuration) { this.configuration = configuration; this.basePath = configuration.basePath || this.basePath; @@ -690,7 +691,7 @@ export const PetApiFp = function(configuration?: Configuration) { */ addPet(body: Pet, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = PetApiFetchParamCreator(configuration).addPet(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -710,7 +711,7 @@ export const PetApiFp = function(configuration?: Configuration) { */ deletePet(petId: number, apiKey?: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = PetApiFetchParamCreator(configuration).deletePet(petId, apiKey, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -729,7 +730,7 @@ export const PetApiFp = function(configuration?: Configuration) { */ findPetsByStatus(status: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise> { const localVarFetchArgs = PetApiFetchParamCreator(configuration).findPetsByStatus(status, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -748,7 +749,7 @@ export const PetApiFp = function(configuration?: Configuration) { */ findPetsByTags(tags: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise> { const localVarFetchArgs = PetApiFetchParamCreator(configuration).findPetsByTags(tags, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -767,7 +768,7 @@ export const PetApiFp = function(configuration?: Configuration) { */ getPetById(petId: number, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = PetApiFetchParamCreator(configuration).getPetById(petId, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -786,7 +787,7 @@ export const PetApiFp = function(configuration?: Configuration) { */ updatePet(body: Pet, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = PetApiFetchParamCreator(configuration).updatePet(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -807,7 +808,7 @@ export const PetApiFp = function(configuration?: Configuration) { */ updatePetWithForm(petId: number, name?: string, status?: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = PetApiFetchParamCreator(configuration).updatePetWithForm(petId, name, status, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -828,7 +829,7 @@ export const PetApiFp = function(configuration?: Configuration) { */ uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = PetApiFetchParamCreator(configuration).uploadFile(petId, additionalMetadata, file, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -1189,7 +1190,7 @@ export const StoreApiFp = function(configuration?: Configuration) { */ deleteOrder(orderId: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = StoreApiFetchParamCreator(configuration).deleteOrder(orderId, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -1207,7 +1208,7 @@ export const StoreApiFp = function(configuration?: Configuration) { */ getInventory(options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { const localVarFetchArgs = StoreApiFetchParamCreator(configuration).getInventory(options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -1226,7 +1227,7 @@ export const StoreApiFp = function(configuration?: Configuration) { */ getOrderById(orderId: number, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = StoreApiFetchParamCreator(configuration).getOrderById(orderId, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -1245,7 +1246,7 @@ export const StoreApiFp = function(configuration?: Configuration) { */ placeOrder(body: Order, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = StoreApiFetchParamCreator(configuration).placeOrder(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -1638,7 +1639,7 @@ export const UserApiFp = function(configuration?: Configuration) { */ createUser(body: User, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUser(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -1657,7 +1658,7 @@ export const UserApiFp = function(configuration?: Configuration) { */ createUsersWithArrayInput(body: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUsersWithArrayInput(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -1676,7 +1677,7 @@ export const UserApiFp = function(configuration?: Configuration) { */ createUsersWithListInput(body: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUsersWithListInput(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -1695,7 +1696,7 @@ export const UserApiFp = function(configuration?: Configuration) { */ deleteUser(username: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = UserApiFetchParamCreator(configuration).deleteUser(username, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -1714,7 +1715,7 @@ export const UserApiFp = function(configuration?: Configuration) { */ getUserByName(username: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = UserApiFetchParamCreator(configuration).getUserByName(username, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -1734,7 +1735,7 @@ export const UserApiFp = function(configuration?: Configuration) { */ loginUser(username: string, password: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = UserApiFetchParamCreator(configuration).loginUser(username, password, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -1752,7 +1753,7 @@ export const UserApiFp = function(configuration?: Configuration) { */ logoutUser(options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = UserApiFetchParamCreator(configuration).logoutUser(options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -1772,7 +1773,7 @@ export const UserApiFp = function(configuration?: Configuration) { */ updateUser(username: string, body: User, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = UserApiFetchParamCreator(configuration).updateUser(username, body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/custom.d.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/custom.d.ts new file mode 100644 index 00000000000..02f969575e3 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/custom.d.ts @@ -0,0 +1 @@ +declare module 'portable-fetch'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/package.json b/samples/client/petstore/typescript-fetch/builds/es6-target/package.json index d7f632a76d4..5fd44fc4e7d 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/package.json +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/package.json @@ -17,7 +17,7 @@ "postinstall": "npm run build" }, "dependencies": { - "isomorphic-fetch": "^2.2.1" + "portable-fetch": "^3.0.0" }, "devDependencies": { "@types/isomorphic-fetch": "0.0.34", diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts index 16f039fab86..524623e31c8 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts @@ -1,3 +1,4 @@ +/// // tslint:disable /** * Swagger Petstore @@ -13,7 +14,7 @@ import * as url from "url"; -import * as isomorphicFetch from "isomorphic-fetch"; +import * as portableFetch from "portable-fetch"; import { Configuration } from "./configuration"; const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); @@ -56,7 +57,7 @@ export interface FetchArgs { export class BaseAPI { protected configuration: Configuration; - constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected fetch: FetchAPI = isomorphicFetch) { + constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected fetch: FetchAPI = portableFetch) { if (configuration) { this.configuration = configuration; this.basePath = configuration.basePath || this.basePath; @@ -690,7 +691,7 @@ export const PetApiFp = function(configuration?: Configuration) { */ addPet(body: Pet, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = PetApiFetchParamCreator(configuration).addPet(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -710,7 +711,7 @@ export const PetApiFp = function(configuration?: Configuration) { */ deletePet(petId: number, apiKey?: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = PetApiFetchParamCreator(configuration).deletePet(petId, apiKey, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -729,7 +730,7 @@ export const PetApiFp = function(configuration?: Configuration) { */ findPetsByStatus(status: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise> { const localVarFetchArgs = PetApiFetchParamCreator(configuration).findPetsByStatus(status, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -748,7 +749,7 @@ export const PetApiFp = function(configuration?: Configuration) { */ findPetsByTags(tags: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise> { const localVarFetchArgs = PetApiFetchParamCreator(configuration).findPetsByTags(tags, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -767,7 +768,7 @@ export const PetApiFp = function(configuration?: Configuration) { */ getPetById(petId: number, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = PetApiFetchParamCreator(configuration).getPetById(petId, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -786,7 +787,7 @@ export const PetApiFp = function(configuration?: Configuration) { */ updatePet(body: Pet, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = PetApiFetchParamCreator(configuration).updatePet(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -807,7 +808,7 @@ export const PetApiFp = function(configuration?: Configuration) { */ updatePetWithForm(petId: number, name?: string, status?: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = PetApiFetchParamCreator(configuration).updatePetWithForm(petId, name, status, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -828,7 +829,7 @@ export const PetApiFp = function(configuration?: Configuration) { */ uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = PetApiFetchParamCreator(configuration).uploadFile(petId, additionalMetadata, file, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -1189,7 +1190,7 @@ export const StoreApiFp = function(configuration?: Configuration) { */ deleteOrder(orderId: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = StoreApiFetchParamCreator(configuration).deleteOrder(orderId, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -1207,7 +1208,7 @@ export const StoreApiFp = function(configuration?: Configuration) { */ getInventory(options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { const localVarFetchArgs = StoreApiFetchParamCreator(configuration).getInventory(options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -1226,7 +1227,7 @@ export const StoreApiFp = function(configuration?: Configuration) { */ getOrderById(orderId: number, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = StoreApiFetchParamCreator(configuration).getOrderById(orderId, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -1245,7 +1246,7 @@ export const StoreApiFp = function(configuration?: Configuration) { */ placeOrder(body: Order, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = StoreApiFetchParamCreator(configuration).placeOrder(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -1638,7 +1639,7 @@ export const UserApiFp = function(configuration?: Configuration) { */ createUser(body: User, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUser(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -1657,7 +1658,7 @@ export const UserApiFp = function(configuration?: Configuration) { */ createUsersWithArrayInput(body: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUsersWithArrayInput(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -1676,7 +1677,7 @@ export const UserApiFp = function(configuration?: Configuration) { */ createUsersWithListInput(body: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUsersWithListInput(body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -1695,7 +1696,7 @@ export const UserApiFp = function(configuration?: Configuration) { */ deleteUser(username: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = UserApiFetchParamCreator(configuration).deleteUser(username, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -1714,7 +1715,7 @@ export const UserApiFp = function(configuration?: Configuration) { */ getUserByName(username: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = UserApiFetchParamCreator(configuration).getUserByName(username, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -1734,7 +1735,7 @@ export const UserApiFp = function(configuration?: Configuration) { */ loginUser(username: string, password: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = UserApiFetchParamCreator(configuration).loginUser(username, password, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json(); @@ -1752,7 +1753,7 @@ export const UserApiFp = function(configuration?: Configuration) { */ logoutUser(options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = UserApiFetchParamCreator(configuration).logoutUser(options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; @@ -1772,7 +1773,7 @@ export const UserApiFp = function(configuration?: Configuration) { */ updateUser(username: string, body: User, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = UserApiFetchParamCreator(configuration).updateUser(username, body, options); - return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response; diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/custom.d.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/custom.d.ts new file mode 100644 index 00000000000..02f969575e3 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/custom.d.ts @@ -0,0 +1 @@ +declare module 'portable-fetch'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/package.json b/samples/client/petstore/typescript-fetch/builds/with-npm-version/package.json index d7f632a76d4..5fd44fc4e7d 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/package.json +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/package.json @@ -17,7 +17,7 @@ "postinstall": "npm run build" }, "dependencies": { - "isomorphic-fetch": "^2.2.1" + "portable-fetch": "^3.0.0" }, "devDependencies": { "@types/isomorphic-fetch": "0.0.34", diff --git a/samples/client/petstore/typescript-node/default/api.ts b/samples/client/petstore/typescript-node/default/api.ts index 45fabd8e1d5..ed2fce03d5c 100644 --- a/samples/client/petstore/typescript-node/default/api.ts +++ b/samples/client/petstore/typescript-node/default/api.ts @@ -10,7 +10,7 @@ * Do not edit the class manually. */ -import request = require('request'); +import localVarRequest = require('request'); import http = require('http'); import Promise = require('bluebird'); @@ -407,8 +407,8 @@ export class User { let enumsMap = { - "Order.StatusEnum": Order.StatusEnum, - "Pet.StatusEnum": Pet.StatusEnum, + "Order.StatusEnum": Order.StatusEnum, + "Pet.StatusEnum": Pet.StatusEnum, } let typeMap = { @@ -424,13 +424,13 @@ export interface Authentication { /** * Apply authentication settings to header and query params. */ - applyToRequest(requestOptions: request.Options): void; + applyToRequest(requestOptions: localVarRequest.Options): void; } export class HttpBasicAuth implements Authentication { public username: string; public password: string; - applyToRequest(requestOptions: request.Options): void { + applyToRequest(requestOptions: localVarRequest.Options): void { requestOptions.auth = { username: this.username, password: this.password } @@ -443,7 +443,7 @@ export class ApiKeyAuth implements Authentication { constructor(private location: string, private paramName: string) { } - applyToRequest(requestOptions: request.Options): void { + applyToRequest(requestOptions: localVarRequest.Options): void { if (this.location == "query") { (requestOptions.qs)[this.paramName] = this.apiKey; } else if (this.location == "header" && requestOptions && requestOptions.headers) { @@ -455,7 +455,7 @@ export class ApiKeyAuth implements Authentication { export class OAuth implements Authentication { public accessToken: string; - applyToRequest(requestOptions: request.Options): void { + applyToRequest(requestOptions: localVarRequest.Options): void { if (requestOptions && requestOptions.headers) { requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; } @@ -465,7 +465,7 @@ export class OAuth implements Authentication { export class VoidAuth implements Authentication { public username: string; public password: string; - applyToRequest(_: request.Options): void { + applyToRequest(_: localVarRequest.Options): void { // Do nothing } } @@ -528,9 +528,9 @@ export class PetApi { */ public addPet (body: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { @@ -538,35 +538,35 @@ export class PetApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Pet") }; - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -584,45 +584,45 @@ export class PetApi { public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: 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'] = ObjectSerializer.serialize(apiKey, "string"); + localVarHeaderParams['api_key'] = ObjectSerializer.serialize(apiKey, "string"); - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'DELETE', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -638,9 +638,9 @@ export class PetApi { */ public findPetsByStatus (status: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { const localVarPath = this.basePath + '/pet/findByStatus'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'status' is not null or undefined if (status === null || status === undefined) { @@ -648,39 +648,39 @@ export class PetApi { } if (status !== undefined) { - queryParameters['status'] = ObjectSerializer.serialize(status, "Array"); + localVarQueryParameters['status'] = ObjectSerializer.serialize(status, "Array"); } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: Array; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Array"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -696,9 +696,9 @@ export class PetApi { */ public findPetsByTags (tags: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { const localVarPath = this.basePath + '/pet/findByTags'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'tags' is not null or undefined if (tags === null || tags === undefined) { @@ -706,39 +706,39 @@ export class PetApi { } if (tags !== undefined) { - queryParameters['tags'] = ObjectSerializer.serialize(tags, "Array"); + localVarQueryParameters['tags'] = ObjectSerializer.serialize(tags, "Array"); } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: Array; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Array"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -755,9 +755,9 @@ export class PetApi { public getPetById (petId: number) : Promise<{ response: http.ClientResponse; body: Pet; }> { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -765,35 +765,35 @@ export class PetApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.api_key.applyToRequest(requestOptions); + this.authentications.api_key.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: Pet; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Pet"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -809,9 +809,9 @@ export class PetApi { */ public updatePet (body: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { @@ -819,35 +819,35 @@ export class PetApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'PUT', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Pet") }; - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -866,9 +866,9 @@ export class PetApi { public updatePetWithForm (petId: number, name?: string, status?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -876,42 +876,42 @@ export class PetApi { } - let useFormData = false; + let localVarUseFormData = false; if (name !== undefined) { - formParams['name'] = ObjectSerializer.serialize(name, "string"); + localVarFormParams['name'] = ObjectSerializer.serialize(name, "string"); } if (status !== undefined) { - formParams['status'] = ObjectSerializer.serialize(status, "string"); + localVarFormParams['status'] = ObjectSerializer.serialize(status, "string"); } - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -930,9 +930,9 @@ export class PetApi { public uploadFile (petId: number, additionalMetadata?: string, file?: Buffer) : Promise<{ response: http.ClientResponse; body: ApiResponse; }> { const localVarPath = this.basePath + '/pet/{petId}/uploadImage' .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -940,44 +940,44 @@ export class PetApi { } - let useFormData = false; + let localVarUseFormData = false; if (additionalMetadata !== undefined) { - formParams['additionalMetadata'] = ObjectSerializer.serialize(additionalMetadata, "string"); + localVarFormParams['additionalMetadata'] = ObjectSerializer.serialize(additionalMetadata, "string"); } if (file !== undefined) { - formParams['file'] = file; + localVarFormParams['file'] = file; } - useFormData = true; + localVarUseFormData = true; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: ApiResponse; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "ApiResponse"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1046,9 +1046,9 @@ export class StoreApi { public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -1056,32 +1056,32 @@ export class StoreApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'DELETE', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1096,40 +1096,40 @@ export class StoreApi { */ public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { const localVarPath = this.basePath + '/store/inventory'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.api_key.applyToRequest(requestOptions); + this.authentications.api_key.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "{ [key: string]: number; }"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1146,9 +1146,9 @@ export class StoreApi { public getOrderById (orderId: number) : Promise<{ response: http.ClientResponse; body: Order; }> { const localVarPath = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -1156,33 +1156,33 @@ export class StoreApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: Order; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Order"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1198,9 +1198,9 @@ export class StoreApi { */ public placeOrder (body: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { const localVarPath = this.basePath + '/store/order'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { @@ -1208,34 +1208,34 @@ export class StoreApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Order") }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: Order; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Order"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1303,9 +1303,9 @@ export class UserApi { */ public createUser (body: User) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { @@ -1313,33 +1313,33 @@ export class UserApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "User") }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1355,9 +1355,9 @@ export class UserApi { */ public createUsersWithArrayInput (body: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/createWithArray'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { @@ -1365,33 +1365,33 @@ export class UserApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Array") }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1407,9 +1407,9 @@ export class UserApi { */ public createUsersWithListInput (body: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/createWithList'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { @@ -1417,33 +1417,33 @@ export class UserApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Array") }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1460,9 +1460,9 @@ export class UserApi { public deleteUser (username: string) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', encodeURIComponent(String(username))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -1470,32 +1470,32 @@ export class UserApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'DELETE', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1512,9 +1512,9 @@ export class UserApi { public getUserByName (username: string) : Promise<{ response: http.ClientResponse; body: User; }> { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', encodeURIComponent(String(username))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -1522,33 +1522,33 @@ export class UserApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: User; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "User"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1565,9 +1565,9 @@ export class UserApi { */ public loginUser (username: string, password: string) : Promise<{ response: http.ClientResponse; body: string; }> { const localVarPath = this.basePath + '/user/login'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -1580,41 +1580,41 @@ export class UserApi { } if (username !== undefined) { - queryParameters['username'] = ObjectSerializer.serialize(username, "string"); + localVarQueryParameters['username'] = ObjectSerializer.serialize(username, "string"); } if (password !== undefined) { - queryParameters['password'] = ObjectSerializer.serialize(password, "string"); + localVarQueryParameters['password'] = ObjectSerializer.serialize(password, "string"); } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: string; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "string"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1629,37 +1629,37 @@ export class UserApi { */ public logoutUser () : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/logout'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1677,9 +1677,9 @@ export class UserApi { public updateUser (username: string, body: User) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', encodeURIComponent(String(username))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -1692,33 +1692,33 @@ export class UserApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'PUT', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "User") }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); diff --git a/samples/client/petstore/typescript-node/npm/api.d.ts b/samples/client/petstore/typescript-node/npm/api.d.ts index 9c5d19062ec..bb0e4f5d2ea 100644 --- a/samples/client/petstore/typescript-node/npm/api.d.ts +++ b/samples/client/petstore/typescript-node/npm/api.d.ts @@ -1,6 +1,22 @@ -import request = require('request'); +import localVarRequest = require('request'); import http = require('http'); import Promise = require('bluebird'); +export declare class ApiResponse { + 'code': number; + 'type': string; + 'message': string; + static discriminator: any; + static attributeTypeMap: Array<{ + name: string; + baseName: string; + type: string; + }>; + static getAttributeTypeMap(): { + name: string; + baseName: string; + type: string; + }[]; +} export declare class Category { 'id': number; 'name': string; @@ -105,34 +121,34 @@ export declare class User { }[]; } export interface Authentication { - applyToRequest(requestOptions: request.Options): void; + applyToRequest(requestOptions: localVarRequest.Options): void; } export declare class HttpBasicAuth implements Authentication { username: string; password: string; - applyToRequest(requestOptions: request.Options): void; + applyToRequest(requestOptions: localVarRequest.Options): void; } export declare class ApiKeyAuth implements Authentication { private location; private paramName; apiKey: string; constructor(location: string, paramName: string); - applyToRequest(requestOptions: request.Options): void; + applyToRequest(requestOptions: localVarRequest.Options): void; } export declare class OAuth implements Authentication { accessToken: string; - applyToRequest(requestOptions: request.Options): void; + applyToRequest(requestOptions: localVarRequest.Options): void; } export declare class VoidAuth implements Authentication { username: string; password: string; - applyToRequest(_: request.Options): void; + applyToRequest(_: localVarRequest.Options): void; } export declare enum PetApiApiKeys { api_key = 0, } export declare class PetApi { - protected basePath: string; + protected _basePath: string; protected defaultHeaders: any; protected _useQuerystring: boolean; protected authentications: { @@ -142,10 +158,11 @@ export declare class PetApi { }; constructor(basePath?: string); useQuerystring: boolean; + basePath: string; + setDefaultAuthentication(auth: Authentication): void; setApiKey(key: PetApiApiKeys, value: string): void; accessToken: string; - private extendObj(objA, objB); - addPet(body?: Pet): Promise<{ + addPet(body: Pet): Promise<{ response: http.ClientResponse; body?: any; }>; @@ -153,11 +170,11 @@ export declare class PetApi { response: http.ClientResponse; body?: any; }>; - findPetsByStatus(status?: Array): Promise<{ + findPetsByStatus(status: Array): Promise<{ response: http.ClientResponse; body: Array; }>; - findPetsByTags(tags?: Array): Promise<{ + findPetsByTags(tags: Array): Promise<{ response: http.ClientResponse; body: Array; }>; @@ -165,24 +182,24 @@ export declare class PetApi { response: http.ClientResponse; body: Pet; }>; - updatePet(body?: Pet): Promise<{ + updatePet(body: Pet): Promise<{ response: http.ClientResponse; body?: any; }>; - updatePetWithForm(petId: string, name?: string, status?: string): Promise<{ + updatePetWithForm(petId: number, name?: string, status?: string): Promise<{ response: http.ClientResponse; body?: any; }>; - uploadFile(petId: number, additionalMetadata?: string, file?: any): Promise<{ + uploadFile(petId: number, additionalMetadata?: string, file?: Buffer): Promise<{ response: http.ClientResponse; - body?: any; + body: ApiResponse; }>; } export declare enum StoreApiApiKeys { api_key = 0, } export declare class StoreApi { - protected basePath: string; + protected _basePath: string; protected defaultHeaders: any; protected _useQuerystring: boolean; protected authentications: { @@ -192,9 +209,10 @@ export declare class StoreApi { }; constructor(basePath?: string); useQuerystring: boolean; + basePath: string; + setDefaultAuthentication(auth: Authentication): void; setApiKey(key: StoreApiApiKeys, value: string): void; accessToken: string; - private extendObj(objA, objB); deleteOrder(orderId: string): Promise<{ response: http.ClientResponse; body?: any; @@ -205,11 +223,11 @@ export declare class StoreApi { [key: string]: number; }; }>; - getOrderById(orderId: string): Promise<{ + getOrderById(orderId: number): Promise<{ response: http.ClientResponse; body: Order; }>; - placeOrder(body?: Order): Promise<{ + placeOrder(body: Order): Promise<{ response: http.ClientResponse; body: Order; }>; @@ -218,7 +236,7 @@ export declare enum UserApiApiKeys { api_key = 0, } export declare class UserApi { - protected basePath: string; + protected _basePath: string; protected defaultHeaders: any; protected _useQuerystring: boolean; protected authentications: { @@ -228,18 +246,19 @@ export declare class UserApi { }; constructor(basePath?: string); useQuerystring: boolean; + basePath: string; + setDefaultAuthentication(auth: Authentication): void; setApiKey(key: UserApiApiKeys, value: string): void; accessToken: string; - private extendObj(objA, objB); - createUser(body?: User): Promise<{ + createUser(body: User): Promise<{ response: http.ClientResponse; body?: any; }>; - createUsersWithArrayInput(body?: Array): Promise<{ + createUsersWithArrayInput(body: Array): Promise<{ response: http.ClientResponse; body?: any; }>; - createUsersWithListInput(body?: Array): Promise<{ + createUsersWithListInput(body: Array): Promise<{ response: http.ClientResponse; body?: any; }>; @@ -251,7 +270,7 @@ export declare class UserApi { response: http.ClientResponse; body: User; }>; - loginUser(username?: string, password?: string): Promise<{ + loginUser(username: string, password: string): Promise<{ response: http.ClientResponse; body: string; }>; @@ -259,7 +278,7 @@ export declare class UserApi { response: http.ClientResponse; body?: any; }>; - updateUser(username: string, body?: User): Promise<{ + updateUser(username: string, body: User): Promise<{ response: http.ClientResponse; body?: any; }>; diff --git a/samples/client/petstore/typescript-node/npm/api.js b/samples/client/petstore/typescript-node/npm/api.js index ea27b029f2e..fd332714097 100644 --- a/samples/client/petstore/typescript-node/npm/api.js +++ b/samples/client/petstore/typescript-node/npm/api.js @@ -1,15 +1,17 @@ "use strict"; -var request = require('request'); +var localVarRequest = require('request'); var Promise = require('bluebird'); var defaultBasePath = 'http://petstore.swagger.io/v2'; -var primitives = ["string", +var primitives = [ + "string", "boolean", "double", "integer", "long", "float", "number", - "any"]; + "any" +]; var ObjectSerializer = (function () { function ObjectSerializer() { } @@ -119,6 +121,32 @@ var ObjectSerializer = (function () { }; return ObjectSerializer; }()); +var ApiResponse = (function () { + function ApiResponse() { + } + ApiResponse.getAttributeTypeMap = function () { + return ApiResponse.attributeTypeMap; + }; + ApiResponse.discriminator = undefined; + ApiResponse.attributeTypeMap = [ + { + "name": "code", + "baseName": "code", + "type": "number" + }, + { + "name": "type", + "baseName": "type", + "type": "string" + }, + { + "name": "message", + "baseName": "message", + "type": "string" + }]; + return ApiResponse; +}()); +exports.ApiResponse = ApiResponse; var Category = (function () { function Category() { } @@ -317,6 +345,7 @@ var enumsMap = { "Pet.StatusEnum": Pet.StatusEnum, }; var typeMap = { + "ApiResponse": ApiResponse, "Category": Category, "Order": Order, "Pet": Pet, @@ -375,7 +404,7 @@ exports.VoidAuth = VoidAuth; var PetApiApiKeys = exports.PetApiApiKeys; var PetApi = (function () { function PetApi(basePathOrUsername, password, basePath) { - this.basePath = defaultBasePath; + this._basePath = defaultBasePath; this.defaultHeaders = {}; this._useQuerystring = false; this.authentications = { @@ -401,6 +430,19 @@ var PetApi = (function () { enumerable: true, configurable: true }); + Object.defineProperty(PetApi.prototype, "basePath", { + get: function () { + return this._basePath; + }, + set: function (basePath) { + this._basePath = basePath; + }, + enumerable: true, + configurable: true + }); + PetApi.prototype.setDefaultAuthentication = function (auth) { + this.authentications.default = auth; + }; PetApi.prototype.setApiKey = function (key, value) { this.authentications[PetApiApiKeys[key]].apiKey = value; }; @@ -411,46 +453,41 @@ var PetApi = (function () { 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 requestOptions = { + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling addPet.'); + } + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Pet") }; - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -462,40 +499,40 @@ var PetApi = (function () { }; 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 = {}; + .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } - headerParams['api_key'] = ObjectSerializer.serialize(apiKey, "string"); - var useFormData = false; - var requestOptions = { + localVarHeaderParams['api_key'] = ObjectSerializer.serialize(apiKey, "string"); + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'DELETE', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -507,39 +544,42 @@ var PetApi = (function () { }; 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'] = ObjectSerializer.serialize(status, "Array<string>"); + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; + if (status === null || status === undefined) { + throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } - var useFormData = false; - var requestOptions = { + if (status !== undefined) { + localVarQueryParameters['status'] = ObjectSerializer.serialize(status, "Array"); + } + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "Array<Pet>"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "Array"); + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -551,39 +591,42 @@ var PetApi = (function () { }; 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'] = ObjectSerializer.serialize(tags, "Array<string>"); + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; + if (tags === null || tags === undefined) { + throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } - var useFormData = false; - var requestOptions = { + if (tags !== undefined) { + localVarQueryParameters['tags'] = ObjectSerializer.serialize(tags, "Array"); + } + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "Array<Pet>"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "Array"); + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -595,41 +638,40 @@ var PetApi = (function () { }; 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 = {}; + .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } - var useFormData = false; - var requestOptions = { + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.api_key.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.api_key.applyToRequest(localVarRequestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Pet"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -641,36 +683,39 @@ var PetApi = (function () { }; PetApi.prototype.updatePet = function (body) { var localVarPath = this.basePath + '/pet'; - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - var useFormData = false; - var requestOptions = { + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updatePet.'); + } + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'PUT', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Pet") }; - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -682,45 +727,45 @@ var PetApi = (function () { }; 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 = {}; + .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } - var useFormData = false; + var localVarUseFormData = false; if (name !== undefined) { - formParams['name'] = ObjectSerializer.serialize(name, "string"); + localVarFormParams['name'] = ObjectSerializer.serialize(name, "string"); } if (status !== undefined) { - formParams['status'] = ObjectSerializer.serialize(status, "string"); + localVarFormParams['status'] = ObjectSerializer.serialize(status, "string"); } - var requestOptions = { + var localVarRequestOptions = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -732,46 +777,47 @@ var PetApi = (function () { }; 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 = {}; + .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } - var useFormData = false; + var localVarUseFormData = false; if (additionalMetadata !== undefined) { - formParams['additionalMetadata'] = ObjectSerializer.serialize(additionalMetadata, "string"); + localVarFormParams['additionalMetadata'] = ObjectSerializer.serialize(additionalMetadata, "string"); } if (file !== undefined) { - formParams['file'] = file; + localVarFormParams['file'] = file; } - useFormData = true; - var requestOptions = { + localVarUseFormData = true; + var localVarRequestOptions = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "ApiResponse"); + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -790,7 +836,7 @@ exports.PetApi = PetApi; var StoreApiApiKeys = exports.StoreApiApiKeys; var StoreApi = (function () { function StoreApi(basePathOrUsername, password, basePath) { - this.basePath = defaultBasePath; + this._basePath = defaultBasePath; this.defaultHeaders = {}; this._useQuerystring = false; this.authentications = { @@ -816,6 +862,19 @@ var StoreApi = (function () { enumerable: true, configurable: true }); + Object.defineProperty(StoreApi.prototype, "basePath", { + get: function () { + return this._basePath; + }, + set: function (basePath) { + this._basePath = basePath; + }, + enumerable: true, + configurable: true + }); + StoreApi.prototype.setDefaultAuthentication = function (auth) { + this.authentications.default = auth; + }; StoreApi.prototype.setApiKey = function (key, value) { this.authentications[StoreApiApiKeys[key]].apiKey = value; }; @@ -826,48 +885,40 @@ var StoreApi = (function () { 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 = {}; + .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } - var useFormData = false; - var requestOptions = { + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'DELETE', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -879,36 +930,36 @@ var StoreApi = (function () { }; StoreApi.prototype.getInventory = function () { var localVarPath = this.basePath + '/store/inventory'; - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - var useFormData = false; - var requestOptions = { + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.api_key.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.api_key.applyToRequest(localVarRequestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "{ [key: string]: number; }"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -920,39 +971,39 @@ var StoreApi = (function () { }; 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 = {}; + .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } - var useFormData = false; - var requestOptions = { + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Order"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -964,36 +1015,39 @@ var StoreApi = (function () { }; 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 requestOptions = { + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling placeOrder.'); + } + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Order") }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Order"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -1012,7 +1066,7 @@ exports.StoreApi = StoreApi; var UserApiApiKeys = exports.UserApiApiKeys; var UserApi = (function () { function UserApi(basePathOrUsername, password, basePath) { - this.basePath = defaultBasePath; + this._basePath = defaultBasePath; this.defaultHeaders = {}; this._useQuerystring = false; this.authentications = { @@ -1038,6 +1092,19 @@ var UserApi = (function () { enumerable: true, configurable: true }); + Object.defineProperty(UserApi.prototype, "basePath", { + get: function () { + return this._basePath; + }, + set: function (basePath) { + this._basePath = basePath; + }, + enumerable: true, + configurable: true + }); + UserApi.prototype.setDefaultAuthentication = function (auth) { + this.authentications.default = auth; + }; UserApi.prototype.setApiKey = function (key, value) { this.authentications[UserApiApiKeys[key]].apiKey = value; }; @@ -1048,45 +1115,40 @@ var UserApi = (function () { 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 requestOptions = { + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUser.'); + } + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "User") }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -1098,35 +1160,38 @@ var UserApi = (function () { }; 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 requestOptions = { + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); + } + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, - body: ObjectSerializer.serialize(body, "Array<User>") + body: ObjectSerializer.serialize(body, "Array") }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -1138,35 +1203,38 @@ var UserApi = (function () { }; 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 requestOptions = { + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); + } + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, - body: ObjectSerializer.serialize(body, "Array<User>") + body: ObjectSerializer.serialize(body, "Array") }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -1178,38 +1246,38 @@ var UserApi = (function () { }; 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 = {}; + .replace('{' + 'username' + '}', encodeURIComponent(String(username))); + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } - var useFormData = false; - var requestOptions = { + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'DELETE', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -1221,39 +1289,39 @@ var UserApi = (function () { }; 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 = {}; + .replace('{' + 'username' + '}', encodeURIComponent(String(username))); + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } - var useFormData = false; - var requestOptions = { + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "User"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -1265,41 +1333,47 @@ var UserApi = (function () { }; UserApi.prototype.loginUser = function (username, password) { var localVarPath = this.basePath + '/user/login'; - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling loginUser.'); + } + if (password === null || password === undefined) { + throw new Error('Required parameter password was null or undefined when calling loginUser.'); + } if (username !== undefined) { - queryParameters['username'] = ObjectSerializer.serialize(username, "string"); + localVarQueryParameters['username'] = ObjectSerializer.serialize(username, "string"); } if (password !== undefined) { - queryParameters['password'] = ObjectSerializer.serialize(password, "string"); + localVarQueryParameters['password'] = ObjectSerializer.serialize(password, "string"); } - var useFormData = false; - var requestOptions = { + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "string"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -1311,34 +1385,34 @@ var UserApi = (function () { }; UserApi.prototype.logoutUser = function () { var localVarPath = this.basePath + '/user/logout'; - var queryParameters = {}; - var headerParams = this.extendObj({}, this.defaultHeaders); - var formParams = {}; - var useFormData = false; - var requestOptions = { + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { @@ -1350,39 +1424,42 @@ var UserApi = (function () { }; 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 = {}; + .replace('{' + 'username' + '}', encodeURIComponent(String(username))); + var localVarQueryParameters = {}; + var localVarHeaderParams = Object.assign({}, this.defaultHeaders); + var localVarFormParams = {}; if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } - var useFormData = false; - var requestOptions = { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updateUser.'); + } + var localVarUseFormData = false; + var localVarRequestOptions = { method: 'PUT', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "User") }; - this.authentications.default.applyToRequest(requestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - requestOptions.formData = formParams; + this.authentications.default.applyToRequest(localVarRequestOptions); + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + localVarRequestOptions.formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise(function (resolve, reject) { - request(requestOptions, function (error, response, body) { + localVarRequest(localVarRequestOptions, function (error, response, body) { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { diff --git a/samples/client/petstore/typescript-node/npm/api.js.map b/samples/client/petstore/typescript-node/npm/api.js.map index 92891a66be6..a8a6ef9ab79 100644 --- a/samples/client/petstore/typescript-node/npm/api.js.map +++ b/samples/client/petstore/typescript-node/npm/api.js.map @@ -1 +1 @@ -{"version":3,"file":"api.js","sourceRoot":"","sources":["api.ts"],"names":[],"mappings":";AAYA,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AAEpC,IAAO,OAAO,WAAW,UAAU,CAAC,CAAC;AAErC,IAAI,eAAe,GAAG,+BAA+B,CAAC;AAOtD,IAAI,UAAU,GAAG,CAAC,QAAQ;IACV,SAAS;IACT,QAAQ;IACR,SAAS;IACT,MAAM;IACN,OAAO;IACP,QAAQ;IACR,KAAK,CAAC,CAAC;AAEtB;IAAA;IAuGD,CAAC;IArGe,gCAAe,GAA7B,UAA8B,IAAS,EAAE,YAAoB;QAC7D,EAAE,CAAC,CAAC,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC;YACvB,MAAM,CAAC,YAAY,CAAC;QACrB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,YAAY,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YAClE,MAAM,CAAC,YAAY,CAAC;QACrB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,YAAY,KAAK,MAAM,CAAC,CAAC,CAAC;YACpC,MAAM,CAAC,YAAY,CAAC;QACrB,CAAC;QAAC,IAAI,CAAC,CAAC;YACP,EAAE,CAAC,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;gBAC5B,MAAM,CAAC,YAAY,CAAC;YACrB,CAAC;YAED,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;gBAC5B,MAAM,CAAC,YAAY,CAAC;YACrB,CAAC;YAGD,IAAI,qBAAqB,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC,aAAa,CAAC;YAChE,EAAE,CAAC,CAAC,qBAAqB,IAAI,IAAI,CAAC,CAAC,CAAC;gBACnC,MAAM,CAAC,YAAY,CAAC;YACrB,CAAC;YAAC,IAAI,CAAC,CAAC;gBACP,EAAE,CAAC,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC;oBACjC,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;gBACpC,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACP,MAAM,CAAC,YAAY,CAAC;gBACrB,CAAC;YACF,CAAC;QACF,CAAC;IAED,CAAC;IAEa,0BAAS,GAAvB,UAAwB,IAAS,EAAE,IAAY;QAC/C,EAAE,CAAC,CAAC,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC;YACvB,MAAM,CAAC,IAAI,CAAC;QACb,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1D,MAAM,CAAC,IAAI,CAAC;QACb,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAChD,IAAI,OAAO,GAAW,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;YACjD,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YACnD,IAAI,eAAe,GAAG,EAAE,CAAC;YACzB,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC;gBACxB,IAAI,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;gBACvB,eAAe,CAAC,IAAI,CAAC,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;YACjE,CAAC;YACD,MAAM,CAAC,eAAe,CAAC;QACxB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC;YAC5B,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;QACxB,CAAC;QAAC,IAAI,CAAC,CAAC;YACP,EAAE,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBACpB,MAAM,CAAC,IAAI,CAAC;YACb,CAAC;YACD,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBACpB,MAAM,CAAC,IAAI,CAAC;YACb,CAAC;YAGD,IAAI,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,mBAAmB,EAAE,CAAC;YACzD,IAAI,QAAQ,GAAG,EAAE,CAAC;YAClB,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,cAAc,CAAC,CAAC,CAAC;gBAClC,IAAI,aAAa,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;gBAC1C,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,aAAa,CAAC,IAAI,CAAC,CAAC;YAC7G,CAAC;YACD,MAAM,CAAC,QAAQ,CAAC;QACjB,CAAC;IACD,CAAC;IAEY,4BAAW,GAAzB,UAA0B,IAAS,EAAE,IAAY;QAEhD,IAAI,GAAG,gBAAgB,CAAC,eAAe,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACpD,EAAE,CAAC,CAAC,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC;YACvB,MAAM,CAAC,IAAI,CAAC;QACb,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1D,MAAM,CAAC,IAAI,CAAC;QACb,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAChD,IAAI,OAAO,GAAW,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;YACjD,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YACnD,IAAI,eAAe,GAAG,EAAE,CAAC;YACzB,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC;gBACxB,IAAI,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;gBACvB,eAAe,CAAC,IAAI,CAAC,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;YACnE,CAAC;YACD,MAAM,CAAC,eAAe,CAAC;QACxB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC;YAC5B,MAAM,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;QACvB,CAAC;QAAC,IAAI,CAAC,CAAC;YACP,EAAE,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBACpB,MAAM,CAAC,IAAI,CAAC;YACb,CAAC;YAED,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBACpB,MAAM,CAAC,IAAI,CAAC;YACb,CAAC;YACD,IAAI,QAAQ,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;YACnC,IAAI,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,mBAAmB,EAAE,CAAC;YACzD,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,cAAc,CAAC,CAAC,CAAC;gBAClC,IAAI,aAAa,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;gBAC1C,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,EAAE,aAAa,CAAC,IAAI,CAAC,CAAC;YAC/G,CAAC;YACD,MAAM,CAAC,QAAQ,CAAC;QACjB,CAAC;IACF,CAAC;IACF,uBAAC;AAAD,CAAC,AAvGA,IAuGA;AAED;IAAA;IAqBA,CAAC;IAHO,4BAAmB,GAA1B;QACC,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CAAC;IAClC,CAAC;IAhBO,sBAAa,GAAG,SAAS,CAAC;IAE3B,yBAAgB,GAA0D;QAChF;YACC,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SAChB;QACD;YACC,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SAChB,CAAE,CAAC;IAKN,eAAC;AAAD,CAAC,AArBD,IAqBC;AArBY,gBAAQ,WAqBpB,CAAA;AAED;IAAA;IAgDA,CAAC;IAHO,yBAAmB,GAA1B;QACC,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAAC;IAC/B,CAAC;IApCO,mBAAa,GAAG,SAAS,CAAC;IAE3B,sBAAgB,GAA0D;QAChF;YACC,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SAChB;QACD;YACC,MAAM,EAAE,OAAO;YACf,UAAU,EAAE,OAAO;YACnB,MAAM,EAAE,QAAQ;SAChB;QACD;YACC,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,QAAQ;SAChB;QACD;YACC,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,MAAM;SACd;QACD;YACC,MAAM,EAAE,QAAQ;YAChB,UAAU,EAAE,QAAQ;YACpB,MAAM,EAAE,kBAAkB;SAC1B;QACD;YACC,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,SAAS;SACjB,CAAE,CAAC;IAKN,YAAC;AAAD,CAAC,AAhDD,IAgDC;AAhDY,aAAK,QAgDjB,CAAA;AAED,IAAiB,KAAK,CAMrB;AAND,WAAiB,KAAK,EAAC,CAAC;IACpB,WAAY,UAAU;QAClB,kCAAe,QAAQ,YAAA,CAAA;QACvB,oCAAiB,UAAU,cAAA,CAAA;QAC3B,qCAAkB,WAAW,eAAA,CAAA;IACjC,CAAC,EAJW,gBAAU,KAAV,gBAAU,QAIrB;IAJD,IAAY,UAAU,GAAV,gBAIX,CAAA;AACL,CAAC,EANgB,KAAK,GAAL,aAAK,KAAL,aAAK,QAMrB;AACD;IAAA;IAgDA,CAAC;IAHO,uBAAmB,GAA1B;QACC,MAAM,CAAC,GAAG,CAAC,gBAAgB,CAAC;IAC7B,CAAC;IApCO,iBAAa,GAAG,SAAS,CAAC;IAE3B,oBAAgB,GAA0D;QAChF;YACC,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SAChB;QACD;YACC,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,UAAU;SAClB;QACD;YACC,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SAChB;QACD;YACC,MAAM,EAAE,WAAW;YACnB,UAAU,EAAE,WAAW;YACvB,MAAM,EAAE,eAAe;SACvB;QACD;YACC,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,YAAY;SACpB;QACD;YACC,MAAM,EAAE,QAAQ;YAChB,UAAU,EAAE,QAAQ;YACpB,MAAM,EAAE,gBAAgB;SACxB,CAAE,CAAC;IAKN,UAAC;AAAD,CAAC,AAhDD,IAgDC;AAhDY,WAAG,MAgDf,CAAA;AAED,IAAiB,GAAG,CAMnB;AAND,WAAiB,GAAG,EAAC,CAAC;IAClB,WAAY,UAAU;QAClB,qCAAkB,WAAW,eAAA,CAAA;QAC7B,mCAAgB,SAAS,aAAA,CAAA;QACzB,gCAAa,MAAM,UAAA,CAAA;IACvB,CAAC,EAJW,cAAU,KAAV,cAAU,QAIrB;IAJD,IAAY,UAAU,GAAV,cAIX,CAAA;AACL,CAAC,EANgB,GAAG,GAAH,WAAG,KAAH,WAAG,QAMnB;AACD;IAAA;IAqBA,CAAC;IAHO,uBAAmB,GAA1B;QACC,MAAM,CAAC,GAAG,CAAC,gBAAgB,CAAC;IAC7B,CAAC;IAhBO,iBAAa,GAAG,SAAS,CAAC;IAE3B,oBAAgB,GAA0D;QAChF;YACC,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SAChB;QACD;YACC,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SAChB,CAAE,CAAC;IAKN,UAAC;AAAD,CAAC,AArBD,IAqBC;AArBY,WAAG,MAqBf,CAAA;AAED;IAAA;IA4DA,CAAC;IAHO,wBAAmB,GAA1B;QACC,MAAM,CAAC,IAAI,CAAC,gBAAgB,CAAC;IAC9B,CAAC;IA9CO,kBAAa,GAAG,SAAS,CAAC;IAE3B,qBAAgB,GAA0D;QAChF;YACC,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SAChB;QACD;YACC,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,QAAQ;SAChB;QACD;YACC,MAAM,EAAE,WAAW;YACnB,UAAU,EAAE,WAAW;YACvB,MAAM,EAAE,QAAQ;SAChB;QACD;YACC,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,QAAQ;SAChB;QACD;YACC,MAAM,EAAE,OAAO;YACf,UAAU,EAAE,OAAO;YACnB,MAAM,EAAE,QAAQ;SAChB;QACD;YACC,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,QAAQ;SAChB;QACD;YACC,MAAM,EAAE,OAAO;YACf,UAAU,EAAE,OAAO;YACnB,MAAM,EAAE,QAAQ;SAChB;QACD;YACC,MAAM,EAAE,YAAY;YACpB,UAAU,EAAE,YAAY;YACxB,MAAM,EAAE,QAAQ;SAChB,CAAE,CAAC;IAKN,WAAC;AAAD,CAAC,AA5DD,IA4DC;AA5DY,YAAI,OA4DhB,CAAA;AAGD,IAAI,QAAQ,GAAG;IACd,kBAAkB,EAAE,KAAK,CAAC,UAAU;IACpC,gBAAgB,EAAE,GAAG,CAAC,UAAU;CAChC,CAAA;AAED,IAAI,OAAO,GAAG;IACb,UAAU,EAAE,QAAQ;IACpB,OAAO,EAAE,KAAK;IACd,KAAK,EAAE,GAAG;IACV,KAAK,EAAE,GAAG;IACV,MAAM,EAAE,IAAI;CACZ,CAAA;AASD;IAAA;IAQA,CAAC;IALG,sCAAc,GAAd,UAAe,cAA+B;QAC1C,cAAc,CAAC,IAAI,GAAG;YAClB,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ;SACnD,CAAA;IACL,CAAC;IACL,oBAAC;AAAD,CAAC,AARD,IAQC;AARY,qBAAa,gBAQzB,CAAA;AAED;IAGI,oBAAoB,QAAgB,EAAU,SAAiB;QAA3C,aAAQ,GAAR,QAAQ,CAAQ;QAAU,cAAS,GAAT,SAAS,CAAQ;IAC/D,CAAC;IAED,mCAAc,GAAd,UAAe,cAA+B;QAC1C,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,IAAI,OAAO,CAAC,CAAC,CAAC;YACrB,cAAc,CAAC,EAAG,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3D,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,IAAI,QAAQ,IAAI,cAAc,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;YAC/E,cAAc,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;QACzD,CAAC;IACL,CAAC;IACL,iBAAC;AAAD,CAAC,AAbD,IAaC;AAbY,kBAAU,aAatB,CAAA;AAED;IAAA;IAQA,CAAC;IALG,8BAAc,GAAd,UAAe,cAA+B;QAC1C,EAAE,CAAC,CAAC,cAAc,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;YAC3C,cAAc,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,SAAS,GAAG,IAAI,CAAC,WAAW,CAAC;QAC3E,CAAC;IACL,CAAC;IACL,YAAC;AAAD,CAAC,AARD,IAQC;AARY,aAAK,QAQjB,CAAA;AAED;IAAA;IAMA,CAAC;IAHG,iCAAc,GAAd,UAAe,CAAkB;IAEjC,CAAC;IACL,eAAC;AAAD,CAAC,AAND,IAMC;AANY,gBAAQ,WAMpB,CAAA;AAED,WAAY,aAAa;IACrB,uDAAO,CAAA;AACX,CAAC,EAFW,qBAAa,KAAb,qBAAa,QAExB;AAFD,IAAY,aAAa,GAAb,qBAEX,CAAA;AAED;IAYI,gBAAY,kBAA0B,EAAE,QAAiB,EAAE,QAAiB;QAXlE,aAAQ,GAAG,eAAe,CAAC;QAC3B,mBAAc,GAAS,EAAE,CAAC;QAC1B,oBAAe,GAAa,KAAK,CAAC;QAElC,oBAAe,GAAG;YACxB,SAAS,EAAkB,IAAI,QAAQ,EAAE;YACzC,SAAS,EAAE,IAAI,UAAU,CAAC,QAAQ,EAAE,SAAS,CAAC;YAC9C,eAAe,EAAE,IAAI,KAAK,EAAE;SAC/B,CAAA;QAIG,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;YACX,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACX,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;YAC7B,CAAC;QACL,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC;gBACrB,IAAI,CAAC,QAAQ,GAAG,kBAAkB,CAAA;YACtC,CAAC;QACL,CAAC;IACL,CAAC;IAED,sBAAI,kCAAc;aAAlB,UAAmB,KAAc;YAC7B,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;QACjC,CAAC;;;OAAA;IAEM,0BAAS,GAAhB,UAAiB,GAAkB,EAAE,KAAa;QAC9C,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,CAAC;IAC5D,CAAC;IAED,sBAAI,+BAAW;aAAf,UAAgB,KAAa;YACzB,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,WAAW,GAAG,KAAK,CAAC;QAC3D,CAAC;;;OAAA;IACO,0BAAS,GAAjB,UAAyB,IAAQ,EAAE,IAAQ;QACvC,GAAG,CAAA,CAAC,IAAI,GAAG,IAAI,IAAI,CAAC,CAAA,CAAC;YACjB,EAAE,CAAA,CAAC,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,CAAA,CAAC;gBACzB,IAAI,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;YAC1B,CAAC;QACL,CAAC;QACD,MAAM,CAAQ,IAAI,CAAC;IACvB,CAAC;IAMM,uBAAM,GAAb,UAAe,IAAU;QACrB,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC;QAC5C,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAGzB,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC;SAChD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAElE,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAOM,0BAAS,GAAhB,UAAkB,KAAa,EAAE,MAAe;QAC5C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc;aAC9C,OAAO,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QACjD,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAIzB,EAAE,CAAC,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;QAC9F,CAAC;QAED,YAAY,CAAC,SAAS,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAEvE,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,QAAQ;YAChB,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAElE,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,iCAAgB,GAAvB,UAAyB,MAAsB;QAC3C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,mBAAmB,CAAC;QACzD,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAGzB,EAAE,CAAC,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC;YACvB,eAAe,CAAC,QAAQ,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,MAAM,EAAE,qBAAqB,CAAC,CAAC;QAC1F,CAAC;QAED,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAElE,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAwD,UAAC,OAAO,EAAE,MAAM;YACtF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACN,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,kBAAkB,CAAC,CAAC;oBAC5D,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,+BAAc,GAArB,UAAuB,IAAoB;QACvC,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,iBAAiB,CAAC;QACvD,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAGzB,EAAE,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACrB,eAAe,CAAC,MAAM,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,qBAAqB,CAAC,CAAC;QACtF,CAAC;QAED,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAElE,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAwD,UAAC,OAAO,EAAE,MAAM;YACtF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACN,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,kBAAkB,CAAC,CAAC;oBAC5D,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,2BAAU,GAAjB,UAAmB,KAAa;QAC5B,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc;aAC9C,OAAO,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QACjD,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAIzB,EAAE,CAAC,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,yEAAyE,CAAC,CAAC;QAC/F,CAAC;QAED,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAElE,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAiD,UAAC,OAAO,EAAE,MAAM;YAC/E,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACN,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;oBAC/C,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,0BAAS,GAAhB,UAAkB,IAAU;QACxB,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC;QAC5C,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAGzB,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC;SAChD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAElE,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAQM,kCAAiB,GAAxB,UAA0B,KAAa,EAAE,IAAa,EAAE,MAAe;QACnE,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc;aAC9C,OAAO,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QACjD,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAIzB,EAAE,CAAC,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,gFAAgF,CAAC,CAAC;QACtG,CAAC;QAED,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,EAAE,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACrB,UAAU,CAAC,MAAM,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QACpE,CAAC;QAED,EAAE,CAAC,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC;YACvB,UAAU,CAAC,QAAQ,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QACxE,CAAC;QAED,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAElE,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAQM,2BAAU,GAAjB,UAAmB,KAAa,EAAE,kBAA2B,EAAE,IAAU;QACrE,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,0BAA0B;aAC1D,OAAO,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QACjD,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAIzB,EAAE,CAAC,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,yEAAyE,CAAC,CAAC;QAC/F,CAAC;QAED,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,EAAE,CAAC,CAAC,kBAAkB,KAAK,SAAS,CAAC,CAAC,CAAC;YACnC,UAAU,CAAC,oBAAoB,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,kBAAkB,EAAE,QAAQ,CAAC,CAAC;QAChG,CAAC;QAED,EAAE,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACrB,UAAU,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;QAC9B,CAAC;QACD,WAAW,GAAG,IAAI,CAAC;QAEnB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAElE,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IACL,aAAC;AAAD,CAAC,AAlfD,IAkfC;AAlfY,cAAM,SAkflB,CAAA;AACD,WAAY,eAAe;IACvB,2DAAO,CAAA;AACX,CAAC,EAFW,uBAAe,KAAf,uBAAe,QAE1B;AAFD,IAAY,eAAe,GAAf,uBAEX,CAAA;AAED;IAYI,kBAAY,kBAA0B,EAAE,QAAiB,EAAE,QAAiB;QAXlE,aAAQ,GAAG,eAAe,CAAC;QAC3B,mBAAc,GAAS,EAAE,CAAC;QAC1B,oBAAe,GAAa,KAAK,CAAC;QAElC,oBAAe,GAAG;YACxB,SAAS,EAAkB,IAAI,QAAQ,EAAE;YACzC,SAAS,EAAE,IAAI,UAAU,CAAC,QAAQ,EAAE,SAAS,CAAC;YAC9C,eAAe,EAAE,IAAI,KAAK,EAAE;SAC/B,CAAA;QAIG,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;YACX,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACX,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;YAC7B,CAAC;QACL,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC;gBACrB,IAAI,CAAC,QAAQ,GAAG,kBAAkB,CAAA;YACtC,CAAC;QACL,CAAC;IACL,CAAC;IAED,sBAAI,oCAAc;aAAlB,UAAmB,KAAc;YAC7B,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;QACjC,CAAC;;;OAAA;IAEM,4BAAS,GAAhB,UAAiB,GAAoB,EAAE,KAAa;QAChD,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,CAAC;IAC9D,CAAC;IAED,sBAAI,iCAAW;aAAf,UAAgB,KAAa;YACzB,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,WAAW,GAAG,KAAK,CAAC;QAC3D,CAAC;;;OAAA;IACO,4BAAS,GAAjB,UAAyB,IAAQ,EAAE,IAAQ;QACvC,GAAG,CAAA,CAAC,IAAI,GAAG,IAAI,IAAI,CAAC,CAAA,CAAC;YACjB,EAAE,CAAA,CAAC,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,CAAA,CAAC;gBACzB,IAAI,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;YAC1B,CAAC;QACL,CAAC;QACD,MAAM,CAAQ,IAAI,CAAC;IACvB,CAAC;IAMM,8BAAW,GAAlB,UAAoB,OAAe;QAC/B,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,wBAAwB;aACxD,OAAO,CAAC,GAAG,GAAG,SAAS,GAAG,GAAG,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;QACrD,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAIzB,EAAE,CAAC,CAAC,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC;YAC5C,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAClG,CAAC;QAED,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,QAAQ;YAChB,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAKM,+BAAY,GAAnB;QACI,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,kBAAkB,CAAC;QACxD,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAGzB,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAwE,UAAC,OAAO,EAAE,MAAM;YACtG,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACN,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,4BAA4B,CAAC,CAAC;oBACtE,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,+BAAY,GAAnB,UAAqB,OAAe;QAChC,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,wBAAwB;aACxD,OAAO,CAAC,GAAG,GAAG,SAAS,GAAG,GAAG,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;QACrD,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAIzB,EAAE,CAAC,CAAC,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC;YAC5C,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC;QACnG,CAAC;QAED,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAmD,UAAC,OAAO,EAAE,MAAM;YACjF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACN,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;oBACjD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,6BAAU,GAAjB,UAAmB,IAAY;QAC3B,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc,CAAC;QACpD,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAGzB,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC;SAClD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAmD,UAAC,OAAO,EAAE,MAAM;YACjF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACN,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;oBACjD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IACL,eAAC;AAAD,CAAC,AAxPD,IAwPC;AAxPY,gBAAQ,WAwPpB,CAAA;AACD,WAAY,cAAc;IACtB,yDAAO,CAAA;AACX,CAAC,EAFW,sBAAc,KAAd,sBAAc,QAEzB;AAFD,IAAY,cAAc,GAAd,sBAEX,CAAA;AAED;IAYI,iBAAY,kBAA0B,EAAE,QAAiB,EAAE,QAAiB;QAXlE,aAAQ,GAAG,eAAe,CAAC;QAC3B,mBAAc,GAAS,EAAE,CAAC;QAC1B,oBAAe,GAAa,KAAK,CAAC;QAElC,oBAAe,GAAG;YACxB,SAAS,EAAkB,IAAI,QAAQ,EAAE;YACzC,SAAS,EAAE,IAAI,UAAU,CAAC,QAAQ,EAAE,SAAS,CAAC;YAC9C,eAAe,EAAE,IAAI,KAAK,EAAE;SAC/B,CAAA;QAIG,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;YACX,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACX,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;YAC7B,CAAC;QACL,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC;gBACrB,IAAI,CAAC,QAAQ,GAAG,kBAAkB,CAAA;YACtC,CAAC;QACL,CAAC;IACL,CAAC;IAED,sBAAI,mCAAc;aAAlB,UAAmB,KAAc;YAC7B,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;QACjC,CAAC;;;OAAA;IAEM,2BAAS,GAAhB,UAAiB,GAAmB,EAAE,KAAa;QAC/C,IAAI,CAAC,eAAe,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,CAAC;IAC7D,CAAC;IAED,sBAAI,gCAAW;aAAf,UAAgB,KAAa;YACzB,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,WAAW,GAAG,KAAK,CAAC;QAC3D,CAAC;;;OAAA;IACO,2BAAS,GAAjB,UAAyB,IAAQ,EAAE,IAAQ;QACvC,GAAG,CAAA,CAAC,IAAI,GAAG,IAAI,IAAI,CAAC,CAAA,CAAC;YACjB,EAAE,CAAA,CAAC,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,CAAA,CAAC;gBACzB,IAAI,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;YAC1B,CAAC;QACL,CAAC;QACD,MAAM,CAAQ,IAAI,CAAC;IACvB,CAAC;IAMM,4BAAU,GAAjB,UAAmB,IAAW;QAC1B,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QAC7C,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAGzB,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;SACjD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,2CAAyB,GAAhC,UAAkC,IAAkB;QAChD,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,uBAAuB,CAAC;QAC7D,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAGzB,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,mBAAmB,CAAC;SAC9D,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,0CAAwB,GAA/B,UAAiC,IAAkB;QAC/C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,sBAAsB,CAAC;QAC5D,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAGzB,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,mBAAmB,CAAC;SAC9D,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,4BAAU,GAAjB,UAAmB,QAAgB;QAC/B,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,kBAAkB;aAClD,OAAO,CAAC,GAAG,GAAG,UAAU,GAAG,GAAG,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;QACvD,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAIzB,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAClG,CAAC;QAED,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,QAAQ;YAChB,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,+BAAa,GAApB,UAAsB,QAAgB;QAClC,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,kBAAkB;aAClD,OAAO,CAAC,GAAG,GAAG,UAAU,GAAG,GAAG,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;QACvD,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAIzB,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,+EAA+E,CAAC,CAAC;QACrG,CAAC;QAED,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACN,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;oBAChD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAOM,2BAAS,GAAhB,UAAkB,QAAiB,EAAE,QAAiB;QAClD,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,aAAa,CAAC;QACnD,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAGzB,EAAE,CAAC,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YACzB,eAAe,CAAC,UAAU,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QACjF,CAAC;QAED,EAAE,CAAC,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YACzB,eAAe,CAAC,UAAU,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QACjF,CAAC;QAED,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAoD,UAAC,OAAO,EAAE,MAAM;YAClF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACN,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;oBAClD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAKM,4BAAU,GAAjB;QACI,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc,CAAC;QACpD,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAGzB,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAOM,4BAAU,GAAjB,UAAmB,QAAgB,EAAE,IAAW;QAC5C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,kBAAkB;aAClD,OAAO,CAAC,GAAG,GAAG,UAAU,GAAG,GAAG,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;QACvD,IAAI,eAAe,GAAQ,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAChE,IAAI,UAAU,GAAQ,EAAE,CAAC;QAIzB,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAClG,CAAC;QAED,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,IAAI,cAAc,GAAoB;YAClC,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,eAAe;YACnB,OAAO,EAAE,YAAY;YACrB,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YAEpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;SACjD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QAE5D,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACjC,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;gBACR,cAAe,CAAC,QAAQ,GAAG,UAAU,CAAC;YAChD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,cAAc,CAAC,IAAI,GAAG,UAAU,CAAC;YACrC,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,OAAO,CAAC,cAAc,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1C,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAC3D,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IACL,cAAC;AAAD,CAAC,AApcD,IAocC;AApcY,eAAO,UAocnB,CAAA"} \ No newline at end of file +{"version":3,"file":"api.js","sourceRoot":"","sources":["api.ts"],"names":[],"mappings":";AAYA,IAAO,eAAe,WAAW,SAAS,CAAC,CAAC;AAE5C,IAAO,OAAO,WAAW,UAAU,CAAC,CAAC;AAErC,IAAI,eAAe,GAAG,+BAA+B,CAAC;AAOtD,IAAI,UAAU,GAAG;IACG,QAAQ;IACR,SAAS;IACT,QAAQ;IACR,SAAS;IACT,MAAM;IACN,OAAO;IACP,QAAQ;IACR,KAAK;CACP,CAAC;AAEnB;IAAA;IAsGA,CAAC;IApGiB,gCAAe,GAA7B,UAA8B,IAAS,EAAE,YAAoB;QACzD,EAAE,CAAC,CAAC,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC;YACpB,MAAM,CAAC,YAAY,CAAC;QACxB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,YAAY,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YAC/D,MAAM,CAAC,YAAY,CAAC;QACxB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,YAAY,KAAK,MAAM,CAAC,CAAC,CAAC;YACjC,MAAM,CAAC,YAAY,CAAC;QACxB,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;gBACzB,MAAM,CAAC,YAAY,CAAC;YACxB,CAAC;YAED,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;gBACzB,MAAM,CAAC,YAAY,CAAC;YACxB,CAAC;YAGD,IAAI,qBAAqB,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC,aAAa,CAAC;YAChE,EAAE,CAAC,CAAC,qBAAqB,IAAI,IAAI,CAAC,CAAC,CAAC;gBAChC,MAAM,CAAC,YAAY,CAAC;YACxB,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,EAAE,CAAC,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC;oBAC9B,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;gBACvC,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,MAAM,CAAC,YAAY,CAAC;gBACxB,CAAC;YACL,CAAC;QACL,CAAC;IACL,CAAC;IAEa,0BAAS,GAAvB,UAAwB,IAAS,EAAE,IAAY;QAC3C,EAAE,CAAC,CAAC,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC;YACpB,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YACvD,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAC7C,IAAI,OAAO,GAAW,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;YACjD,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YACnD,IAAI,eAAe,GAAG,EAAE,CAAC;YACzB,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC;gBACrB,IAAI,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;gBACvB,eAAe,CAAC,IAAI,CAAC,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;YACpE,CAAC;YACD,MAAM,CAAC,eAAe,CAAC;QAC3B,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC;YACzB,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC3B,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBACjB,MAAM,CAAC,IAAI,CAAC;YAChB,CAAC;YACD,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBACjB,MAAM,CAAC,IAAI,CAAC;YAChB,CAAC;YAGD,IAAI,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,mBAAmB,EAAE,CAAC;YACzD,IAAI,QAAQ,GAAG,EAAE,CAAC;YAClB,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,cAAc,CAAC,CAAC,CAAC;gBAC/B,IAAI,aAAa,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;gBAC1C,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,aAAa,CAAC,IAAI,CAAC,CAAC;YAChH,CAAC;YACD,MAAM,CAAC,QAAQ,CAAC;QACpB,CAAC;IACL,CAAC;IAEa,4BAAW,GAAzB,UAA0B,IAAS,EAAE,IAAY;QAE7C,IAAI,GAAG,gBAAgB,CAAC,eAAe,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACpD,EAAE,CAAC,CAAC,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC;YACpB,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YACvD,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAC7C,IAAI,OAAO,GAAW,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;YACjD,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YACnD,IAAI,eAAe,GAAG,EAAE,CAAC;YACzB,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC;gBACrB,IAAI,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;gBACvB,eAAe,CAAC,IAAI,CAAC,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;YACtE,CAAC;YACD,MAAM,CAAC,eAAe,CAAC;QAC3B,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC;YACzB,MAAM,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;QAC1B,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBACjB,MAAM,CAAC,IAAI,CAAC;YAChB,CAAC;YAED,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBACjB,MAAM,CAAC,IAAI,CAAC;YAChB,CAAC;YACD,IAAI,QAAQ,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;YACnC,IAAI,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,mBAAmB,EAAE,CAAC;YACzD,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,cAAc,CAAC,CAAC,CAAC;gBAC/B,IAAI,aAAa,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;gBAC1C,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,EAAE,aAAa,CAAC,IAAI,CAAC,CAAC;YAClH,CAAC;YACD,MAAM,CAAC,QAAQ,CAAC;QACpB,CAAC;IACL,CAAC;IACL,uBAAC;AAAD,CAAC,AAtGD,IAsGC;AAKD;IAAA;IA2BA,CAAC;IAHU,+BAAmB,GAA1B;QACI,MAAM,CAAC,WAAW,CAAC,gBAAgB,CAAC;IACxC,CAAC;IArBM,yBAAa,GAAG,SAAS,CAAC;IAE1B,4BAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,SAAS;YACjB,UAAU,EAAE,SAAS;YACrB,MAAM,EAAE,QAAQ;SACnB,CAAK,CAAC;IAKf,kBAAC;AAAD,CAAC,AA3BD,IA2BC;AA3BY,mBAAW,cA2BvB,CAAA;AAKD;IAAA;IAqBA,CAAC;IAHU,4BAAmB,GAA1B;QACI,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CAAC;IACrC,CAAC;IAhBM,sBAAa,GAAG,SAAS,CAAC;IAE1B,yBAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SACnB,CAAK,CAAC;IAKf,eAAC;AAAD,CAAC,AArBD,IAqBC;AArBY,gBAAQ,WAqBpB,CAAA;AAKD;IAAA;IAgDA,CAAC;IAHU,yBAAmB,GAA1B;QACI,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAAC;IAClC,CAAC;IApCM,mBAAa,GAAG,SAAS,CAAC;IAE1B,sBAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,OAAO;YACf,UAAU,EAAE,OAAO;YACnB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,MAAM;SACjB;QACD;YACI,MAAM,EAAE,QAAQ;YAChB,UAAU,EAAE,QAAQ;YACpB,MAAM,EAAE,kBAAkB;SAC7B;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,SAAS;SACpB,CAAK,CAAC;IAKf,YAAC;AAAD,CAAC,AAhDD,IAgDC;AAhDY,aAAK,QAgDjB,CAAA;AAED,IAAiB,KAAK,CAMrB;AAND,WAAiB,KAAK,EAAC,CAAC;IACpB,WAAY,UAAU;QAClB,kCAAe,QAAQ,YAAA,CAAA;QACvB,oCAAiB,UAAU,cAAA,CAAA;QAC3B,qCAAkB,WAAW,eAAA,CAAA;IACjC,CAAC,EAJW,gBAAU,KAAV,gBAAU,QAIrB;IAJD,IAAY,UAAU,GAAV,gBAIX,CAAA;AACL,CAAC,EANgB,KAAK,GAAL,aAAK,KAAL,aAAK,QAMrB;AAID;IAAA;IAgDA,CAAC;IAHU,uBAAmB,GAA1B;QACI,MAAM,CAAC,GAAG,CAAC,gBAAgB,CAAC;IAChC,CAAC;IApCM,iBAAa,GAAG,SAAS,CAAC;IAE1B,oBAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,UAAU;SACrB;QACD;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,WAAW;YACnB,UAAU,EAAE,WAAW;YACvB,MAAM,EAAE,eAAe;SAC1B;QACD;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,YAAY;SACvB;QACD;YACI,MAAM,EAAE,QAAQ;YAChB,UAAU,EAAE,QAAQ;YACpB,MAAM,EAAE,gBAAgB;SAC3B,CAAK,CAAC;IAKf,UAAC;AAAD,CAAC,AAhDD,IAgDC;AAhDY,WAAG,MAgDf,CAAA;AAED,IAAiB,GAAG,CAMnB;AAND,WAAiB,GAAG,EAAC,CAAC;IAClB,WAAY,UAAU;QAClB,qCAAkB,WAAW,eAAA,CAAA;QAC7B,mCAAgB,SAAS,aAAA,CAAA;QACzB,gCAAa,MAAM,UAAA,CAAA;IACvB,CAAC,EAJW,cAAU,KAAV,cAAU,QAIrB;IAJD,IAAY,UAAU,GAAV,cAIX,CAAA;AACL,CAAC,EANgB,GAAG,GAAH,WAAG,KAAH,WAAG,QAMnB;AAID;IAAA;IAqBA,CAAC;IAHU,uBAAmB,GAA1B;QACI,MAAM,CAAC,GAAG,CAAC,gBAAgB,CAAC;IAChC,CAAC;IAhBM,iBAAa,GAAG,SAAS,CAAC;IAE1B,oBAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,MAAM;YACd,UAAU,EAAE,MAAM;YAClB,MAAM,EAAE,QAAQ;SACnB,CAAK,CAAC;IAKf,UAAC;AAAD,CAAC,AArBD,IAqBC;AArBY,WAAG,MAqBf,CAAA;AAKD;IAAA;IA4DA,CAAC;IAHU,wBAAmB,GAA1B;QACI,MAAM,CAAC,IAAI,CAAC,gBAAgB,CAAC;IACjC,CAAC;IA9CM,kBAAa,GAAG,SAAS,CAAC;IAE1B,qBAAgB,GAA0D;QAC7E;YACI,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,WAAW;YACnB,UAAU,EAAE,WAAW;YACvB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,OAAO;YACf,UAAU,EAAE,OAAO;YACnB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,OAAO;YACf,UAAU,EAAE,OAAO;YACnB,MAAM,EAAE,QAAQ;SACnB;QACD;YACI,MAAM,EAAE,YAAY;YACpB,UAAU,EAAE,YAAY;YACxB,MAAM,EAAE,QAAQ;SACnB,CAAK,CAAC;IAKf,WAAC;AAAD,CAAC,AA5DD,IA4DC;AA5DY,YAAI,OA4DhB,CAAA;AAGD,IAAI,QAAQ,GAAG;IACP,kBAAkB,EAAE,KAAK,CAAC,UAAU;IACpC,gBAAgB,EAAE,GAAG,CAAC,UAAU;CACvC,CAAA;AAED,IAAI,OAAO,GAAG;IACV,aAAa,EAAE,WAAW;IAC1B,UAAU,EAAE,QAAQ;IACpB,OAAO,EAAE,KAAK;IACd,KAAK,EAAE,GAAG;IACV,KAAK,EAAE,GAAG;IACV,MAAM,EAAE,IAAI;CACf,CAAA;AASD;IAAA;IAQA,CAAC;IALG,sCAAc,GAAd,UAAe,cAAuC;QAClD,cAAc,CAAC,IAAI,GAAG;YAClB,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ;SACnD,CAAA;IACL,CAAC;IACL,oBAAC;AAAD,CAAC,AARD,IAQC;AARY,qBAAa,gBAQzB,CAAA;AAED;IAGI,oBAAoB,QAAgB,EAAU,SAAiB;QAA3C,aAAQ,GAAR,QAAQ,CAAQ;QAAU,cAAS,GAAT,SAAS,CAAQ;IAC/D,CAAC;IAED,mCAAc,GAAd,UAAe,cAAuC;QAClD,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,IAAI,OAAO,CAAC,CAAC,CAAC;YACrB,cAAc,CAAC,EAAG,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3D,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,IAAI,QAAQ,IAAI,cAAc,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;YAC/E,cAAc,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;QACzD,CAAC;IACL,CAAC;IACL,iBAAC;AAAD,CAAC,AAbD,IAaC;AAbY,kBAAU,aAatB,CAAA;AAED;IAAA;IAQA,CAAC;IALG,8BAAc,GAAd,UAAe,cAAuC;QAClD,EAAE,CAAC,CAAC,cAAc,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;YAC3C,cAAc,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,SAAS,GAAG,IAAI,CAAC,WAAW,CAAC;QAC3E,CAAC;IACL,CAAC;IACL,YAAC;AAAD,CAAC,AARD,IAQC;AARY,aAAK,QAQjB,CAAA;AAED;IAAA;IAMA,CAAC;IAHG,iCAAc,GAAd,UAAe,CAA0B;IAEzC,CAAC;IACL,eAAC;AAAD,CAAC,AAND,IAMC;AANY,gBAAQ,WAMpB,CAAA;AAED,WAAY,aAAa;IACrB,uDAAO,CAAA;AACX,CAAC,EAFW,qBAAa,KAAb,qBAAa,QAExB;AAFD,IAAY,aAAa,GAAb,qBAEX,CAAA;AAED;IAYI,gBAAY,kBAA0B,EAAE,QAAiB,EAAE,QAAiB;QAXlE,cAAS,GAAG,eAAe,CAAC;QAC5B,mBAAc,GAAS,EAAE,CAAC;QAC1B,oBAAe,GAAa,KAAK,CAAC;QAElC,oBAAe,GAAG;YACxB,SAAS,EAAkB,IAAI,QAAQ,EAAE;YACzC,SAAS,EAAE,IAAI,UAAU,CAAC,QAAQ,EAAE,SAAS,CAAC;YAC9C,eAAe,EAAE,IAAI,KAAK,EAAE;SAC/B,CAAA;QAIG,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;YACX,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACX,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;YAC7B,CAAC;QACL,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC;gBACrB,IAAI,CAAC,QAAQ,GAAG,kBAAkB,CAAA;YACtC,CAAC;QACL,CAAC;IACL,CAAC;IAED,sBAAI,kCAAc;aAAlB,UAAmB,KAAc;YAC7B,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;QACjC,CAAC;;;OAAA;IAED,sBAAI,4BAAQ;aAIZ;YACI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QAC1B,CAAC;aAND,UAAa,QAAgB;YACzB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC9B,CAAC;;;OAAA;IAMM,yCAAwB,GAA/B,UAAgC,IAAoB;QACvD,IAAI,CAAC,eAAe,CAAC,OAAO,GAAG,IAAI,CAAC;IACjC,CAAC;IAEM,0BAAS,GAAhB,UAAiB,GAAkB,EAAE,KAAa;QAC9C,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,CAAC;IAC5D,CAAC;IAED,sBAAI,+BAAW;aAAf,UAAgB,KAAa;YACzB,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,WAAW,GAAG,KAAK,CAAC;QAC3D,CAAC;;;OAAA;IAMM,uBAAM,GAAb,UAAe,IAAS;QACpB,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC;QAC5C,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,oEAAoE,CAAC,CAAC;QAC1F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC;SAChD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAOM,0BAAS,GAAhB,UAAkB,KAAa,EAAE,MAAe;QAC5C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc;aAC9C,OAAO,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACrE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;QAC9F,CAAC;QAED,oBAAoB,CAAC,SAAS,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAE/E,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,QAAQ;YAChB,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,iCAAgB,GAAvB,UAAyB,MAAqB;QAC1C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,mBAAmB,CAAC;QACzD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,MAAM,KAAK,IAAI,IAAI,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC;YAC1C,MAAM,IAAI,KAAK,CAAC,gFAAgF,CAAC,CAAC;QACtG,CAAC;QAED,EAAE,CAAC,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC;YACvB,uBAAuB,CAAC,QAAQ,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;QAC5F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAwD,UAAC,OAAO,EAAE,MAAM;YACtF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;oBACxD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,+BAAc,GAArB,UAAuB,IAAmB;QACtC,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,iBAAiB,CAAC;QACvD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAClG,CAAC;QAED,EAAE,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACrB,uBAAuB,CAAC,MAAM,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;QACxF,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAwD,UAAC,OAAO,EAAE,MAAM;YACtF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;oBACxD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,2BAAU,GAAjB,UAAmB,KAAa;QAC5B,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc;aAC9C,OAAO,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACrE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,yEAAyE,CAAC,CAAC;QAC/F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAiD,UAAC,OAAO,EAAE,MAAM;YAC/E,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;oBACjD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,0BAAS,GAAhB,UAAkB,IAAS;QACvB,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC;QAC5C,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,uEAAuE,CAAC,CAAC;QAC7F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC;SAChD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAQM,kCAAiB,GAAxB,UAA0B,KAAa,EAAE,IAAa,EAAE,MAAe;QACnE,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc;aAC9C,OAAO,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACrE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,gFAAgF,CAAC,CAAC;QACtG,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,EAAE,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACrB,kBAAkB,CAAC,MAAM,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC5E,CAAC;QAED,EAAE,CAAC,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC;YACvB,kBAAkB,CAAC,QAAQ,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAChF,CAAC;QAED,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAQM,2BAAU,GAAjB,UAAmB,KAAa,EAAE,kBAA2B,EAAE,IAAa;QACxE,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,0BAA0B;aAC1D,OAAO,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACrE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,yEAAyE,CAAC,CAAC;QAC/F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,EAAE,CAAC,CAAC,kBAAkB,KAAK,SAAS,CAAC,CAAC,CAAC;YACnC,kBAAkB,CAAC,oBAAoB,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,kBAAkB,EAAE,QAAQ,CAAC,CAAC;QACxG,CAAC;QAED,EAAE,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACrB,kBAAkB,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;QACtC,CAAC;QACD,mBAAmB,GAAG,IAAI,CAAC;QAE3B,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAE1E,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAyD,UAAC,OAAO,EAAE,MAAM;YACvF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;oBACzD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IACL,aAAC;AAAD,CAAC,AAhgBD,IAggBC;AAhgBY,cAAM,SAggBlB,CAAA;AACD,WAAY,eAAe;IACvB,2DAAO,CAAA;AACX,CAAC,EAFW,uBAAe,KAAf,uBAAe,QAE1B;AAFD,IAAY,eAAe,GAAf,uBAEX,CAAA;AAED;IAYI,kBAAY,kBAA0B,EAAE,QAAiB,EAAE,QAAiB;QAXlE,cAAS,GAAG,eAAe,CAAC;QAC5B,mBAAc,GAAS,EAAE,CAAC;QAC1B,oBAAe,GAAa,KAAK,CAAC;QAElC,oBAAe,GAAG;YACxB,SAAS,EAAkB,IAAI,QAAQ,EAAE;YACzC,SAAS,EAAE,IAAI,UAAU,CAAC,QAAQ,EAAE,SAAS,CAAC;YAC9C,eAAe,EAAE,IAAI,KAAK,EAAE;SAC/B,CAAA;QAIG,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;YACX,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACX,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;YAC7B,CAAC;QACL,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC;gBACrB,IAAI,CAAC,QAAQ,GAAG,kBAAkB,CAAA;YACtC,CAAC;QACL,CAAC;IACL,CAAC;IAED,sBAAI,oCAAc;aAAlB,UAAmB,KAAc;YAC7B,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;QACjC,CAAC;;;OAAA;IAED,sBAAI,8BAAQ;aAIZ;YACI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QAC1B,CAAC;aAND,UAAa,QAAgB;YACzB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC9B,CAAC;;;OAAA;IAMM,2CAAwB,GAA/B,UAAgC,IAAoB;QACvD,IAAI,CAAC,eAAe,CAAC,OAAO,GAAG,IAAI,CAAC;IACjC,CAAC;IAEM,4BAAS,GAAhB,UAAiB,GAAoB,EAAE,KAAa;QAChD,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,CAAC;IAC9D,CAAC;IAED,sBAAI,iCAAW;aAAf,UAAgB,KAAa;YACzB,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,WAAW,GAAG,KAAK,CAAC;QAC3D,CAAC;;;OAAA;IAMM,8BAAW,GAAlB,UAAoB,OAAe;QAC/B,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,wBAAwB;aACxD,OAAO,CAAC,GAAG,GAAG,SAAS,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;QACzE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC;YAC5C,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAClG,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,QAAQ;YAChB,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAKM,+BAAY,GAAnB;QACI,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,kBAAkB,CAAC;QACxD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAwE,UAAC,OAAO,EAAE,MAAM;YACtG,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,4BAA4B,CAAC,CAAC;oBACxE,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,+BAAY,GAAnB,UAAqB,OAAe;QAChC,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,wBAAwB;aACxD,OAAO,CAAC,GAAG,GAAG,SAAS,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;QACzE,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC;YAC5C,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC;QACnG,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAmD,UAAC,OAAO,EAAE,MAAM;YACjF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;oBACnD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,6BAAU,GAAjB,UAAmB,IAAW;QAC1B,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc,CAAC;QACpD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;QAC9F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC;SAClD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAmD,UAAC,OAAO,EAAE,MAAM;YACjF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;oBACnD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IACL,eAAC;AAAD,CAAC,AA7PD,IA6PC;AA7PY,gBAAQ,WA6PpB,CAAA;AACD,WAAY,cAAc;IACtB,yDAAO,CAAA;AACX,CAAC,EAFW,sBAAc,KAAd,sBAAc,QAEzB;AAFD,IAAY,cAAc,GAAd,sBAEX,CAAA;AAED;IAYI,iBAAY,kBAA0B,EAAE,QAAiB,EAAE,QAAiB;QAXlE,cAAS,GAAG,eAAe,CAAC;QAC5B,mBAAc,GAAS,EAAE,CAAC;QAC1B,oBAAe,GAAa,KAAK,CAAC;QAElC,oBAAe,GAAG;YACxB,SAAS,EAAkB,IAAI,QAAQ,EAAE;YACzC,SAAS,EAAE,IAAI,UAAU,CAAC,QAAQ,EAAE,SAAS,CAAC;YAC9C,eAAe,EAAE,IAAI,KAAK,EAAE;SAC/B,CAAA;QAIG,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;YACX,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACX,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;YAC7B,CAAC;QACL,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,EAAE,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC;gBACrB,IAAI,CAAC,QAAQ,GAAG,kBAAkB,CAAA;YACtC,CAAC;QACL,CAAC;IACL,CAAC;IAED,sBAAI,mCAAc;aAAlB,UAAmB,KAAc;YAC7B,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;QACjC,CAAC;;;OAAA;IAED,sBAAI,6BAAQ;aAIZ;YACI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QAC1B,CAAC;aAND,UAAa,QAAgB;YACzB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC9B,CAAC;;;OAAA;IAMM,0CAAwB,GAA/B,UAAgC,IAAoB;QACvD,IAAI,CAAC,eAAe,CAAC,OAAO,GAAG,IAAI,CAAC;IACjC,CAAC;IAEM,2BAAS,GAAhB,UAAiB,GAAmB,EAAE,KAAa;QAC/C,IAAI,CAAC,eAAe,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,CAAC;IAC7D,CAAC;IAED,sBAAI,gCAAW;aAAf,UAAgB,KAAa;YACzB,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,WAAW,GAAG,KAAK,CAAC;QAC3D,CAAC;;;OAAA;IAMM,4BAAU,GAAjB,UAAmB,IAAU;QACzB,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QAC7C,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;QAC9F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;SACjD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,2CAAyB,GAAhC,UAAkC,IAAiB;QAC/C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,uBAAuB,CAAC;QAC7D,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,uFAAuF,CAAC,CAAC;QAC7G,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,aAAa,CAAC;SACxD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,0CAAwB,GAA/B,UAAiC,IAAiB;QAC9C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,sBAAsB,CAAC;QAC5D,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,sFAAsF,CAAC,CAAC;QAC5G,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,aAAa,CAAC;SACxD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,4BAAU,GAAjB,UAAmB,QAAgB;QAC/B,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,kBAAkB;aAClD,OAAO,CAAC,GAAG,GAAG,UAAU,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QAC3E,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAClG,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,QAAQ;YAChB,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAMM,+BAAa,GAApB,UAAsB,QAAgB;QAClC,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,kBAAkB;aAClD,OAAO,CAAC,GAAG,GAAG,UAAU,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QAC3E,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,+EAA+E,CAAC,CAAC;QACrG,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;oBAClD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAOM,2BAAS,GAAhB,UAAkB,QAAgB,EAAE,QAAgB;QAChD,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,aAAa,CAAC;QACnD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,2EAA2E,CAAC,CAAC;QACjG,CAAC;QAGD,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,2EAA2E,CAAC,CAAC;QACjG,CAAC;QAED,EAAE,CAAC,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YACzB,uBAAuB,CAAC,UAAU,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QACzF,CAAC;QAED,EAAE,CAAC,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YACzB,uBAAuB,CAAC,UAAU,CAAC,GAAG,gBAAgB,CAAC,SAAS,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QACzF,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAoD,UAAC,OAAO,EAAE,MAAM;YAClF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,IAAI,GAAG,gBAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;oBACpD,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAKM,4BAAU,GAAjB;QACI,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,cAAc,CAAC;QACpD,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;SACb,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAOM,4BAAU,GAAjB,UAAmB,QAAgB,EAAE,IAAU;QAC3C,IAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,GAAG,kBAAkB;aAClD,OAAO,CAAC,GAAG,GAAG,UAAU,GAAG,GAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QAC3E,IAAI,uBAAuB,GAAQ,EAAE,CAAC;QACtC,IAAI,oBAAoB,GAAc,MAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9E,IAAI,kBAAkB,GAAQ,EAAE,CAAC;QAGjC,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAClG,CAAC;QAGD,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;QAC9F,CAAC;QAGD,IAAI,mBAAmB,GAAG,KAAK,CAAC;QAEhC,IAAI,sBAAsB,GAA4B;YAClD,MAAM,EAAE,KAAK;YACb,EAAE,EAAE,uBAAuB;YAC3B,OAAO,EAAE,oBAAoB;YAC7B,GAAG,EAAE,YAAY;YACjB,cAAc,EAAE,IAAI,CAAC,eAAe;YACpC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;SACjD,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAEpE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;YACzC,EAAE,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBAChB,sBAAuB,CAAC,QAAQ,GAAG,kBAAkB,CAAC;YAChE,CAAC;YAAC,IAAI,CAAC,CAAC;gBACJ,sBAAsB,CAAC,IAAI,GAAG,kBAAkB,CAAC;YACrD,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,OAAO,CAAkD,UAAC,OAAO,EAAE,MAAM;YAChF,eAAe,CAAC,sBAAsB,EAAE,UAAC,KAAK,EAAE,QAAQ,EAAE,IAAI;gBAC1D,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACR,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,IAAI,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;wBAClF,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAChD,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/C,CAAC;gBACL,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IACL,cAAC;AAAD,CAAC,AA9dD,IA8dC;AA9dY,eAAO,UA8dnB,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 45fabd8e1d5..ed2fce03d5c 100644 --- a/samples/client/petstore/typescript-node/npm/api.ts +++ b/samples/client/petstore/typescript-node/npm/api.ts @@ -10,7 +10,7 @@ * Do not edit the class manually. */ -import request = require('request'); +import localVarRequest = require('request'); import http = require('http'); import Promise = require('bluebird'); @@ -407,8 +407,8 @@ export class User { let enumsMap = { - "Order.StatusEnum": Order.StatusEnum, - "Pet.StatusEnum": Pet.StatusEnum, + "Order.StatusEnum": Order.StatusEnum, + "Pet.StatusEnum": Pet.StatusEnum, } let typeMap = { @@ -424,13 +424,13 @@ export interface Authentication { /** * Apply authentication settings to header and query params. */ - applyToRequest(requestOptions: request.Options): void; + applyToRequest(requestOptions: localVarRequest.Options): void; } export class HttpBasicAuth implements Authentication { public username: string; public password: string; - applyToRequest(requestOptions: request.Options): void { + applyToRequest(requestOptions: localVarRequest.Options): void { requestOptions.auth = { username: this.username, password: this.password } @@ -443,7 +443,7 @@ export class ApiKeyAuth implements Authentication { constructor(private location: string, private paramName: string) { } - applyToRequest(requestOptions: request.Options): void { + applyToRequest(requestOptions: localVarRequest.Options): void { if (this.location == "query") { (requestOptions.qs)[this.paramName] = this.apiKey; } else if (this.location == "header" && requestOptions && requestOptions.headers) { @@ -455,7 +455,7 @@ export class ApiKeyAuth implements Authentication { export class OAuth implements Authentication { public accessToken: string; - applyToRequest(requestOptions: request.Options): void { + applyToRequest(requestOptions: localVarRequest.Options): void { if (requestOptions && requestOptions.headers) { requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; } @@ -465,7 +465,7 @@ export class OAuth implements Authentication { export class VoidAuth implements Authentication { public username: string; public password: string; - applyToRequest(_: request.Options): void { + applyToRequest(_: localVarRequest.Options): void { // Do nothing } } @@ -528,9 +528,9 @@ export class PetApi { */ public addPet (body: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { @@ -538,35 +538,35 @@ export class PetApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Pet") }; - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -584,45 +584,45 @@ export class PetApi { public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: 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'] = ObjectSerializer.serialize(apiKey, "string"); + localVarHeaderParams['api_key'] = ObjectSerializer.serialize(apiKey, "string"); - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'DELETE', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -638,9 +638,9 @@ export class PetApi { */ public findPetsByStatus (status: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { const localVarPath = this.basePath + '/pet/findByStatus'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'status' is not null or undefined if (status === null || status === undefined) { @@ -648,39 +648,39 @@ export class PetApi { } if (status !== undefined) { - queryParameters['status'] = ObjectSerializer.serialize(status, "Array"); + localVarQueryParameters['status'] = ObjectSerializer.serialize(status, "Array"); } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: Array; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Array"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -696,9 +696,9 @@ export class PetApi { */ public findPetsByTags (tags: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { const localVarPath = this.basePath + '/pet/findByTags'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'tags' is not null or undefined if (tags === null || tags === undefined) { @@ -706,39 +706,39 @@ export class PetApi { } if (tags !== undefined) { - queryParameters['tags'] = ObjectSerializer.serialize(tags, "Array"); + localVarQueryParameters['tags'] = ObjectSerializer.serialize(tags, "Array"); } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: Array; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Array"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -755,9 +755,9 @@ export class PetApi { public getPetById (petId: number) : Promise<{ response: http.ClientResponse; body: Pet; }> { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -765,35 +765,35 @@ export class PetApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.api_key.applyToRequest(requestOptions); + this.authentications.api_key.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: Pet; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Pet"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -809,9 +809,9 @@ export class PetApi { */ public updatePet (body: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { @@ -819,35 +819,35 @@ export class PetApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'PUT', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Pet") }; - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -866,9 +866,9 @@ export class PetApi { public updatePetWithForm (petId: number, name?: string, status?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -876,42 +876,42 @@ export class PetApi { } - let useFormData = false; + let localVarUseFormData = false; if (name !== undefined) { - formParams['name'] = ObjectSerializer.serialize(name, "string"); + localVarFormParams['name'] = ObjectSerializer.serialize(name, "string"); } if (status !== undefined) { - formParams['status'] = ObjectSerializer.serialize(status, "string"); + localVarFormParams['status'] = ObjectSerializer.serialize(status, "string"); } - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -930,9 +930,9 @@ export class PetApi { public uploadFile (petId: number, additionalMetadata?: string, file?: Buffer) : Promise<{ response: http.ClientResponse; body: ApiResponse; }> { const localVarPath = this.basePath + '/pet/{petId}/uploadImage' .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -940,44 +940,44 @@ export class PetApi { } - let useFormData = false; + let localVarUseFormData = false; if (additionalMetadata !== undefined) { - formParams['additionalMetadata'] = ObjectSerializer.serialize(additionalMetadata, "string"); + localVarFormParams['additionalMetadata'] = ObjectSerializer.serialize(additionalMetadata, "string"); } if (file !== undefined) { - formParams['file'] = file; + localVarFormParams['file'] = file; } - useFormData = true; + localVarUseFormData = true; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: ApiResponse; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "ApiResponse"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1046,9 +1046,9 @@ export class StoreApi { public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -1056,32 +1056,32 @@ export class StoreApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'DELETE', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1096,40 +1096,40 @@ export class StoreApi { */ public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { const localVarPath = this.basePath + '/store/inventory'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.api_key.applyToRequest(requestOptions); + this.authentications.api_key.applyToRequest(localVarRequestOptions); - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "{ [key: string]: number; }"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1146,9 +1146,9 @@ export class StoreApi { public getOrderById (orderId: number) : Promise<{ response: http.ClientResponse; body: Order; }> { const localVarPath = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -1156,33 +1156,33 @@ export class StoreApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: Order; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Order"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1198,9 +1198,9 @@ export class StoreApi { */ public placeOrder (body: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { const localVarPath = this.basePath + '/store/order'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { @@ -1208,34 +1208,34 @@ export class StoreApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Order") }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: Order; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Order"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1303,9 +1303,9 @@ export class UserApi { */ public createUser (body: User) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { @@ -1313,33 +1313,33 @@ export class UserApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "User") }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1355,9 +1355,9 @@ export class UserApi { */ public createUsersWithArrayInput (body: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/createWithArray'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { @@ -1365,33 +1365,33 @@ export class UserApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Array") }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1407,9 +1407,9 @@ export class UserApi { */ public createUsersWithListInput (body: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/createWithList'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { @@ -1417,33 +1417,33 @@ export class UserApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'POST', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Array") }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1460,9 +1460,9 @@ export class UserApi { public deleteUser (username: string) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', encodeURIComponent(String(username))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -1470,32 +1470,32 @@ export class UserApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'DELETE', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1512,9 +1512,9 @@ export class UserApi { public getUserByName (username: string) : Promise<{ response: http.ClientResponse; body: User; }> { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', encodeURIComponent(String(username))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -1522,33 +1522,33 @@ export class UserApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: User; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "User"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1565,9 +1565,9 @@ export class UserApi { */ public loginUser (username: string, password: string) : Promise<{ response: http.ClientResponse; body: string; }> { const localVarPath = this.basePath + '/user/login'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -1580,41 +1580,41 @@ export class UserApi { } if (username !== undefined) { - queryParameters['username'] = ObjectSerializer.serialize(username, "string"); + localVarQueryParameters['username'] = ObjectSerializer.serialize(username, "string"); } if (password !== undefined) { - queryParameters['password'] = ObjectSerializer.serialize(password, "string"); + localVarQueryParameters['password'] = ObjectSerializer.serialize(password, "string"); } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: string; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "string"); - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1629,37 +1629,37 @@ export class UserApi { */ public logoutUser () : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/logout'; - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'GET', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); @@ -1677,9 +1677,9 @@ export class UserApi { public updateUser (username: string, body: User) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', encodeURIComponent(String(username))); - let queryParameters: any = {}; - let headerParams: any = (Object).assign({}, this.defaultHeaders); - let formParams: any = {}; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -1692,33 +1692,33 @@ export class UserApi { } - let useFormData = false; + let localVarUseFormData = false; - let requestOptions: request.Options = { + let localVarRequestOptions: localVarRequest.Options = { method: 'PUT', - qs: queryParameters, - headers: headerParams, + qs: localVarQueryParameters, + headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "User") }; - this.authentications.default.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(localVarRequestOptions); - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - requestOptions.form = formParams; + localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { - request(requestOptions, (error, response, body) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); diff --git a/samples/client/petstore/typescript-node/npm/client.js b/samples/client/petstore/typescript-node/npm/client.js index 74b85df1371..b5ef9cd8608 100644 --- a/samples/client/petstore/typescript-node/npm/client.js +++ b/samples/client/petstore/typescript-node/npm/client.js @@ -4,9 +4,9 @@ var fs = require('fs'); function deepCheck(objectA, objectB) { var a = objectA; var b = objectB; - var isString = (typeof a == "string" && typeof b == "string"); - var isBool = (typeof a == "boolean" && typeof b == "boolean"); - var isNumber = (typeof a == "number" && typeof b == "number"); + var isString = (typeof a === "string" && typeof b === "string"); + var isBool = (typeof a === "boolean" && typeof b === "boolean"); + var isNumber = (typeof a === "number" && typeof b === "number"); if (a instanceof Array && b instanceof Array) { for (var i = 0; i < a.length; i++) { if (!deepCheck(a[i], b[i])) { @@ -18,7 +18,7 @@ function deepCheck(objectA, objectB) { else if (isString || isBool || isNumber) { return a === b; } - else if (typeof a == "object" && typeof b == "object") { + else if (typeof a === "object" && typeof b === "object") { for (var key in a) { if (!deepCheck(a[key], b[key])) { return false; @@ -114,7 +114,7 @@ petApi.addPet(pet) }) .then(function (res) { console.log('Updated pet using POST form'); - return petApi.uploadFile(petId, undefined, fs.createReadStream('sample.png')); + return petApi.uploadFile(petId, undefined, fs.readFileSync('sample.png')); }) .then(function (res) { console.log('Uploaded image'); diff --git a/samples/client/petstore/typescript-node/npm/client.js.map b/samples/client/petstore/typescript-node/npm/client.js.map index a81b19de489..0ab215bb74b 100644 --- a/samples/client/petstore/typescript-node/npm/client.js.map +++ b/samples/client/petstore/typescript-node/npm/client.js.map @@ -1 +1 @@ -{"version":3,"file":"client.js","sourceRoot":"","sources":["client.ts"],"names":[],"mappings":";AAAA,IAAO,GAAG,WAAW,OAAO,CAAC,CAAC;AAC9B,IAAO,EAAE,WAAW,IAAI,CAAC,CAAC;AAG1B,mBAAmB,OAAY,EAAE,OAAY;IACzC,IAAI,CAAC,GAAG,OAAO,CAAC;IAChB,IAAI,CAAC,GAAG,OAAO,CAAC;IAChB,IAAI,QAAQ,GAAY,CAAC,OAAO,CAAC,IAAI,QAAQ,IAAI,OAAO,CAAC,IAAI,QAAQ,CAAC,CAAC;IACvE,IAAI,MAAM,GAAY,CAAC,OAAO,CAAC,IAAI,SAAS,IAAI,OAAO,CAAC,IAAI,SAAS,CAAC,CAAC;IACvE,IAAI,QAAQ,GAAY,CAAC,OAAO,CAAC,IAAI,QAAQ,IAAI,OAAO,CAAC,IAAI,QAAQ,CAAC,CAAC;IAEvE,EAAE,CAAC,CAAC,CAAC,YAAY,KAAK,IAAI,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC;QAC3C,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAChC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;gBACzB,MAAM,CAAC,KAAK,CAAC;YACjB,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,CAAC;IAChB,CAAC;IAAC,IAAI,CAAC,EAAE,CAAC,CAAC,QAAQ,IAAI,MAAM,IAAI,QAAQ,CAAC,CAAC,CAAC;QACxC,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC;IACnB,CAAC;IAAC,IAAI,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,QAAQ,IAAI,OAAO,CAAC,IAAI,QAAQ,CAAC,CAAA,CAAC;QACrD,GAAG,CAAC,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;YAChB,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;gBAC7B,MAAM,CAAC,KAAK,CAAC;YACjB,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,CAAC;IAChB,CAAC;IAAC,IAAI,CAAC,CAAC;QACJ,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC;IACnB,CAAC;AACL,CAAC;AAED,IAAI,MAAM,GAAG,IAAI,GAAG,CAAC,MAAM,EAAE,CAAC;AAC9B,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,aAAa,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC;AAG3D,IAAI,IAAI,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,CAAC;AACzB,IAAI,CAAC,EAAE,GAAG,KAAK,CAAC;AAChB,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;AAEvB,IAAI,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,CAAC;AACxB,GAAG,CAAC,IAAI,GAAG,kBAAkB,CAAC;AAC9B,GAAG,CAAC,EAAE,GAAG,KAAK,CAAC;AACf,GAAG,CAAC,SAAS,GAAG,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC;AAC/C,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC;AAElB,IAAI,KAAU,CAAC;AAEf,IAAI,QAAQ,GAAG,CAAC,CAAC;AAGjB,IAAI,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAA;AAC9B,IAAI,UAAU,GAAG,MAAM,CAAC,OAAO,CAAC,CAAA;AAChC,IAAI,gBAAgB,GAAG,UAAU,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC;AAC9D,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;AACzC,IAAI,aAAa,GAAG;IACI,IAAI,EAAE,GAAG,CAAC,EAAE;IACZ,UAAU,EAAE;QACI,IAAI,EAAE,KAAK;QACX,MAAM,EAAE,eAAe;KAC1B;IACb,MAAM,EAAE,GAAG,CAAC,IAAI;IAChB,WAAW,EAAE,GAAG,CAAC,SAAS;IAC1B,MAAM,EAAE;QACI;YACI,IAAI,EAAE,KAAK;YACX,MAAM,EAAE,UAAU;SACrB;KACJ;IACT,QAAQ,EAAE,WAAW;CACxB,CAAC;AACtB,IAAI,eAAe,GAAG,gBAAgB,CAAC,WAAW,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;AAEzE,IAAI,OAAO,GAAY,eAAe,YAAY,UAAU,CAAC,GAAG,CAAC;AACjE,IAAI,QAAQ,GAAY,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,YAAY,UAAU,CAAC,GAAG,CAAC;AAC1E,IAAI,YAAY,GAAY,eAAe,CAAC,QAAQ,YAAY,UAAU,CAAC,QAAQ,CAAC;AAEpF,IAAI,MAAM,GAAG,EAAE,CAAC;AAChB,GAAG,CAAC,CAAC,IAAI,GAAG,IAAI,eAAe,CAAC,CAAC,CAAC;IAC9B,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;IACjB,MAAM,CAAC,GAAG,CAAC,CAAC,WAAW,CAAC,GAAG,SAAS,CAAC,eAAe,CAAC,GAAG,CAAC,EAAE,aAAa,CAAC,GAAG,CAAC,CAAC,CAAA;IAC9E,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;IACzC,MAAM,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC;AAC/C,CAAC;AACD,IAAI,YAAY,GAAY,OAAO,IAAI,QAAQ,IAAI,YAAY,CAAC;AAEhE,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC;IAChB,QAAQ,GAAG,CAAC,CAAC;IACb,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAA;IACzC,OAAO,CAAC,GAAG,CAAC,oBAAoB,EAAE,QAAQ,CAAC,CAAA;IAC3C,OAAO,CAAC,GAAG,CAAC,wBAAwB,EAAE,YAAY,CAAC,CAAC;AACxD,CAAC;AAED,GAAG,CAAC,CAAC,IAAI,GAAG,IAAI,MAAM,CAAC,CAAC,CAAC;IACrB,IAAI,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;IACxB,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;QACtB,QAAQ,GAAG,CAAC,CAAC;QACb,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,aAAa,EAAC,UAAU,EACb,KAAK,CAAC,IAAI,CAAC,EAAE,cAAc,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC9E,CAAC;AACL,CAAC;AAED,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAA;AAGrC,IAAI,QAAQ,GAAG,IAAI,GAAG,CAAC,QAAQ,EAAE,CAAC;AAClC,QAAQ,CAAC,EAAE,GAAG,KAAK,CAAC;AACpB,QAAQ,CAAC,IAAI,GAAG,eAAe,CAAC;AAChC,GAAG,CAAC,QAAQ,GAAG,QAAQ,CAAC;AACxB,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,SAAS,CAAC;AAE1C,IAAI,gBAAgB,GAAG,gBAAgB,CAAC,SAAS,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;AAC9D,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,gBAAgB,EAAE,aAAa,CAAC,CAAC,CAAC,CAAC;IAC9C,QAAQ,GAAG,CAAC,CAAA;IACZ,OAAO,CAAC,GAAG,CAAC,uCAAuC,EAAE,gBAAgB,EACzB,cAAc,EAAE,aAAa,CAAC,CAAA;AAC9E,CAAC;AAGD,GAAG,CAAC,QAAQ,GAAG,SAAS,CAAC;AACzB,GAAG,CAAC,MAAM,GAAG,SAAS,CAAC;AAGvB,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC;KACb,IAAI,CAAC,UAAC,GAAG;IACN,IAAI,MAAM,GAAY,GAAG,CAAC,IAAI,CAAC;IAC/B,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC;IAClB,OAAO,CAAC,GAAG,CAAC,yBAAuB,KAAO,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,SAAS,CAAC;IAC7C,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AACpC,CAAC,CAAC;KACD,IAAI,CAAC,UAAC,GAAG;IACN,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAC3C,MAAM,CAAC,MAAM,CAAC,iBAAiB,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC;AACjE,CAAC,CAAC;KACD,IAAI,CAAC,UAAC,GAAG;IACN,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAC3C,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE,CAAC,gBAAgB,CAAC,YAAY,CAAC,CAAC,CAAC;AAClF,CAAC,CAAC;KACD,IAAI,CAAC,UAAC,GAAG;IACN,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;IAC9B,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;AACpC,CAAC,CAAC;KACD,IAAI,CAAC,UAAC,GAAG;IACN,OAAO,CAAC,GAAG,CAAC,iBAAiB,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;IACjE,OAAO,CAAC,GAAG,CAAC,aAAa,EAAE,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IACvD,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,OAAO,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IACpE,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC9B,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,IAAI,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC;QAChD,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;IAC7C,CAAC;AACL,CAAC,CAAC;KACD,KAAK,CAAC,UAAC,GAAQ;IACZ,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,QAAQ,GAAG,CAAC,CAAC;AACjB,CAAC,CAAC;KACD,IAAI,CAAC;IACF,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AACnC,CAAC,CAAC;KACD,IAAI,CAAC,UAAC,GAAG;IACN,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IAC3B,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC3B,CAAC,CAAC,CAAC"} \ No newline at end of file +{"version":3,"file":"client.js","sourceRoot":"","sources":["client.ts"],"names":[],"mappings":";AAAA,IAAO,GAAG,WAAW,OAAO,CAAC,CAAC;AAC9B,IAAO,EAAE,WAAW,IAAI,CAAC,CAAC;AAG1B,mBAAmB,OAAY,EAAE,OAAY;IACzC,IAAI,CAAC,GAAG,OAAO,CAAC;IAChB,IAAI,CAAC,GAAG,OAAO,CAAC;IAChB,IAAI,QAAQ,GAAY,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC;IACzE,IAAI,MAAM,GAAY,CAAC,OAAO,CAAC,KAAK,SAAS,IAAI,OAAO,CAAC,KAAK,SAAS,CAAC,CAAC;IACzE,IAAI,QAAQ,GAAY,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC;IAEzE,EAAE,CAAC,CAAC,CAAC,YAAY,KAAK,IAAI,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC;QAC3C,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAChC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;gBACzB,MAAM,CAAC,KAAK,CAAC;YACjB,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,CAAC;IAChB,CAAC;IAAC,IAAI,CAAC,EAAE,CAAC,CAAC,QAAQ,IAAI,MAAM,IAAI,QAAQ,CAAC,CAAC,CAAC;QACxC,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC;IACnB,CAAC;IAAC,IAAI,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC;QACxD,GAAG,CAAC,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;YAChB,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;gBAC7B,MAAM,CAAC,KAAK,CAAC;YACjB,CAAC;QACL,CAAC;QACD,MAAM,CAAC,IAAI,CAAC;IAChB,CAAC;IAAC,IAAI,CAAC,CAAC;QACJ,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC;IACnB,CAAC;AACL,CAAC;AAED,IAAI,MAAM,GAAG,IAAI,GAAG,CAAC,MAAM,EAAE,CAAC;AAC9B,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,aAAa,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC;AAG3D,IAAI,IAAI,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,CAAC;AACzB,IAAI,CAAC,EAAE,GAAG,KAAK,CAAC;AAChB,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;AAEvB,IAAI,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,CAAC;AACxB,GAAG,CAAC,IAAI,GAAG,kBAAkB,CAAC;AAC9B,GAAG,CAAC,EAAE,GAAG,KAAK,CAAC;AACf,GAAG,CAAC,SAAS,GAAG,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC;AAC/C,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC;AAElB,IAAI,KAAU,CAAC;AAEf,IAAI,QAAQ,GAAG,CAAC,CAAC;AAGjB,IAAI,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AAC/B,IAAI,UAAU,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;AACjC,IAAI,gBAAgB,GAAG,UAAU,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC;AAC9D,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;AACzC,IAAI,aAAa,GAAG;IACI,IAAI,EAAE,GAAG,CAAC,EAAE;IACZ,UAAU,EAAE;QACI,IAAI,EAAE,KAAK;QACX,MAAM,EAAE,eAAe;KAC1B;IACb,MAAM,EAAE,GAAG,CAAC,IAAI;IAChB,WAAW,EAAE,GAAG,CAAC,SAAS;IAC1B,MAAM,EAAE;QACI;YACI,IAAI,EAAE,KAAK;YACX,MAAM,EAAE,UAAU;SACrB;KACJ;IACT,QAAQ,EAAE,WAAW;CACxB,CAAC;AACtB,IAAI,eAAe,GAAG,gBAAgB,CAAC,WAAW,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;AAEzE,IAAI,OAAO,GAAY,eAAe,YAAY,UAAU,CAAC,GAAG,CAAC;AACjE,IAAI,QAAQ,GAAY,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,YAAY,UAAU,CAAC,GAAG,CAAC;AAC1E,IAAI,YAAY,GAAY,eAAe,CAAC,QAAQ,YAAY,UAAU,CAAC,QAAQ,CAAC;AAEpF,IAAI,MAAM,GAAG,EAAE,CAAC;AAChB,GAAG,CAAC,CAAC,IAAI,GAAG,IAAI,eAAe,CAAC,CAAC,CAAC;IAC9B,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;IACjB,MAAM,CAAC,GAAG,CAAC,CAAC,WAAW,CAAC,GAAG,SAAS,CAAC,eAAe,CAAC,GAAG,CAAC,EAAE,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC;IAC/E,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;IACzC,MAAM,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC;AAC/C,CAAC;AACD,IAAI,YAAY,GAAY,OAAO,IAAI,QAAQ,IAAI,YAAY,CAAC;AAEhE,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC;IAChB,QAAQ,GAAG,CAAC,CAAC;IACb,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;IAC1C,OAAO,CAAC,GAAG,CAAC,oBAAoB,EAAE,QAAQ,CAAC,CAAC;IAC5C,OAAO,CAAC,GAAG,CAAC,wBAAwB,EAAE,YAAY,CAAC,CAAC;AACxD,CAAC;AAED,GAAG,CAAC,CAAC,IAAI,GAAG,IAAI,MAAM,CAAC,CAAC,CAAC;IACrB,IAAI,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;IACxB,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;QACtB,QAAQ,GAAG,CAAC,CAAC;QACb,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,aAAa,EAAC,UAAU,EACb,KAAK,CAAC,IAAI,CAAC,EAAE,cAAc,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC9E,CAAC;AACL,CAAC;AAED,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;AAGtC,IAAI,QAAQ,GAAG,IAAI,GAAG,CAAC,QAAQ,EAAE,CAAC;AAClC,QAAQ,CAAC,EAAE,GAAG,KAAK,CAAC;AACpB,QAAQ,CAAC,IAAI,GAAG,eAAe,CAAC;AAChC,GAAG,CAAC,QAAQ,GAAG,QAAQ,CAAC;AACxB,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,SAAS,CAAC;AAE1C,IAAI,gBAAgB,GAAG,gBAAgB,CAAC,SAAS,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;AAC9D,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,gBAAgB,EAAE,aAAa,CAAC,CAAC,CAAC,CAAC;IAC9C,QAAQ,GAAG,CAAC,CAAC;IACb,OAAO,CAAC,GAAG,CAAC,uCAAuC,EAAE,gBAAgB,EACzB,cAAc,EAAE,aAAa,CAAC,CAAC;AAC/E,CAAC;AAGD,GAAG,CAAC,QAAQ,GAAG,SAAS,CAAC;AACzB,GAAG,CAAC,MAAM,GAAG,SAAS,CAAC;AAGvB,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC;KACb,IAAI,CAAC,UAAC,GAAG;IACN,IAAI,MAAM,GAAY,GAAG,CAAC,IAAI,CAAC;IAC/B,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC;IAClB,OAAO,CAAC,GAAG,CAAC,yBAAuB,KAAO,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,SAAS,CAAC;IAC7C,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AACpC,CAAC,CAAC;KACD,IAAI,CAAC,UAAC,GAAG;IACN,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAC3C,MAAM,CAAC,MAAM,CAAC,iBAAiB,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC;AACjE,CAAC,CAAC;KACD,IAAI,CAAC,UAAC,GAAG;IACN,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAC3C,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE,CAAC,YAAY,CAAC,YAAY,CAAC,CAAC,CAAC;AAC9E,CAAC,CAAC;KACD,IAAI,CAAC,UAAC,GAAG;IACN,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;IAC9B,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;AACpC,CAAC,CAAC;KACD,IAAI,CAAC,UAAC,GAAG;IACN,OAAO,CAAC,GAAG,CAAC,iBAAiB,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;IAC9D,OAAO,CAAC,GAAG,CAAC,aAAa,EAAE,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IACvD,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,OAAO,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IACpE,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACjC,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,IAAI,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC;QAChD,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;IAC7C,CAAC;AACL,CAAC,CAAC;KACD,KAAK,CAAC,UAAC,GAAQ;IACZ,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,QAAQ,GAAG,CAAC,CAAC;AACjB,CAAC,CAAC;KACD,IAAI,CAAC;IACF,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AACnC,CAAC,CAAC;KACD,IAAI,CAAC,UAAC,GAAG;IACN,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IAC3B,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC3B,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/npm/package-lock.json b/samples/client/petstore/typescript-node/npm/package-lock.json new file mode 100644 index 00000000000..f68b69830ad --- /dev/null +++ b/samples/client/petstore/typescript-node/npm/package-lock.json @@ -0,0 +1,1572 @@ +{ + "name": "@swagger/angular2-typescript-petstore", + "version": "0.0.1-SNAPSHOT.201605241654", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", + "dev": true + }, + "agent-base": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-2.1.1.tgz", + "integrity": "sha1-1t4Q1a9hMtW9aSQn1G/FOFOQlMc=", + "dev": true, + "requires": { + "extend": "3.0.1", + "semver": "5.0.3" + } + }, + "ajv": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-5.3.0.tgz", + "integrity": "sha1-RBT/dKUIecII7l/cgm4ywwNUnto=", + "requires": { + "co": "4.6.0", + "fast-deep-equal": "1.0.0", + "fast-json-stable-stringify": "2.0.0", + "json-schema-traverse": "0.3.1" + } + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha1-q8av7tzqUugJzcA3au0845Y10X8=", + "dev": true + }, + "archy": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/archy/-/archy-1.0.0.tgz", + "integrity": "sha1-+cjBN1fMHde8N5rHeyxipcKGjEA=", + "dev": true + }, + "array-uniq": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", + "integrity": "sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=", + "dev": true + }, + "arrify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", + "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", + "dev": true + }, + "asn1": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.3.tgz", + "integrity": "sha1-2sh4dxPJlmhJ/IGAd36+nB3fO4Y=" + }, + "assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=" + }, + "async": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/async/-/async-0.9.2.tgz", + "integrity": "sha1-rqdNXmHB+JlhO/ZL2mbUx48v0X0=", + "dev": true + }, + "asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=" + }, + "aws-sign2": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", + "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=" + }, + "aws4": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.6.0.tgz", + "integrity": "sha1-g+9cqGCysy5KDe7e6MdxudtXRx4=" + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "bcrypt-pbkdf": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.1.tgz", + "integrity": "sha1-Y7xdy2EzG5K8Bf1SiVPDNGKgb40=", + "optional": true, + "requires": { + "tweetnacl": "0.14.5" + } + }, + "bluebird": { + "version": "3.5.1", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.1.tgz", + "integrity": "sha512-MKiLiV+I1AA596t9w1sQJ8jkiSr5+ZKi0WKrYGUn6d1Fx+Ij4tIj+m2WMQSGczs5jZVxV339chE8iwk6F64wjA==" + }, + "boom": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/boom/-/boom-4.3.1.tgz", + "integrity": "sha1-T4owBctKfjiJ90kDD9JbluAdLjE=", + "requires": { + "hoek": "4.2.0" + } + }, + "boxen": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/boxen/-/boxen-0.3.1.tgz", + "integrity": "sha1-p9iYJDrmIvertrtgTXQKdsalRhs=", + "dev": true, + "requires": { + "chalk": "1.1.3", + "filled-array": "1.1.0", + "object-assign": "4.1.1", + "repeating": "2.0.1", + "string-width": "1.0.2", + "widest-line": "1.0.0" + } + }, + "brace-expansion": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.8.tgz", + "integrity": "sha1-wHshHHyVLsH479Uad+8NHTmQopI=", + "dev": true, + "requires": { + "balanced-match": "1.0.0", + "concat-map": "0.0.1" + } + }, + "capture-stack-trace": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/capture-stack-trace/-/capture-stack-trace-1.0.0.tgz", + "integrity": "sha1-Sm+gc5nCa7pH8LJJa00PtAjFVQ0=", + "dev": true + }, + "caseless": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=" + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "2.2.1", + "escape-string-regexp": "1.0.5", + "has-ansi": "2.0.0", + "strip-ansi": "3.0.1", + "supports-color": "2.0.0" + } + }, + "clone": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.3.tgz", + "integrity": "sha1-KY1+IjFmD0DAA8LtMUDezz9TCF8=", + "dev": true + }, + "co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=" + }, + "code-point-at": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", + "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=", + "dev": true + }, + "columnify": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/columnify/-/columnify-1.5.4.tgz", + "integrity": "sha1-Rzfd8ce2mop8NAVweC6UfuyOeLs=", + "dev": true, + "requires": { + "strip-ansi": "3.0.1", + "wcwidth": "1.0.1" + } + }, + "combined-stream": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.5.tgz", + "integrity": "sha1-k4NwpXtKUd6ix3wV1cX9+JUWQAk=", + "requires": { + "delayed-stream": "1.0.0" + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "concat-stream": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.0.tgz", + "integrity": "sha1-CqxmL9Ur54lk1VMvaUeE5wEQrPc=", + "dev": true, + "requires": { + "inherits": "2.0.3", + "readable-stream": "2.3.3", + "typedarray": "0.0.6" + } + }, + "configstore": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/configstore/-/configstore-2.1.0.tgz", + "integrity": "sha1-c3o6cDbpiGECqmCZ5HuzOrGroaE=", + "dev": true, + "requires": { + "dot-prop": "3.0.0", + "graceful-fs": "4.1.11", + "mkdirp": "0.5.1", + "object-assign": "4.1.1", + "os-tmpdir": "1.0.2", + "osenv": "0.1.4", + "uuid": "2.0.3", + "write-file-atomic": "1.3.4", + "xdg-basedir": "2.0.0" + }, + "dependencies": { + "uuid": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-2.0.3.tgz", + "integrity": "sha1-Z+LoY3lyFVMN/zGOW/nc6/1Hsho=", + "dev": true + } + } + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" + }, + "create-error-class": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/create-error-class/-/create-error-class-3.0.2.tgz", + "integrity": "sha1-Br56vvlHo/FKMP1hBnHUAbyot7Y=", + "dev": true, + "requires": { + "capture-stack-trace": "1.0.0" + } + }, + "cryptiles": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/cryptiles/-/cryptiles-3.1.2.tgz", + "integrity": "sha1-qJ+7Ig9c4l7FboxKqKT9e1sNKf4=", + "requires": { + "boom": "5.2.0" + }, + "dependencies": { + "boom": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/boom/-/boom-5.2.0.tgz", + "integrity": "sha512-Z5BTk6ZRe4tXXQlkqftmsAUANpXmuwlsF5Oov8ThoMbQRzdGTA1ngYRW160GexgOgjsFOKJz0LYhoNi+2AMBUw==", + "requires": { + "hoek": "4.2.0" + } + } + } + }, + "dashdash": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", + "requires": { + "assert-plus": "1.0.0" + } + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-extend": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.4.2.tgz", + "integrity": "sha1-SLaZwn4zS/ifEIkr5DL25MfTSn8=", + "dev": true + }, + "defaults": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.3.tgz", + "integrity": "sha1-xlYFHpgX2f8I7YgUd/P+QBnz730=", + "dev": true, + "requires": { + "clone": "1.0.3" + } + }, + "delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=" + }, + "detect-indent": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz", + "integrity": "sha1-920GQ1LN9Docts5hnE7jqUdd4gg=", + "dev": true, + "requires": { + "repeating": "2.0.1" + } + }, + "dot-prop": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-3.0.0.tgz", + "integrity": "sha1-G3CK8JSknJoOfbyteQq6U52sEXc=", + "dev": true, + "requires": { + "is-obj": "1.0.1" + } + }, + "duplexer2": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", + "integrity": "sha1-ixLauHjA1p4+eJEFFmKjL8a93ME=", + "dev": true, + "requires": { + "readable-stream": "2.3.3" + } + }, + "ecc-jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz", + "integrity": "sha1-D8c6ntXw1Tw4GTOYUj735UN3dQU=", + "optional": true, + "requires": { + "jsbn": "0.1.1" + } + }, + "error-ex": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.1.tgz", + "integrity": "sha1-+FWobOYa3E6GIcPNoh56dhLDqNw=", + "dev": true, + "requires": { + "is-arrayish": "0.2.1" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "extend": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz", + "integrity": "sha1-p1Xqe8Gt/MWjHOfnYtuq3F5jZEQ=" + }, + "extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=" + }, + "fast-deep-equal": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-1.0.0.tgz", + "integrity": "sha1-liVqO8l1WV6zbYLpkp0GDYk0Of8=" + }, + "fast-json-stable-stringify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", + "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=" + }, + "filled-array": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/filled-array/-/filled-array-1.1.0.tgz", + "integrity": "sha1-w8T2xmO5I0WamqKZEtLQMfFQf4Q=", + "dev": true + }, + "forever-agent": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", + "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=" + }, + "form-data": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.1.tgz", + "integrity": "sha1-b7lPvXGIUwbXPRXMSX/kzE7NRL8=", + "requires": { + "asynckit": "0.4.0", + "combined-stream": "1.0.5", + "mime-types": "2.1.17" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true + }, + "getpass": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", + "requires": { + "assert-plus": "1.0.0" + } + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "1.0.0", + "inflight": "1.0.6", + "inherits": "2.0.3", + "minimatch": "3.0.4", + "once": "1.4.0", + "path-is-absolute": "1.0.1" + } + }, + "got": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/got/-/got-5.7.1.tgz", + "integrity": "sha1-X4FjWmHkplifGAVp6k44FoClHzU=", + "dev": true, + "requires": { + "create-error-class": "3.0.2", + "duplexer2": "0.1.4", + "is-redirect": "1.0.0", + "is-retry-allowed": "1.1.0", + "is-stream": "1.1.0", + "lowercase-keys": "1.0.0", + "node-status-codes": "1.0.0", + "object-assign": "4.1.1", + "parse-json": "2.2.0", + "pinkie-promise": "2.0.1", + "read-all-stream": "3.1.0", + "readable-stream": "2.3.3", + "timed-out": "3.1.3", + "unzip-response": "1.0.2", + "url-parse-lax": "1.0.0" + } + }, + "graceful-fs": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", + "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "dev": true + }, + "har-schema": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", + "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=" + }, + "har-validator": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.0.3.tgz", + "integrity": "sha1-ukAsJmGU8VlW7xXg/PJCmT9qff0=", + "requires": { + "ajv": "5.3.0", + "har-schema": "2.0.0" + } + }, + "has": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.1.tgz", + "integrity": "sha1-hGFzP1OLCDfJNh45qauelwTcLyg=", + "dev": true, + "requires": { + "function-bind": "1.1.1" + } + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "hawk": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/hawk/-/hawk-6.0.2.tgz", + "integrity": "sha512-miowhl2+U7Qle4vdLqDdPt9m09K6yZhkLDTWGoUiUzrQCn+mHHSmfJgAyGaLRZbPmTqfFFjRV1QWCW0VWUJBbQ==", + "requires": { + "boom": "4.3.1", + "cryptiles": "3.1.2", + "hoek": "4.2.0", + "sntp": "2.1.0" + } + }, + "hoek": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/hoek/-/hoek-4.2.0.tgz", + "integrity": "sha512-v0XCLxICi9nPfYrS9RL8HbYnXi9obYAeLbSP00BmnZwCK9+Ih9WOjoZ8YoHCoav2csqn4FOz4Orldsy2dmDwmQ==" + }, + "http-proxy-agent": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-1.0.0.tgz", + "integrity": "sha1-zBzjjkU7+YSg93AtLdWcc9CBKEo=", + "dev": true, + "requires": { + "agent-base": "2.1.1", + "debug": "2.6.9", + "extend": "3.0.1" + } + }, + "http-signature": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", + "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", + "requires": { + "assert-plus": "1.0.0", + "jsprim": "1.4.1", + "sshpk": "1.13.1" + } + }, + "https-proxy-agent": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-1.0.0.tgz", + "integrity": "sha1-NffabEjOTdv6JkiRrFk+5f+GceY=", + "dev": true, + "requires": { + "agent-base": "2.1.1", + "debug": "2.6.9", + "extend": "3.0.1" + } + }, + "imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "1.4.0", + "wrappy": "1.0.2" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "ini": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.4.tgz", + "integrity": "sha1-BTfLedr1m1mhpRff9wbIbsA5Fi4=", + "dev": true + }, + "invariant": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.2.tgz", + "integrity": "sha1-nh9WrArNtr8wMwbzOL47IErmA2A=", + "dev": true, + "requires": { + "loose-envify": "1.3.1" + } + }, + "is-absolute": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/is-absolute/-/is-absolute-0.2.6.tgz", + "integrity": "sha1-IN5p89uULvLYe5wto28XIjWxtes=", + "dev": true, + "requires": { + "is-relative": "0.2.1", + "is-windows": "0.2.0" + } + }, + "is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", + "dev": true + }, + "is-finite": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", + "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", + "dev": true, + "requires": { + "number-is-nan": "1.0.1" + } + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", + "dev": true, + "requires": { + "number-is-nan": "1.0.1" + } + }, + "is-npm": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-npm/-/is-npm-1.0.0.tgz", + "integrity": "sha1-8vtjpl5JBbQGyGBydloaTceTufQ=", + "dev": true + }, + "is-obj": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", + "integrity": "sha1-PkcprB9f3gJc19g6iW2rn09n2w8=", + "dev": true + }, + "is-plain-obj": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-1.1.0.tgz", + "integrity": "sha1-caUMhCnfync8kqOQpKA7OfzVHT4=", + "dev": true + }, + "is-redirect": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-redirect/-/is-redirect-1.0.0.tgz", + "integrity": "sha1-HQPd7VO9jbDzDCbk+V02/HyH3CQ=", + "dev": true + }, + "is-relative": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-relative/-/is-relative-0.2.1.tgz", + "integrity": "sha1-0n9MfVFtF1+2ENuEu+7yPDvJeqU=", + "dev": true, + "requires": { + "is-unc-path": "0.1.2" + } + }, + "is-retry-allowed": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-1.1.0.tgz", + "integrity": "sha1-EaBgVotnM5REAz0BJaYaINVk+zQ=", + "dev": true + }, + "is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", + "dev": true + }, + "is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=" + }, + "is-unc-path": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/is-unc-path/-/is-unc-path-0.1.2.tgz", + "integrity": "sha1-arBTpyVzwQJQ/0FqOBTDUXivObk=", + "dev": true, + "requires": { + "unc-path-regex": "0.1.2" + } + }, + "is-utf8": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", + "integrity": "sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI=", + "dev": true + }, + "is-windows": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-0.2.0.tgz", + "integrity": "sha1-3hqm1j6indJIc3tp8f+LgALSEIw=", + "dev": true + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=" + }, + "js-tokens": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", + "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", + "dev": true + }, + "jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", + "optional": true + }, + "json-schema": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", + "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=" + }, + "json-schema-traverse": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz", + "integrity": "sha1-NJptRMU6Ud6JtAgFxdXlm0F9M0A=" + }, + "json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" + }, + "jsprim": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", + "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", + "requires": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.2.3", + "verror": "1.10.0" + } + }, + "latest-version": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/latest-version/-/latest-version-2.0.0.tgz", + "integrity": "sha1-VvjWE5YghHuAF/jx9NeOIRMkFos=", + "dev": true, + "requires": { + "package-json": "2.4.0" + } + }, + "listify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/listify/-/listify-1.0.0.tgz", + "integrity": "sha1-A8p7otFQ1CZ3c/dOV1WNEFPSvuM=", + "dev": true + }, + "lockfile": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/lockfile/-/lockfile-1.0.3.tgz", + "integrity": "sha1-Jjj8OaAzHpysGgS3F5mTHJxQ33k=", + "dev": true + }, + "loose-envify": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", + "integrity": "sha1-0aitM/qc4OcT1l/dCsi3SNR4yEg=", + "dev": true, + "requires": { + "js-tokens": "3.0.2" + } + }, + "lowercase-keys": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-1.0.0.tgz", + "integrity": "sha1-TjNms55/VFfjXxMkvfb4jQv8cwY=", + "dev": true + }, + "make-error": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.0.tgz", + "integrity": "sha1-Uq06M5zPEM5itAQLcI/nByRLi5Y=", + "dev": true + }, + "make-error-cause": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/make-error-cause/-/make-error-cause-1.2.2.tgz", + "integrity": "sha1-3wOI/NCzeBbf8KX7gQiTl3fcvJ0=", + "dev": true, + "requires": { + "make-error": "1.3.0" + } + }, + "methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=", + "dev": true + }, + "mime-db": { + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.30.0.tgz", + "integrity": "sha1-dMZD2i3Z1qRTmZY0ZbJtXKfXHwE=" + }, + "mime-types": { + "version": "2.1.17", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.17.tgz", + "integrity": "sha1-Cdejk/A+mVp5+K+Fe3Cp4KsWVXo=", + "requires": { + "mime-db": "1.30.0" + } + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "1.1.8" + } + }, + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "dev": true, + "requires": { + "minimist": "0.0.8" + }, + "dependencies": { + "minimist": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "dev": true + } + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "node-status-codes": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-status-codes/-/node-status-codes-1.0.0.tgz", + "integrity": "sha1-WuVUHQJGRdMqWPzdyc7s6nrjrC8=", + "dev": true + }, + "nopt": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-1.0.10.tgz", + "integrity": "sha1-bd0hvSoxQXuScn3Vhfim83YI6+4=", + "dev": true, + "requires": { + "abbrev": "1.1.1" + } + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", + "dev": true + }, + "oauth-sign": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.8.2.tgz", + "integrity": "sha1-Rqarfwrq2N6unsBWV4C31O/rnUM=" + }, + "object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "dev": true + }, + "object.pick": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz", + "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", + "dev": true, + "requires": { + "isobject": "3.0.1" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1.0.2" + } + }, + "os-homedir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", + "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=", + "dev": true + }, + "os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", + "dev": true + }, + "osenv": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/osenv/-/osenv-0.1.4.tgz", + "integrity": "sha1-Qv5tWVPfBsgGS+bxdsPQWqqjRkQ=", + "dev": true, + "requires": { + "os-homedir": "1.0.2", + "os-tmpdir": "1.0.2" + } + }, + "package-json": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/package-json/-/package-json-2.4.0.tgz", + "integrity": "sha1-DRW9Z9HLvduyyiIv8u24a8sxqLs=", + "dev": true, + "requires": { + "got": "5.7.1", + "registry-auth-token": "3.3.1", + "registry-url": "3.1.0", + "semver": "5.4.1" + }, + "dependencies": { + "semver": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.4.1.tgz", + "integrity": "sha512-WfG/X9+oATh81XtllIo/I8gOiY9EXRdv1cQdyykeXK17YcUW3EXUAi2To4pcH6nZtJPr7ZOpM5OMyWJZm+8Rsg==", + "dev": true + } + } + }, + "parse-json": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", + "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", + "dev": true, + "requires": { + "error-ex": "1.3.1" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=" + }, + "pinkie": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", + "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", + "dev": true + }, + "pinkie-promise": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", + "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", + "dev": true, + "requires": { + "pinkie": "2.0.4" + } + }, + "popsicle": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/popsicle/-/popsicle-5.0.1.tgz", + "integrity": "sha1-lWBtmf5cEsPFmqrqKiomwsUBysY=", + "dev": true, + "requires": { + "any-promise": "1.3.0", + "arrify": "1.0.1", + "concat-stream": "1.6.0", + "form-data": "0.2.0", + "make-error-cause": "1.2.2", + "methods": "1.1.2", + "tough-cookie": "2.3.3", + "xtend": "4.0.1" + }, + "dependencies": { + "combined-stream": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-0.0.7.tgz", + "integrity": "sha1-ATfmV7qlp1QcV6w3rF/AfXO03B8=", + "dev": true, + "requires": { + "delayed-stream": "0.0.5" + } + }, + "delayed-stream": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-0.0.5.tgz", + "integrity": "sha1-1LH0OpPoKW3+AmlPRoC8N6MTxz8=", + "dev": true + }, + "form-data": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-0.2.0.tgz", + "integrity": "sha1-Jvi8JtpkQOKZy9z7aQNcT3em5GY=", + "dev": true, + "requires": { + "async": "0.9.2", + "combined-stream": "0.0.7", + "mime-types": "2.0.14" + } + }, + "mime-db": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.12.0.tgz", + "integrity": "sha1-PQxjGA9FjrENMlqqN9fFiuMS6dc=", + "dev": true + }, + "mime-types": { + "version": "2.0.14", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.0.14.tgz", + "integrity": "sha1-MQ4VnbI+B3+Lsit0jav6SVcUCqY=", + "dev": true, + "requires": { + "mime-db": "1.12.0" + } + } + } + }, + "popsicle-proxy-agent": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/popsicle-proxy-agent/-/popsicle-proxy-agent-1.0.0.tgz", + "integrity": "sha1-W4jV0SU6CmAcummGjLpvXbxdCCk=", + "dev": true, + "requires": { + "http-proxy-agent": "1.0.0", + "https-proxy-agent": "1.0.0" + } + }, + "popsicle-retry": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/popsicle-retry/-/popsicle-retry-2.0.0.tgz", + "integrity": "sha1-oLRFWMe1BktQ5KvQoFmhmbatGl8=", + "dev": true, + "requires": { + "any-promise": "1.3.0" + } + }, + "popsicle-status": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/popsicle-status/-/popsicle-status-1.0.2.tgz", + "integrity": "sha1-oCQWcnWAckQS4J0TA/BnzqPKDhM=", + "dev": true + }, + "prepend-http": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", + "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=", + "dev": true + }, + "process-nextick-args": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.7.tgz", + "integrity": "sha1-FQ4gt1ZZCtP5EJPyWk8q2L/zC6M=", + "dev": true + }, + "promise-finally": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/promise-finally/-/promise-finally-2.2.1.tgz", + "integrity": "sha1-ImFsS6kCkW6Yi9RsVNfKoIkQzXc=", + "dev": true, + "requires": { + "any-promise": "1.3.0" + } + }, + "punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=" + }, + "qs": { + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.1.tgz", + "integrity": "sha512-eRzhrN1WSINYCDCbrz796z37LOe3m5tmW7RQf6oBntukAG1nmovJvhnwHHRMAfeoItc1m2Hk02WER2aQ/iqs+A==" + }, + "rc": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.2.tgz", + "integrity": "sha1-2M6ctX6NZNnHut2YdsfDTL48cHc=", + "dev": true, + "requires": { + "deep-extend": "0.4.2", + "ini": "1.3.4", + "minimist": "1.2.0", + "strip-json-comments": "2.0.1" + } + }, + "read-all-stream": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/read-all-stream/-/read-all-stream-3.1.0.tgz", + "integrity": "sha1-NcPhd/IHjveJ7kv6+kNzB06u9Po=", + "dev": true, + "requires": { + "pinkie-promise": "2.0.1", + "readable-stream": "2.3.3" + } + }, + "readable-stream": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.3.tgz", + "integrity": "sha512-m+qzzcn7KUxEmd1gMbchF+Y2eIUbieUaxkWtptyHywrX0rE8QEYqPC07Vuy4Wm32/xE16NcdBctb8S0Xe/5IeQ==", + "dev": true, + "requires": { + "core-util-is": "1.0.2", + "inherits": "2.0.3", + "isarray": "1.0.0", + "process-nextick-args": "1.0.7", + "safe-buffer": "5.1.1", + "string_decoder": "1.0.3", + "util-deprecate": "1.0.2" + } + }, + "registry-auth-token": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.1.tgz", + "integrity": "sha1-+w0yie4Nmtosu1KvXf5mywcNMAY=", + "dev": true, + "requires": { + "rc": "1.2.2", + "safe-buffer": "5.1.1" + } + }, + "registry-url": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/registry-url/-/registry-url-3.1.0.tgz", + "integrity": "sha1-PU74cPc93h138M+aOBQyRE4XSUI=", + "dev": true, + "requires": { + "rc": "1.2.2" + } + }, + "repeating": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", + "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", + "dev": true, + "requires": { + "is-finite": "1.0.2" + } + }, + "request": { + "version": "2.83.0", + "resolved": "https://registry.npmjs.org/request/-/request-2.83.0.tgz", + "integrity": "sha512-lR3gD69osqm6EYLk9wB/G1W/laGWjzH90t1vEa2xuxHD5KUrSzp9pUSfTm+YC5Nxt2T8nMPEvKlhbQayU7bgFw==", + "requires": { + "aws-sign2": "0.7.0", + "aws4": "1.6.0", + "caseless": "0.12.0", + "combined-stream": "1.0.5", + "extend": "3.0.1", + "forever-agent": "0.6.1", + "form-data": "2.3.1", + "har-validator": "5.0.3", + "hawk": "6.0.2", + "http-signature": "1.2.0", + "is-typedarray": "1.0.0", + "isstream": "0.1.2", + "json-stringify-safe": "5.0.1", + "mime-types": "2.1.17", + "oauth-sign": "0.8.2", + "performance-now": "2.1.0", + "qs": "6.5.1", + "safe-buffer": "5.1.1", + "stringstream": "0.0.5", + "tough-cookie": "2.3.3", + "tunnel-agent": "0.6.0", + "uuid": "3.1.0" + } + }, + "rewire": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/rewire/-/rewire-2.5.2.tgz", + "integrity": "sha1-ZCfee3/u+n02QBUH62SlOFvFjcc=" + }, + "rimraf": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.2.tgz", + "integrity": "sha512-lreewLK/BlghmxtfH36YYVg1i8IAce4TI7oao75I1g245+6BctqTVQiBP3YUJ9C6DQOXJmkYR9X9fCLtCOJc5w==", + "dev": true, + "requires": { + "glob": "7.1.2" + } + }, + "safe-buffer": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", + "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==" + }, + "semver": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.0.3.tgz", + "integrity": "sha1-d0Zt5YnNXTyV8TiqeLxWmjy10no=", + "dev": true + }, + "semver-diff": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/semver-diff/-/semver-diff-2.1.0.tgz", + "integrity": "sha1-S7uEN8jTfksM8aaP1ybsbWRdbTY=", + "dev": true, + "requires": { + "semver": "5.0.3" + } + }, + "slide": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/slide/-/slide-1.1.6.tgz", + "integrity": "sha1-VusCfWW00tzmyy4tMsTUr8nh1wc=", + "dev": true + }, + "sntp": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/sntp/-/sntp-2.1.0.tgz", + "integrity": "sha512-FL1b58BDrqS3A11lJ0zEdnJ3UOKqVxawAkF3k7F0CVN7VQ34aZrV+G8BZ1WC9ZL7NyrwsW0oviwsWDgRuVYtJg==", + "requires": { + "hoek": "4.2.0" + } + }, + "sort-keys": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/sort-keys/-/sort-keys-1.1.2.tgz", + "integrity": "sha1-RBttTTRnmPG05J6JIK37oOVD+a0=", + "dev": true, + "requires": { + "is-plain-obj": "1.1.0" + } + }, + "sshpk": { + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.13.1.tgz", + "integrity": "sha1-US322mKHFEMW3EwY/hzx2UBzm+M=", + "requires": { + "asn1": "0.2.3", + "assert-plus": "1.0.0", + "bcrypt-pbkdf": "1.0.1", + "dashdash": "1.14.1", + "ecc-jsbn": "0.1.1", + "getpass": "0.1.7", + "jsbn": "0.1.1", + "tweetnacl": "0.14.5" + } + }, + "string-template": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/string-template/-/string-template-1.0.0.tgz", + "integrity": "sha1-np8iM9wA8hhxjsN5oopWc+zKi5Y=", + "dev": true + }, + "string-width": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "dev": true, + "requires": { + "code-point-at": "1.1.0", + "is-fullwidth-code-point": "1.0.0", + "strip-ansi": "3.0.1" + } + }, + "string_decoder": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz", + "integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==", + "dev": true, + "requires": { + "safe-buffer": "5.1.1" + } + }, + "stringstream": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/stringstream/-/stringstream-0.0.5.tgz", + "integrity": "sha1-TkhM1N5aC7vuGORjB3EKioFiGHg=" + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "strip-bom": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", + "integrity": "sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=", + "dev": true, + "requires": { + "is-utf8": "0.2.1" + } + }, + "strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", + "dev": true + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + }, + "thenify": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.0.tgz", + "integrity": "sha1-5p44obq+lpsBCCB5eLn2K4hgSDk=", + "dev": true, + "requires": { + "any-promise": "1.3.0" + } + }, + "throat": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/throat/-/throat-2.0.2.tgz", + "integrity": "sha1-qfzoCLaeEzpjJZB4DzQsMKYkmwI=", + "dev": true + }, + "timed-out": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/timed-out/-/timed-out-3.1.3.tgz", + "integrity": "sha1-lYYL/MXHbCd/j4Mm/Q9bLiDrohc=", + "dev": true + }, + "touch": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/touch/-/touch-1.0.0.tgz", + "integrity": "sha1-RJy+LbrlqMgDjjDXH6D/RklHxN4=", + "dev": true, + "requires": { + "nopt": "1.0.10" + } + }, + "tough-cookie": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.3.3.tgz", + "integrity": "sha1-C2GKVWW23qkL80JdBNVe3EdadWE=", + "requires": { + "punycode": "1.4.1" + } + }, + "tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "requires": { + "safe-buffer": "5.1.1" + } + }, + "tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=", + "optional": true + }, + "typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", + "dev": true + }, + "typescript": { + "version": "1.8.10", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-1.8.10.tgz", + "integrity": "sha1-tHXW4N/wv1DyluXKbvn7tccyDx4=", + "dev": true + }, + "typings": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/typings/-/typings-0.8.1.tgz", + "integrity": "sha1-lP3uTK0MEoM9h2YMXMH6YtriHaQ=", + "dev": true, + "requires": { + "any-promise": "1.3.0", + "archy": "1.0.0", + "bluebird": "3.5.1", + "chalk": "1.1.3", + "columnify": "1.5.4", + "listify": "1.0.0", + "minimist": "1.2.0", + "typings-core": "0.3.1", + "update-notifier": "0.6.3", + "wordwrap": "1.0.0", + "xtend": "4.0.1" + } + }, + "typings-core": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/typings-core/-/typings-core-0.3.1.tgz", + "integrity": "sha1-v/0mjjFVyeDL+7mXUCQMCeUf3sY=", + "dev": true, + "requires": { + "any-promise": "1.3.0", + "array-uniq": "1.0.3", + "configstore": "2.1.0", + "debug": "2.6.9", + "detect-indent": "4.0.0", + "graceful-fs": "4.1.11", + "has": "1.0.1", + "invariant": "2.2.2", + "is-absolute": "0.2.6", + "lockfile": "1.0.3", + "make-error-cause": "1.2.2", + "mkdirp": "0.5.1", + "object.pick": "1.3.0", + "parse-json": "2.2.0", + "popsicle": "5.0.1", + "popsicle-proxy-agent": "1.0.0", + "popsicle-retry": "2.0.0", + "popsicle-status": "1.0.2", + "promise-finally": "2.2.1", + "rc": "1.2.2", + "rimraf": "2.6.2", + "sort-keys": "1.1.2", + "string-template": "1.0.0", + "strip-bom": "2.0.0", + "thenify": "3.3.0", + "throat": "2.0.2", + "touch": "1.0.0", + "typescript": "1.8.10", + "xtend": "4.0.1", + "zip-object": "0.1.0" + } + }, + "unc-path-regex": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/unc-path-regex/-/unc-path-regex-0.1.2.tgz", + "integrity": "sha1-5z3T17DXxe2G+6xrCufYxqadUPo=", + "dev": true + }, + "unzip-response": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/unzip-response/-/unzip-response-1.0.2.tgz", + "integrity": "sha1-uYTwh3/AqJwsdzzB73tbIytbBv4=", + "dev": true + }, + "update-notifier": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/update-notifier/-/update-notifier-0.6.3.tgz", + "integrity": "sha1-d23sjaoT6WKjQeih2YNUMGtnrgg=", + "dev": true, + "requires": { + "boxen": "0.3.1", + "chalk": "1.1.3", + "configstore": "2.1.0", + "is-npm": "1.0.0", + "latest-version": "2.0.0", + "semver-diff": "2.1.0" + } + }, + "url-parse-lax": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/url-parse-lax/-/url-parse-lax-1.0.0.tgz", + "integrity": "sha1-evjzA2Rem9eaJy56FKxovAYJ2nM=", + "dev": true, + "requires": { + "prepend-http": "1.0.4" + } + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", + "dev": true + }, + "uuid": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.1.0.tgz", + "integrity": "sha512-DIWtzUkw04M4k3bf1IcpS2tngXEL26YUD2M0tMDUpnUrz2hgzUBlD55a4FjdLGPvfHxS6uluGWvaVEqgBcVa+g==" + }, + "verror": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", + "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", + "requires": { + "assert-plus": "1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "1.3.0" + } + }, + "wcwidth": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz", + "integrity": "sha1-8LDc+RW8X/FSivrbLA4XtTLaL+g=", + "dev": true, + "requires": { + "defaults": "1.0.3" + } + }, + "widest-line": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-1.0.0.tgz", + "integrity": "sha1-DAnIXCqUaD0Nfq+O4JfVZL8OEFw=", + "dev": true, + "requires": { + "string-width": "1.0.2" + } + }, + "wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", + "dev": true + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "write-file-atomic": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-1.3.4.tgz", + "integrity": "sha1-+Aek8LHZ6ROuekgRLmzDrxmRtF8=", + "dev": true, + "requires": { + "graceful-fs": "4.1.11", + "imurmurhash": "0.1.4", + "slide": "1.1.6" + } + }, + "xdg-basedir": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-2.0.0.tgz", + "integrity": "sha1-7byQPMOF/ARSPZZqM1UEtVBNG9I=", + "dev": true, + "requires": { + "os-homedir": "1.0.2" + } + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + }, + "zip-object": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/zip-object/-/zip-object-0.1.0.tgz", + "integrity": "sha1-waDaBMiMg3dW4khoCgP/kC7D9To=", + "dev": true + } + } +} diff --git a/samples/client/petstore/typescript-node/npm/package.json b/samples/client/petstore/typescript-node/npm/package.json index 9680fa89acb..17de827438b 100644 --- a/samples/client/petstore/typescript-node/npm/package.json +++ b/samples/client/petstore/typescript-node/npm/package.json @@ -24,4 +24,4 @@ "publishConfig": { "registry": "https://skimdb.npmjs.com/registry" } -} \ No newline at end of file +} diff --git a/samples/server/petstore/erlang-server/.swagger-codegen/VERSION b/samples/server/petstore/erlang-server/.swagger-codegen/VERSION index 7fea99011a6..f9f7450d135 100644 --- a/samples/server/petstore/erlang-server/.swagger-codegen/VERSION +++ b/samples/server/petstore/erlang-server/.swagger-codegen/VERSION @@ -1 +1 @@ -2.2.3-SNAPSHOT \ No newline at end of file +2.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/erlang-server/priv/swagger.json b/samples/server/petstore/erlang-server/priv/swagger.json index 3eef6c58413..808835928b6 100644 --- a/samples/server/petstore/erlang-server/priv/swagger.json +++ b/samples/server/petstore/erlang-server/priv/swagger.json @@ -9,7 +9,7 @@ "email" : "apiteam@swagger.io" }, "license" : { - "name" : "Apache 2.0", + "name" : "Apache-2.0", "url" : "http://www.apache.org/licenses/LICENSE-2.0.html" } }, @@ -166,7 +166,8 @@ }, "security" : [ { "petstore_auth" : [ "write:pets", "read:pets" ] - } ] + } ], + "deprecated" : true } }, "/pet/{petId}" : { @@ -683,6 +684,14 @@ }, "title" : "Pet Order", "description" : "An order for a pets from the pet store", + "example" : { + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" + }, "xml" : { "name" : "Order" } @@ -700,6 +709,10 @@ }, "title" : "Pet catehgry", "description" : "A category for a pet", + "example" : { + "name" : "name", + "id" : 6 + }, "xml" : { "name" : "Category" } @@ -737,6 +750,16 @@ }, "title" : "a User", "description" : "A User who is purchasing from the pet store", + "example" : { + "firstName" : "firstName", + "lastName" : "lastName", + "password" : "password", + "userStatus" : 6, + "phone" : "phone", + "id" : 0, + "email" : "email", + "username" : "username" + }, "xml" : { "name" : "User" } @@ -754,6 +777,10 @@ }, "title" : "Pet Tag", "description" : "A tag for a pet", + "example" : { + "name" : "name", + "id" : 1 + }, "xml" : { "name" : "Tag" } @@ -801,6 +828,23 @@ }, "title" : "a Pet", "description" : "A pet for sale in the pet store", + "example" : { + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" + }, "xml" : { "name" : "Pet" } @@ -820,7 +864,12 @@ } }, "title" : "An uploaded response", - "description" : "Describes the result of uploading an image resource" + "description" : "Describes the result of uploading an image resource", + "example" : { + "code" : 0, + "type" : "type", + "message" : "message" + } } }, "externalDocs" : { diff --git a/samples/server/petstore/erlang-server/src/swagger.app.src b/samples/server/petstore/erlang-server/src/swagger.app.src index 9016bde7219..f76b2b0a148 100644 --- a/samples/server/petstore/erlang-server/src/swagger.app.src +++ b/samples/server/petstore/erlang-server/src/swagger.app.src @@ -14,6 +14,6 @@ {env, [ ]}, {modules, []}, - {licenses, ["Apache 2.0"]}, + {licenses, ["Apache-2.0"]}, {links, []} ]}. diff --git a/samples/server/petstore/erlang-server/src/swagger_api.erl b/samples/server/petstore/erlang-server/src/swagger_api.erl index 2fbc055ad08..02e15583133 100644 --- a/samples/server/petstore/erlang-server/src/swagger_api.erl +++ b/samples/server/petstore/erlang-server/src/swagger_api.erl @@ -4,6 +4,8 @@ -export([request_param_info/2]). -export([populate_request/3]). -export([validate_response/4]). +%% exported to silence swagger complains +-export([get_value/3, validate_response_body/4]). -type operation_id() :: atom(). -type request_param() :: atom(). @@ -599,7 +601,7 @@ validate(Rule = {enum, Values}, Name, Value, _ValidatorState) -> end; validate(Rule = {max, Max}, Name, Value, _ValidatorState) -> - case Value >= Max of + case Value =< Max of true -> ok; false -> validation_error(Rule, Name) end; @@ -611,7 +613,7 @@ validate(Rule = {exclusive_max, ExclusiveMax}, Name, Value, _ValidatorState) -> end; validate(Rule = {min, Min}, Name, Value, _ValidatorState) -> - case Value =< Min of + case Value >= Min of true -> ok; false -> validation_error(Rule, Name) end; @@ -677,6 +679,8 @@ validation_error(ViolatedRule, Name) -> validation_error(ViolatedRule, Name, Info) -> throw({wrong_param, Name, ViolatedRule, Info}). +-spec get_value(body | qs_val | header | binding, Name :: any(), Req0 :: cowboy_req:req()) -> + {Value :: any(), Req :: cowboy_req:req()}. get_value(body, _Name, Req0) -> {ok, Body, Req} = cowboy_req:body(Req0), Value = prepare_body(Body), diff --git a/samples/server/petstore/erlang-server/src/swagger_pet_handler.erl b/samples/server/petstore/erlang-server/src/swagger_pet_handler.erl index 4351da7da6c..d1c1a7b94d8 100644 --- a/samples/server/petstore/erlang-server/src/swagger_pet_handler.erl +++ b/samples/server/petstore/erlang-server/src/swagger_pet_handler.erl @@ -204,7 +204,7 @@ is_authorized( ) -> is_authorized(Req, State) -> - {{false, <<"">>}, Req, State}. + {true, Req, State}. -spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) -> { diff --git a/samples/server/petstore/erlang-server/src/swagger_server.erl b/samples/server/petstore/erlang-server/src/swagger_server.erl index 4f56a326034..1c3b9218afe 100644 --- a/samples/server/petstore/erlang-server/src/swagger_server.erl +++ b/samples/server/petstore/erlang-server/src/swagger_server.erl @@ -9,6 +9,7 @@ -spec child_spec( ID :: any(), #{ ip => inet:ip_address(), port => inet:port_number(), + logic_handler => module(), net_opts => [] }) -> supervisor:child_spec(). diff --git a/samples/server/petstore/erlang-server/src/swagger_store_handler.erl b/samples/server/petstore/erlang-server/src/swagger_store_handler.erl index 537ecdcb43f..adfeb256ae6 100644 --- a/samples/server/petstore/erlang-server/src/swagger_store_handler.erl +++ b/samples/server/petstore/erlang-server/src/swagger_store_handler.erl @@ -95,14 +95,6 @@ allowed_methods(Req, State) -> State :: state() }. -is_authorized( - Req0, - State = #state{ - operation_id = 'DeleteOrder' = OperationID, - logic_handler = LogicHandler - } -) -> - {true, Req0, State}; is_authorized( Req0, @@ -124,26 +116,10 @@ is_authorized( {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} end; -is_authorized( - Req0, - State = #state{ - operation_id = 'GetOrderById' = OperationID, - logic_handler = LogicHandler - } -) -> - {true, Req0, State}; -is_authorized( - Req0, - State = #state{ - operation_id = 'PlaceOrder' = OperationID, - logic_handler = LogicHandler - } -) -> - {true, Req0, State}; is_authorized(Req, State) -> - {{false, <<"">>}, Req, State}. + {true, Req, State}. -spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) -> { diff --git a/samples/server/petstore/erlang-server/src/swagger_user_handler.erl b/samples/server/petstore/erlang-server/src/swagger_user_handler.erl index 4597046b956..9e6ccaae3bc 100644 --- a/samples/server/petstore/erlang-server/src/swagger_user_handler.erl +++ b/samples/server/petstore/erlang-server/src/swagger_user_handler.erl @@ -127,80 +127,16 @@ allowed_methods(Req, State) -> State :: state() }. -is_authorized( - Req0, - State = #state{ - operation_id = 'CreateUser' = OperationID, - logic_handler = LogicHandler - } -) -> - {true, Req0, State}; -is_authorized( - Req0, - State = #state{ - operation_id = 'CreateUsersWithArrayInput' = OperationID, - logic_handler = LogicHandler - } -) -> - {true, Req0, State}; -is_authorized( - Req0, - State = #state{ - operation_id = 'CreateUsersWithListInput' = OperationID, - logic_handler = LogicHandler - } -) -> - {true, Req0, State}; -is_authorized( - Req0, - State = #state{ - operation_id = 'DeleteUser' = OperationID, - logic_handler = LogicHandler - } -) -> - {true, Req0, State}; -is_authorized( - Req0, - State = #state{ - operation_id = 'GetUserByName' = OperationID, - logic_handler = LogicHandler - } -) -> - {true, Req0, State}; -is_authorized( - Req0, - State = #state{ - operation_id = 'LoginUser' = OperationID, - logic_handler = LogicHandler - } -) -> - {true, Req0, State}; -is_authorized( - Req0, - State = #state{ - operation_id = 'LogoutUser' = OperationID, - logic_handler = LogicHandler - } -) -> - {true, Req0, State}; -is_authorized( - Req0, - State = #state{ - operation_id = 'UpdateUser' = OperationID, - logic_handler = LogicHandler - } -) -> - {true, Req0, State}; is_authorized(Req, State) -> - {{false, <<"">>}, Req, State}. + {true, Req, State}. -spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) -> { diff --git a/samples/server/petstore/finch/.swagger-codegen/VERSION b/samples/server/petstore/finch/.swagger-codegen/VERSION index 7fea99011a6..f9f7450d135 100644 --- a/samples/server/petstore/finch/.swagger-codegen/VERSION +++ b/samples/server/petstore/finch/.swagger-codegen/VERSION @@ -1 +1 @@ -2.2.3-SNAPSHOT \ No newline at end of file +2.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/apis/PetApi.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/apis/PetApi.scala index 74a01c56f51..be9bc36a557 100644 --- a/samples/server/petstore/finch/src/main/scala/io/swagger/apis/PetApi.scala +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/apis/PetApi.scala @@ -51,7 +51,7 @@ object PetApi { * @return And endpoint representing a Unit */ private def deletePet(da: DataAccessor): Endpoint[Unit] = - delete("pet" :: long :: string) { (petId: Long, apiKey: String) => + delete("pet" :: long :: headerOption("api_key")) { (petId: Long, apiKey: Option[String]) => da.Pet_deletePet(petId, apiKey) NoContent[Unit] } handle { @@ -108,7 +108,7 @@ object PetApi { * @return And endpoint representing a Unit */ private def updatePetWithForm(da: DataAccessor): Endpoint[Unit] = - post("pet" :: long :: string :: string) { (petId: Long, name: String, status: String) => + post("pet" :: long :: String :: String) { (petId: Long, name: String, status: String) => da.Pet_updatePetWithForm(petId, name, status) NoContent[Unit] } handle { @@ -120,7 +120,7 @@ object PetApi { * @return And endpoint representing a ApiResponse */ private def uploadFile(da: DataAccessor): Endpoint[ApiResponse] = - post("pet" :: long :: "uploadImage" :: string :: fileUpload("file")) { (petId: Long, additionalMetadata: String, file: FileUpload) => + post("pet" :: long :: "uploadImage" :: String :: fileUpload("file")) { (petId: Long, additionalMetadata: String, file: FileUpload) => Ok(da.Pet_uploadFile(petId, additionalMetadata, file)) } handle { case e: Exception => BadRequest(e) diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/apis/UserApi.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/apis/UserApi.scala index dfb49b4291a..bf1579835aa 100644 --- a/samples/server/petstore/finch/src/main/scala/io/swagger/apis/UserApi.scala +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/apis/UserApi.scala @@ -97,7 +97,7 @@ object UserApi { * @return And endpoint representing a String */ private def loginUser(da: DataAccessor): Endpoint[String] = - get("user" :: "login" :: string :: string) { (username: String, password: String) => + get("user" :: "login" :: param("username") :: param("password")) { (username: String, password: String) => Ok(da.User_loginUser(username, password)) } handle { case e: Exception => BadRequest(e) diff --git a/samples/server/petstore/flaskConnexion-python2/git_push.sh b/samples/server/petstore/flaskConnexion-python2/git_push.sh index ed374619b13..792320114fb 100644 --- a/samples/server/petstore/flaskConnexion-python2/git_push.sh +++ b/samples/server/petstore/flaskConnexion-python2/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/server/petstore/flaskConnexion-python2/setup.py b/samples/server/petstore/flaskConnexion-python2/setup.py index 7a1ce575d35..be5dce52ab7 100644 --- a/samples/server/petstore/flaskConnexion-python2/setup.py +++ b/samples/server/petstore/flaskConnexion-python2/setup.py @@ -26,6 +26,8 @@ setup( packages=find_packages(), package_data={'': ['swagger/swagger.yaml']}, include_package_data=True, + entry_points={ + 'console_scripts': ['swagger_server=swagger_server.__main__:main']}, long_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. """ diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/__main__.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/__main__.py index a85a5591ece..9f4473760ee 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/__main__.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/__main__.py @@ -1,11 +1,16 @@ #!/usr/bin/env python import connexion -from .encoder import JSONEncoder + +from swagger_server import encoder + + +def main(): + app = connexion.App(__name__, specification_dir='./swagger/') + app.app.json_encoder = encoder.JSONEncoder + app.add_api('swagger.yaml', arguments={'title': 'Swagger Petstore'}) + app.run(port=8080) if __name__ == '__main__': - app = connexion.App(__name__, specification_dir='./swagger/') - app.app.json_encoder = JSONEncoder - app.add_api('swagger.yaml', arguments={'title': '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.'}) - app.run(port=8080) + main() diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/pet_controller.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/pet_controller.py index 5a999aae88f..5de865c908a 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/pet_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/pet_controller.py @@ -1,30 +1,31 @@ import connexion -from swagger_server.models.api_response import ApiResponse -from swagger_server.models.pet import Pet -from datetime import date, datetime -from typing import List, Dict -from six import iteritems -from ..util import deserialize_date, deserialize_datetime +import six + +from swagger_server.models.api_response import ApiResponse # noqa: E501 +from swagger_server.models.pet import Pet # noqa: E501 +from swagger_server import util -def add_pet(body): - """ - Add a new pet to the store - +def add_pet(body): # noqa: E501 + """Add a new pet to the store + + # noqa: E501 + :param body: Pet object that needs to be added to the store :type body: dict | bytes :rtype: None """ if connexion.request.is_json: - body = Pet.from_dict(connexion.request.get_json()) + body = Pet.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' -def delete_pet(petId, api_key=None): - """ - Deletes a pet - +def delete_pet(petId, api_key=None): # noqa: E501 + """Deletes a pet + + # noqa: E501 + :param petId: Pet id to delete :type petId: int :param api_key: @@ -35,10 +36,11 @@ def delete_pet(petId, api_key=None): return 'do some magic!' -def find_pets_by_status(status): - """ - Finds Pets by status - Multiple status values can be provided with comma separated strings +def find_pets_by_status(status): # noqa: E501 + """Finds Pets by status + + Multiple status values can be provided with comma separated strings # noqa: E501 + :param status: Status values that need to be considered for filter :type status: List[str] @@ -47,10 +49,11 @@ def find_pets_by_status(status): return 'do some magic!' -def find_pets_by_tags(tags): - """ - Finds Pets by tags - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. +def find_pets_by_tags(tags): # noqa: E501 + """Finds Pets by tags + + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. # noqa: E501 + :param tags: Tags to filter by :type tags: List[str] @@ -59,10 +62,11 @@ def find_pets_by_tags(tags): return 'do some magic!' -def get_pet_by_id(petId): - """ - Find pet by ID - Returns a single pet +def get_pet_by_id(petId): # noqa: E501 + """Find pet by ID + + Returns a single pet # noqa: E501 + :param petId: ID of pet to return :type petId: int @@ -71,24 +75,26 @@ def get_pet_by_id(petId): return 'do some magic!' -def update_pet(body): - """ - Update an existing pet - +def update_pet(body): # noqa: E501 + """Update an existing pet + + # noqa: E501 + :param body: Pet object that needs to be added to the store :type body: dict | bytes :rtype: None """ if connexion.request.is_json: - body = Pet.from_dict(connexion.request.get_json()) + body = Pet.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' -def update_pet_with_form(petId, name=None, status=None): - """ - Updates a pet in the store with form data - +def update_pet_with_form(petId, name=None, status=None): # noqa: E501 + """Updates a pet in the store with form data + + # noqa: E501 + :param petId: ID of pet that needs to be updated :type petId: int :param name: Updated name of the pet @@ -101,10 +107,11 @@ def update_pet_with_form(petId, name=None, status=None): return 'do some magic!' -def upload_file(petId, additionalMetadata=None, file=None): - """ - uploads an image - +def upload_file(petId, additionalMetadata=None, file=None): # noqa: E501 + """uploads an image + + # noqa: E501 + :param petId: ID of pet to update :type petId: int :param additionalMetadata: Additional data to pass to server diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/store_controller.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/store_controller.py index 0cdcaf445dc..eae3546c21e 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/store_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/store_controller.py @@ -1,15 +1,15 @@ import connexion -from swagger_server.models.order import Order -from datetime import date, datetime -from typing import List, Dict -from six import iteritems -from ..util import deserialize_date, deserialize_datetime +import six + +from swagger_server.models.order import Order # noqa: E501 +from swagger_server import util -def delete_order(orderId): - """ - Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors +def delete_order(orderId): # noqa: E501 + """Delete purchase order by ID + + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors # noqa: E501 + :param orderId: ID of the order that needs to be deleted :type orderId: str @@ -18,20 +18,22 @@ def delete_order(orderId): return 'do some magic!' -def get_inventory(): - """ - Returns pet inventories by status - Returns a map of status codes to quantities +def get_inventory(): # noqa: E501 + """Returns pet inventories by status + + Returns a map of status codes to quantities # noqa: E501 + :rtype: Dict[str, int] """ return 'do some magic!' -def get_order_by_id(orderId): - """ - Find purchase order by ID - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions +def get_order_by_id(orderId): # noqa: E501 + """Find purchase order by ID + + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions # noqa: E501 + :param orderId: ID of pet that needs to be fetched :type orderId: int @@ -40,15 +42,16 @@ def get_order_by_id(orderId): return 'do some magic!' -def place_order(body): - """ - Place an order for a pet - +def place_order(body): # noqa: E501 + """Place an order for a pet + + # noqa: E501 + :param body: order placed for purchasing the pet :type body: dict | bytes :rtype: Order """ if connexion.request.is_json: - body = Order.from_dict(connexion.request.get_json()) + body = Order.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/user_controller.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/user_controller.py index 9a88626c5b8..c7c3ee3519a 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/user_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/user_controller.py @@ -1,57 +1,60 @@ import connexion -from swagger_server.models.user import User -from datetime import date, datetime -from typing import List, Dict -from six import iteritems -from ..util import deserialize_date, deserialize_datetime +import six + +from swagger_server.models.user import User # noqa: E501 +from swagger_server import util -def create_user(body): - """ - Create user - This can only be done by the logged in user. +def create_user(body): # noqa: E501 + """Create user + + This can only be done by the logged in user. # noqa: E501 + :param body: Created user object :type body: dict | bytes :rtype: None """ if connexion.request.is_json: - body = User.from_dict(connexion.request.get_json()) + body = User.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' -def create_users_with_array_input(body): - """ - Creates list of users with given input array - +def create_users_with_array_input(body): # noqa: E501 + """Creates list of users with given input array + + # noqa: E501 + :param body: List of user object :type body: list | bytes :rtype: None """ if connexion.request.is_json: - body = [User.from_dict(d) for d in connexion.request.get_json()] + body = [User.from_dict(d) for d in connexion.request.get_json()] # noqa: E501 return 'do some magic!' -def create_users_with_list_input(body): - """ - Creates list of users with given input array - +def create_users_with_list_input(body): # noqa: E501 + """Creates list of users with given input array + + # noqa: E501 + :param body: List of user object :type body: list | bytes :rtype: None """ if connexion.request.is_json: - body = [User.from_dict(d) for d in connexion.request.get_json()] + body = [User.from_dict(d) for d in connexion.request.get_json()] # noqa: E501 return 'do some magic!' -def delete_user(username): - """ - Delete user - This can only be done by the logged in user. +def delete_user(username): # noqa: E501 + """Delete user + + This can only be done by the logged in user. # noqa: E501 + :param username: The name that needs to be deleted :type username: str @@ -60,10 +63,11 @@ def delete_user(username): return 'do some magic!' -def get_user_by_name(username): - """ - Get user by user name - +def get_user_by_name(username): # noqa: E501 + """Get user by user name + + # noqa: E501 + :param username: The name that needs to be fetched. Use user1 for testing. :type username: str @@ -72,10 +76,11 @@ def get_user_by_name(username): return 'do some magic!' -def login_user(username, password): - """ - Logs user into the system - +def login_user(username, password): # noqa: E501 + """Logs user into the system + + # noqa: E501 + :param username: The user name for login :type username: str :param password: The password for login in clear text @@ -86,20 +91,22 @@ def login_user(username, password): return 'do some magic!' -def logout_user(): - """ - Logs out current logged in user session - +def logout_user(): # noqa: E501 + """Logs out current logged in user session + + # noqa: E501 + :rtype: None """ return 'do some magic!' -def update_user(username, body): - """ - Updated user - This can only be done by the logged in user. +def update_user(username, body): # noqa: E501 + """Updated user + + This can only be done by the logged in user. # noqa: E501 + :param username: name that need to be deleted :type username: str :param body: Updated user object @@ -108,5 +115,5 @@ def update_user(username, body): :rtype: None """ if connexion.request.is_json: - body = User.from_dict(connexion.request.get_json()) + body = User.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/encoder.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/encoder.py index 3ff8cad5d72..61ba4721961 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/encoder.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/encoder.py @@ -1,6 +1,8 @@ -from six import iteritems -from swagger_server.models.base_model_ import Model from connexion.apps.flask_app import FlaskJSONEncoder +import six + +from swagger_server.models.base_model_ import Model + class JSONEncoder(FlaskJSONEncoder): include_nulls = False @@ -8,11 +10,11 @@ class JSONEncoder(FlaskJSONEncoder): def default(self, o): if isinstance(o, Model): dikt = {} - for attr, _ in iteritems(o.swagger_types): + for attr, _ in six.iteritems(o.swagger_types): value = getattr(o, attr) if value is None and not self.include_nulls: continue attr = o.attribute_map[attr] dikt[attr] = value return dikt - return FlaskJSONEncoder.default(self, o) \ No newline at end of file + return FlaskJSONEncoder.default(self, o) diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/models/__init__.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/__init__.py index 6571ad28e0f..fcf8253348d 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/models/__init__.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/__init__.py @@ -1,10 +1,11 @@ # coding: utf-8 +# flake8: noqa from __future__ import absolute_import # import models into model package -from .api_response import ApiResponse -from .category import Category -from .order import Order -from .pet import Pet -from .tag import Tag -from .user import User +from swagger_server.models.api_response import ApiResponse +from swagger_server.models.category import Category +from swagger_server.models.order import Order +from swagger_server.models.pet import Pet +from swagger_server.models.tag import Tag +from swagger_server.models.user import User diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/models/api_response.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/api_response.py index c1e51033298..08e4007b9c2 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/models/api_response.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/api_response.py @@ -1,28 +1,28 @@ # coding: utf-8 from __future__ import absolute_import -from .base_model_ import Model -from datetime import date, datetime -from typing import List, Dict -from ..util import deserialize_model +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server import util class ApiResponse(Model): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ + def __init__(self, code=None, type=None, message=None): # noqa: E501 + """ApiResponse - a model defined in Swagger - def __init__(self, code=None, type=None, message=None): - """ - ApiResponse - a model defined in Swagger - - :param code: The code of this ApiResponse. + :param code: The code of this ApiResponse. # noqa: E501 :type code: int - :param type: The type of this ApiResponse. + :param type: The type of this ApiResponse. # noqa: E501 :type type: str - :param message: The message of this ApiResponse. + :param message: The message of this ApiResponse. # noqa: E501 :type message: str """ self.swagger_types = { @@ -43,20 +43,19 @@ class ApiResponse(Model): @classmethod def from_dict(cls, dikt): - """ - Returns the dict as a model + """Returns the dict as a model :param dikt: A dict. :type: dict - :return: The ApiResponse of this ApiResponse. + :return: The ApiResponse of this ApiResponse. # noqa: E501 :rtype: ApiResponse """ - return deserialize_model(dikt, cls) + return util.deserialize_model(dikt, cls) @property def code(self): - """ - Gets the code of this ApiResponse. + """Gets the code of this ApiResponse. + :return: The code of this ApiResponse. :rtype: int @@ -65,8 +64,8 @@ class ApiResponse(Model): @code.setter def code(self, code): - """ - Sets the code of this ApiResponse. + """Sets the code of this ApiResponse. + :param code: The code of this ApiResponse. :type code: int @@ -76,8 +75,8 @@ class ApiResponse(Model): @property def type(self): - """ - Gets the type of this ApiResponse. + """Gets the type of this ApiResponse. + :return: The type of this ApiResponse. :rtype: str @@ -86,8 +85,8 @@ class ApiResponse(Model): @type.setter def type(self, type): - """ - Sets the type of this ApiResponse. + """Sets the type of this ApiResponse. + :param type: The type of this ApiResponse. :type type: str @@ -97,8 +96,8 @@ class ApiResponse(Model): @property def message(self): - """ - Gets the message of this ApiResponse. + """Gets the message of this ApiResponse. + :return: The message of this ApiResponse. :rtype: str @@ -107,12 +106,11 @@ class ApiResponse(Model): @message.setter def message(self, message): - """ - Sets the message of this ApiResponse. + """Sets the message of this ApiResponse. + :param message: The message of this ApiResponse. :type message: str """ self._message = message - diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/models/base_model_.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/base_model_.py index 30a7a03577a..35296d34ca4 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/models/base_model_.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/base_model_.py @@ -1,31 +1,32 @@ -from pprint import pformat -from six import iteritems -from ..util import deserialize_model +import pprint + +import six + +from swagger_server import util class Model(object): - # swaggerTypes: The key is attribute name and the value is attribute type. + # swaggerTypes: The key is attribute name and the + # value is attribute type. swagger_types = {} - # attributeMap: The key is attribute name and the value is json key in definition. + # attributeMap: The key is attribute name and the + # value is json key in definition. attribute_map = {} @classmethod def from_dict(cls, dikt): - """ - Returns the dict as a model - """ - return deserialize_model(dikt, cls) + """Returns the dict as a model""" + return util.deserialize_model(dikt, cls) def to_dict(self): - """ - Returns the model properties as a dict + """Returns the model properties as a dict :rtype: dict """ result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -46,27 +47,20 @@ class Model(object): return result def to_str(self): - """ - Returns the string representation of the model + """Returns the string representation of the model :rtype: str """ - return pformat(self.to_dict()) + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """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 \ No newline at end of file + """Returns true if both objects are not equal""" + return not self == other diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/models/category.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/category.py index d465845fe11..34aa53d3ce0 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/models/category.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/category.py @@ -1,26 +1,26 @@ # coding: utf-8 from __future__ import absolute_import -from .base_model_ import Model -from datetime import date, datetime -from typing import List, Dict -from ..util import deserialize_model +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server import util class Category(Model): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ + def __init__(self, id=None, name=None): # noqa: E501 + """Category - a model defined in Swagger - def __init__(self, id=None, name=None): - """ - Category - a model defined in Swagger - - :param id: The id of this Category. + :param id: The id of this Category. # noqa: E501 :type id: long - :param name: The name of this Category. + :param name: The name of this Category. # noqa: E501 :type name: str """ self.swagger_types = { @@ -38,20 +38,19 @@ class Category(Model): @classmethod def from_dict(cls, dikt): - """ - Returns the dict as a model + """Returns the dict as a model :param dikt: A dict. :type: dict - :return: The Category of this Category. + :return: The Category of this Category. # noqa: E501 :rtype: Category """ - return deserialize_model(dikt, cls) + return util.deserialize_model(dikt, cls) @property def id(self): - """ - Gets the id of this Category. + """Gets the id of this Category. + :return: The id of this Category. :rtype: long @@ -60,8 +59,8 @@ class Category(Model): @id.setter def id(self, id): - """ - Sets the id of this Category. + """Sets the id of this Category. + :param id: The id of this Category. :type id: long @@ -71,8 +70,8 @@ class Category(Model): @property def name(self): - """ - Gets the name of this Category. + """Gets the name of this Category. + :return: The name of this Category. :rtype: str @@ -81,12 +80,11 @@ class Category(Model): @name.setter def name(self, name): - """ - Sets the name of this Category. + """Sets the name of this Category. + :param name: The name of this Category. :type name: str """ self._name = name - diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/models/order.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/order.py index fefe4cb8c5f..7b7f5f0645f 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/models/order.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/order.py @@ -1,34 +1,34 @@ # coding: utf-8 from __future__ import absolute_import -from .base_model_ import Model -from datetime import date, datetime -from typing import List, Dict -from ..util import deserialize_model +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server import util class Order(Model): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ + def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=None, complete=False): # noqa: E501 + """Order - a model defined in Swagger - def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=None, complete=False): - """ - Order - a model defined in Swagger - - :param id: The id of this Order. + :param id: The id of this Order. # noqa: E501 :type id: long - :param pet_id: The pet_id of this Order. + :param pet_id: The pet_id of this Order. # noqa: E501 :type pet_id: long - :param quantity: The quantity of this Order. + :param quantity: The quantity of this Order. # noqa: E501 :type quantity: int - :param ship_date: The ship_date of this Order. + :param ship_date: The ship_date of this Order. # noqa: E501 :type ship_date: datetime - :param status: The status of this Order. + :param status: The status of this Order. # noqa: E501 :type status: str - :param complete: The complete of this Order. + :param complete: The complete of this Order. # noqa: E501 :type complete: bool """ self.swagger_types = { @@ -58,20 +58,19 @@ class Order(Model): @classmethod def from_dict(cls, dikt): - """ - Returns the dict as a model + """Returns the dict as a model :param dikt: A dict. :type: dict - :return: The Order of this Order. + :return: The Order of this Order. # noqa: E501 :rtype: Order """ - return deserialize_model(dikt, cls) + return util.deserialize_model(dikt, cls) @property def id(self): - """ - Gets the id of this Order. + """Gets the id of this Order. + :return: The id of this Order. :rtype: long @@ -80,8 +79,8 @@ class Order(Model): @id.setter def id(self, id): - """ - Sets the id of this Order. + """Sets the id of this Order. + :param id: The id of this Order. :type id: long @@ -91,8 +90,8 @@ class Order(Model): @property def pet_id(self): - """ - Gets the pet_id of this Order. + """Gets the pet_id of this Order. + :return: The pet_id of this Order. :rtype: long @@ -101,8 +100,8 @@ class Order(Model): @pet_id.setter def pet_id(self, pet_id): - """ - Sets the pet_id of this Order. + """Sets the pet_id of this Order. + :param pet_id: The pet_id of this Order. :type pet_id: long @@ -112,8 +111,8 @@ class Order(Model): @property def quantity(self): - """ - Gets the quantity of this Order. + """Gets the quantity of this Order. + :return: The quantity of this Order. :rtype: int @@ -122,8 +121,8 @@ class Order(Model): @quantity.setter def quantity(self, quantity): - """ - Sets the quantity of this Order. + """Sets the quantity of this Order. + :param quantity: The quantity of this Order. :type quantity: int @@ -133,8 +132,8 @@ class Order(Model): @property def ship_date(self): - """ - Gets the ship_date of this Order. + """Gets the ship_date of this Order. + :return: The ship_date of this Order. :rtype: datetime @@ -143,8 +142,8 @@ class Order(Model): @ship_date.setter def ship_date(self, ship_date): - """ - Sets the ship_date of this Order. + """Sets the ship_date of this Order. + :param ship_date: The ship_date of this Order. :type ship_date: datetime @@ -154,9 +153,9 @@ class Order(Model): @property def status(self): - """ - Gets the status of this Order. - Order Status + """Gets the status of this Order. + + Order Status # noqa: E501 :return: The status of this Order. :rtype: str @@ -165,14 +164,14 @@ class Order(Model): @status.setter def status(self, status): - """ - Sets the status of this Order. - Order Status + """Sets the status of this Order. + + Order Status # noqa: E501 :param status: The status of this Order. :type status: str """ - allowed_values = ["placed", "approved", "delivered"] + allowed_values = ["placed", "approved", "delivered"] # noqa: E501 if status not in allowed_values: raise ValueError( "Invalid value for `status` ({0}), must be one of {1}" @@ -183,8 +182,8 @@ class Order(Model): @property def complete(self): - """ - Gets the complete of this Order. + """Gets the complete of this Order. + :return: The complete of this Order. :rtype: bool @@ -193,12 +192,11 @@ class Order(Model): @complete.setter def complete(self, complete): - """ - Sets the complete of this Order. + """Sets the complete of this Order. + :param complete: The complete of this Order. :type complete: bool """ self._complete = complete - diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/models/pet.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/pet.py index 35dac42dc45..0f8e96dcd56 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/models/pet.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/pet.py @@ -1,36 +1,36 @@ # coding: utf-8 from __future__ import absolute_import -from swagger_server.models.category import Category -from swagger_server.models.tag import Tag -from .base_model_ import Model -from datetime import date, datetime -from typing import List, Dict -from ..util import deserialize_model +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server.models.category import Category # noqa: F401,E501 +from swagger_server.models.tag import Tag # noqa: F401,E501 +from swagger_server import util class Pet(Model): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ + def __init__(self, id=None, category=None, name=None, photo_urls=None, tags=None, status=None): # noqa: E501 + """Pet - a model defined in Swagger - def __init__(self, id=None, category=None, name=None, photo_urls=None, tags=None, status=None): - """ - Pet - a model defined in Swagger - - :param id: The id of this Pet. + :param id: The id of this Pet. # noqa: E501 :type id: long - :param category: The category of this Pet. + :param category: The category of this Pet. # noqa: E501 :type category: Category - :param name: The name of this Pet. + :param name: The name of this Pet. # noqa: E501 :type name: str - :param photo_urls: The photo_urls of this Pet. + :param photo_urls: The photo_urls of this Pet. # noqa: E501 :type photo_urls: List[str] - :param tags: The tags of this Pet. + :param tags: The tags of this Pet. # noqa: E501 :type tags: List[Tag] - :param status: The status of this Pet. + :param status: The status of this Pet. # noqa: E501 :type status: str """ self.swagger_types = { @@ -60,20 +60,19 @@ class Pet(Model): @classmethod def from_dict(cls, dikt): - """ - Returns the dict as a model + """Returns the dict as a model :param dikt: A dict. :type: dict - :return: The Pet of this Pet. + :return: The Pet of this Pet. # noqa: E501 :rtype: Pet """ - return deserialize_model(dikt, cls) + return util.deserialize_model(dikt, cls) @property def id(self): - """ - Gets the id of this Pet. + """Gets the id of this Pet. + :return: The id of this Pet. :rtype: long @@ -82,8 +81,8 @@ class Pet(Model): @id.setter def id(self, id): - """ - Sets the id of this Pet. + """Sets the id of this Pet. + :param id: The id of this Pet. :type id: long @@ -93,8 +92,8 @@ class Pet(Model): @property def category(self): - """ - Gets the category of this Pet. + """Gets the category of this Pet. + :return: The category of this Pet. :rtype: Category @@ -103,8 +102,8 @@ class Pet(Model): @category.setter def category(self, category): - """ - Sets the category of this Pet. + """Sets the category of this Pet. + :param category: The category of this Pet. :type category: Category @@ -114,8 +113,8 @@ class Pet(Model): @property def name(self): - """ - Gets the name of this Pet. + """Gets the name of this Pet. + :return: The name of this Pet. :rtype: str @@ -124,21 +123,21 @@ class Pet(Model): @name.setter def name(self, name): - """ - Sets the name of this Pet. + """Sets the name of this Pet. + :param name: The name of this Pet. :type name: str """ if name is None: - raise ValueError("Invalid value for `name`, must not be `None`") + raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name @property def photo_urls(self): - """ - Gets the photo_urls of this Pet. + """Gets the photo_urls of this Pet. + :return: The photo_urls of this Pet. :rtype: List[str] @@ -147,21 +146,21 @@ class Pet(Model): @photo_urls.setter def photo_urls(self, photo_urls): - """ - Sets the photo_urls of this Pet. + """Sets the photo_urls of this Pet. + :param photo_urls: The photo_urls of this Pet. :type photo_urls: List[str] """ if photo_urls is None: - raise ValueError("Invalid value for `photo_urls`, must not be `None`") + raise ValueError("Invalid value for `photo_urls`, must not be `None`") # noqa: E501 self._photo_urls = photo_urls @property def tags(self): - """ - Gets the tags of this Pet. + """Gets the tags of this Pet. + :return: The tags of this Pet. :rtype: List[Tag] @@ -170,8 +169,8 @@ class Pet(Model): @tags.setter def tags(self, tags): - """ - Sets the tags of this Pet. + """Sets the tags of this Pet. + :param tags: The tags of this Pet. :type tags: List[Tag] @@ -181,9 +180,9 @@ class Pet(Model): @property def status(self): - """ - Gets the status of this Pet. - pet status in the store + """Gets the status of this Pet. + + pet status in the store # noqa: E501 :return: The status of this Pet. :rtype: str @@ -192,14 +191,14 @@ class Pet(Model): @status.setter def status(self, status): - """ - Sets the status of this Pet. - pet status in the store + """Sets the status of this Pet. + + pet status in the store # noqa: E501 :param status: The status of this Pet. :type status: str """ - allowed_values = ["available", "pending", "sold"] + allowed_values = ["available", "pending", "sold"] # noqa: E501 if status not in allowed_values: raise ValueError( "Invalid value for `status` ({0}), must be one of {1}" @@ -207,4 +206,3 @@ class Pet(Model): ) self._status = status - diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/models/tag.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/tag.py index 0933d44d0b1..d26d435242e 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/models/tag.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/tag.py @@ -1,26 +1,26 @@ # coding: utf-8 from __future__ import absolute_import -from .base_model_ import Model -from datetime import date, datetime -from typing import List, Dict -from ..util import deserialize_model +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server import util class Tag(Model): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ + def __init__(self, id=None, name=None): # noqa: E501 + """Tag - a model defined in Swagger - def __init__(self, id=None, name=None): - """ - Tag - a model defined in Swagger - - :param id: The id of this Tag. + :param id: The id of this Tag. # noqa: E501 :type id: long - :param name: The name of this Tag. + :param name: The name of this Tag. # noqa: E501 :type name: str """ self.swagger_types = { @@ -38,20 +38,19 @@ class Tag(Model): @classmethod def from_dict(cls, dikt): - """ - Returns the dict as a model + """Returns the dict as a model :param dikt: A dict. :type: dict - :return: The Tag of this Tag. + :return: The Tag of this Tag. # noqa: E501 :rtype: Tag """ - return deserialize_model(dikt, cls) + return util.deserialize_model(dikt, cls) @property def id(self): - """ - Gets the id of this Tag. + """Gets the id of this Tag. + :return: The id of this Tag. :rtype: long @@ -60,8 +59,8 @@ class Tag(Model): @id.setter def id(self, id): - """ - Sets the id of this Tag. + """Sets the id of this Tag. + :param id: The id of this Tag. :type id: long @@ -71,8 +70,8 @@ class Tag(Model): @property def name(self): - """ - Gets the name of this Tag. + """Gets the name of this Tag. + :return: The name of this Tag. :rtype: str @@ -81,12 +80,11 @@ class Tag(Model): @name.setter def name(self, name): - """ - Sets the name of this Tag. + """Sets the name of this Tag. + :param name: The name of this Tag. :type name: str """ self._name = name - diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/models/user.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/user.py index eddf5ef92ef..84956ff2663 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/models/user.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/user.py @@ -1,38 +1,38 @@ # coding: utf-8 from __future__ import absolute_import -from .base_model_ import Model -from datetime import date, datetime -from typing import List, Dict -from ..util import deserialize_model +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server import util class User(Model): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ + def __init__(self, id=None, username=None, first_name=None, last_name=None, email=None, password=None, phone=None, user_status=None): # noqa: E501 + """User - a model defined in Swagger - 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 - - :param id: The id of this User. + :param id: The id of this User. # noqa: E501 :type id: long - :param username: The username of this User. + :param username: The username of this User. # noqa: E501 :type username: str - :param first_name: The first_name of this User. + :param first_name: The first_name of this User. # noqa: E501 :type first_name: str - :param last_name: The last_name of this User. + :param last_name: The last_name of this User. # noqa: E501 :type last_name: str - :param email: The email of this User. + :param email: The email of this User. # noqa: E501 :type email: str - :param password: The password of this User. + :param password: The password of this User. # noqa: E501 :type password: str - :param phone: The phone of this User. + :param phone: The phone of this User. # noqa: E501 :type phone: str - :param user_status: The user_status of this User. + :param user_status: The user_status of this User. # noqa: E501 :type user_status: int """ self.swagger_types = { @@ -68,20 +68,19 @@ class User(Model): @classmethod def from_dict(cls, dikt): - """ - Returns the dict as a model + """Returns the dict as a model :param dikt: A dict. :type: dict - :return: The User of this User. + :return: The User of this User. # noqa: E501 :rtype: User """ - return deserialize_model(dikt, cls) + return util.deserialize_model(dikt, cls) @property def id(self): - """ - Gets the id of this User. + """Gets the id of this User. + :return: The id of this User. :rtype: long @@ -90,8 +89,8 @@ class User(Model): @id.setter def id(self, id): - """ - Sets the id of this User. + """Sets the id of this User. + :param id: The id of this User. :type id: long @@ -101,8 +100,8 @@ class User(Model): @property def username(self): - """ - Gets the username of this User. + """Gets the username of this User. + :return: The username of this User. :rtype: str @@ -111,8 +110,8 @@ class User(Model): @username.setter def username(self, username): - """ - Sets the username of this User. + """Sets the username of this User. + :param username: The username of this User. :type username: str @@ -122,8 +121,8 @@ class User(Model): @property def first_name(self): - """ - Gets the first_name of this User. + """Gets the first_name of this User. + :return: The first_name of this User. :rtype: str @@ -132,8 +131,8 @@ class User(Model): @first_name.setter def first_name(self, first_name): - """ - Sets the first_name of this User. + """Sets the first_name of this User. + :param first_name: The first_name of this User. :type first_name: str @@ -143,8 +142,8 @@ class User(Model): @property def last_name(self): - """ - Gets the last_name of this User. + """Gets the last_name of this User. + :return: The last_name of this User. :rtype: str @@ -153,8 +152,8 @@ class User(Model): @last_name.setter def last_name(self, last_name): - """ - Sets the last_name of this User. + """Sets the last_name of this User. + :param last_name: The last_name of this User. :type last_name: str @@ -164,8 +163,8 @@ class User(Model): @property def email(self): - """ - Gets the email of this User. + """Gets the email of this User. + :return: The email of this User. :rtype: str @@ -174,8 +173,8 @@ class User(Model): @email.setter def email(self, email): - """ - Sets the email of this User. + """Sets the email of this User. + :param email: The email of this User. :type email: str @@ -185,8 +184,8 @@ class User(Model): @property def password(self): - """ - Gets the password of this User. + """Gets the password of this User. + :return: The password of this User. :rtype: str @@ -195,8 +194,8 @@ class User(Model): @password.setter def password(self, password): - """ - Sets the password of this User. + """Sets the password of this User. + :param password: The password of this User. :type password: str @@ -206,8 +205,8 @@ class User(Model): @property def phone(self): - """ - Gets the phone of this User. + """Gets the phone of this User. + :return: The phone of this User. :rtype: str @@ -216,8 +215,8 @@ class User(Model): @phone.setter def phone(self, phone): - """ - Sets the phone of this User. + """Sets the phone of this User. + :param phone: The phone of this User. :type phone: str @@ -227,9 +226,9 @@ class User(Model): @property def user_status(self): - """ - Gets the user_status of this User. - User Status + """Gets the user_status of this User. + + User Status # noqa: E501 :return: The user_status of this User. :rtype: int @@ -238,13 +237,12 @@ class User(Model): @user_status.setter def user_status(self, user_status): - """ - Sets the user_status of this User. - User Status + """Sets the user_status of this User. + + User Status # noqa: E501 :param user_status: The user_status of this User. :type user_status: int """ self._user_status = user_status - diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/swagger/swagger.yaml b/samples/server/petstore/flaskConnexion-python2/swagger_server/swagger/swagger.yaml index 32000d3c2dc..ba2a870047d 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/swagger/swagger.yaml +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/swagger/swagger.yaml @@ -108,11 +108,11 @@ paths: type: "array" items: type: "string" - default: "available" enum: - "available" - "pending" - "sold" + default: "available" collectionFormat: "csv" responses: 200: @@ -627,12 +627,12 @@ definitions: title: "Pet Order" description: "An order for a pets from the pet store" example: - petId: 6 - quantity: 1 id: 0 - shipDate: "2000-01-23T04:56:07.000+00:00" + petId: 6 complete: false status: "placed" + quantity: 1 + shipDate: "2000-01-23T04:56:07.000+00:00" xml: name: "Order" Category: @@ -646,8 +646,8 @@ definitions: title: "Pet catehgry" description: "A category for a pet" example: - name: "name" id: 6 + name: "name" xml: name: "Category" User: @@ -675,14 +675,14 @@ definitions: title: "a User" description: "A User who is purchasing from the pet store" example: - firstName: "firstName" - lastName: "lastName" - password: "password" - userStatus: 6 - phone: "phone" id: 0 - email: "email" + lastName: "lastName" + phone: "phone" username: "username" + email: "email" + userStatus: 6 + firstName: "firstName" + password: "password" xml: name: "User" Tag: @@ -696,8 +696,8 @@ definitions: title: "Pet Tag" description: "A tag for a pet" example: - name: "name" id: 1 + name: "name" xml: name: "Tag" Pet: @@ -738,20 +738,20 @@ definitions: title: "a Pet" description: "A pet for sale in the pet store" example: + tags: + - id: 1 + name: "name" + - id: 1 + name: "name" + id: 0 + category: + id: 6 + name: "name" + status: "available" + name: "doggie" photoUrls: - "photoUrls" - "photoUrls" - name: "doggie" - id: 0 - category: - name: "name" - id: 6 - tags: - - name: "name" - id: 1 - - name: "name" - id: 1 - status: "available" xml: name: "Pet" ApiResponse: @@ -767,9 +767,9 @@ definitions: title: "An uploaded response" description: "Describes the result of uploading an image resource" example: + message: "message" code: 0 type: "type" - message: "message" externalDocs: description: "Find out more about Swagger" url: "http://swagger.io" diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/test/__init__.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/test/__init__.py index 77b10c3a012..644506301ce 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/test/__init__.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/test/__init__.py @@ -1,8 +1,10 @@ -from flask_testing import TestCase -from ..encoder import JSONEncoder -import connexion import logging +import connexion +from flask_testing import TestCase + +from swagger_server.encoder import JSONEncoder + class BaseTestCase(TestCase): diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_pet_controller.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_pet_controller.py index b99269a991a..fb4c34ea3e1 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_pet_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_pet_controller.py @@ -2,115 +2,124 @@ from __future__ import absolute_import -from swagger_server.models.api_response import ApiResponse -from swagger_server.models.pet import Pet -from . import BaseTestCase -from six import BytesIO from flask import json +from six import BytesIO + +from swagger_server.models.api_response import ApiResponse # noqa: E501 +from swagger_server.models.pet import Pet # noqa: E501 +from swagger_server.test import BaseTestCase class TestPetController(BaseTestCase): - """ PetController integration test stubs """ + """PetController integration test stubs""" def test_add_pet(self): - """ - Test case for add_pet + """Test case for add_pet Add a new pet to the store """ body = Pet() - response = self.client.open('/v2/pet', - method='POST', - data=json.dumps(body), - content_type='application/json') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/pet', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_delete_pet(self): - """ - Test case for delete_pet + """Test case for delete_pet Deletes a pet """ headers = [('api_key', 'api_key_example')] - response = self.client.open('/v2/pet/{petId}'.format(petId=789), - method='DELETE', - headers=headers) - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/pet/{petId}'.format(petId=789), + method='DELETE', + headers=headers) + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_find_pets_by_status(self): - """ - Test case for find_pets_by_status + """Test case for find_pets_by_status Finds Pets by status """ query_string = [('status', 'available')] - response = self.client.open('/v2/pet/findByStatus', - method='GET', - query_string=query_string) - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/pet/findByStatus', + method='GET', + query_string=query_string) + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_find_pets_by_tags(self): - """ - Test case for find_pets_by_tags + """Test case for find_pets_by_tags Finds Pets by tags """ query_string = [('tags', 'tags_example')] - response = self.client.open('/v2/pet/findByTags', - method='GET', - query_string=query_string) - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/pet/findByTags', + method='GET', + query_string=query_string) + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_get_pet_by_id(self): - """ - Test case for get_pet_by_id + """Test case for get_pet_by_id Find pet by ID """ - response = self.client.open('/v2/pet/{petId}'.format(petId=789), - method='GET') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/pet/{petId}'.format(petId=789), + method='GET') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_update_pet(self): - """ - Test case for update_pet + """Test case for update_pet Update an existing pet """ body = Pet() - response = self.client.open('/v2/pet', - method='PUT', - data=json.dumps(body), - content_type='application/json') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/pet', + method='PUT', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_update_pet_with_form(self): - """ - Test case for update_pet_with_form + """Test case for update_pet_with_form Updates a pet in the store with form data """ data = dict(name='name_example', status='status_example') - response = self.client.open('/v2/pet/{petId}'.format(petId=789), - method='POST', - data=data, - content_type='application/x-www-form-urlencoded') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/pet/{petId}'.format(petId=789), + method='POST', + data=data, + content_type='application/x-www-form-urlencoded') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_upload_file(self): - """ - Test case for upload_file + """Test case for upload_file uploads an image """ data = dict(additionalMetadata='additionalMetadata_example', file=(BytesIO(b'some file data'), 'file.txt')) - response = self.client.open('/v2/pet/{petId}/uploadImage'.format(petId=789), - method='POST', - data=data, - content_type='multipart/form-data') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/pet/{petId}/uploadImage'.format(petId=789), + method='POST', + data=data, + content_type='multipart/form-data') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) if __name__ == '__main__': diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_store_controller.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_store_controller.py index 0a5360b4e25..854e18600fc 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_store_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_store_controller.py @@ -2,57 +2,62 @@ from __future__ import absolute_import -from swagger_server.models.order import Order -from . import BaseTestCase -from six import BytesIO from flask import json +from six import BytesIO + +from swagger_server.models.order import Order # noqa: E501 +from swagger_server.test import BaseTestCase class TestStoreController(BaseTestCase): - """ StoreController integration test stubs """ + """StoreController integration test stubs""" def test_delete_order(self): - """ - Test case for delete_order + """Test case for delete_order Delete purchase order by ID """ - response = self.client.open('/v2/store/order/{orderId}'.format(orderId='orderId_example'), - method='DELETE') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/store/order/{orderId}'.format(orderId='orderId_example'), + method='DELETE') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_get_inventory(self): - """ - Test case for get_inventory + """Test case for get_inventory Returns pet inventories by status """ - response = self.client.open('/v2/store/inventory', - method='GET') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/store/inventory', + method='GET') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_get_order_by_id(self): - """ - Test case for get_order_by_id + """Test case for get_order_by_id Find purchase order by ID """ - response = self.client.open('/v2/store/order/{orderId}'.format(orderId=5), - method='GET') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/store/order/{orderId}'.format(orderId=5), + method='GET') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_place_order(self): - """ - Test case for place_order + """Test case for place_order Place an order for a pet """ body = Order() - response = self.client.open('/v2/store/order', - method='POST', - data=json.dumps(body), - content_type='application/json') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/store/order', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) if __name__ == '__main__': diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_user_controller.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_user_controller.py index 867de3c0150..30e1885afab 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_user_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_user_controller.py @@ -2,109 +2,118 @@ from __future__ import absolute_import -from swagger_server.models.user import User -from . import BaseTestCase -from six import BytesIO from flask import json +from six import BytesIO + +from swagger_server.models.user import User # noqa: E501 +from swagger_server.test import BaseTestCase class TestUserController(BaseTestCase): - """ UserController integration test stubs """ + """UserController integration test stubs""" def test_create_user(self): - """ - Test case for create_user + """Test case for create_user Create user """ body = User() - response = self.client.open('/v2/user', - method='POST', - data=json.dumps(body), - content_type='application/json') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/user', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_create_users_with_array_input(self): - """ - Test case for create_users_with_array_input + """Test case for create_users_with_array_input Creates list of users with given input array """ body = [User()] - response = self.client.open('/v2/user/createWithArray', - method='POST', - data=json.dumps(body), - content_type='application/json') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/user/createWithArray', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_create_users_with_list_input(self): - """ - Test case for create_users_with_list_input + """Test case for create_users_with_list_input Creates list of users with given input array """ body = [User()] - response = self.client.open('/v2/user/createWithList', - method='POST', - data=json.dumps(body), - content_type='application/json') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/user/createWithList', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_delete_user(self): - """ - Test case for delete_user + """Test case for delete_user Delete user """ - response = self.client.open('/v2/user/{username}'.format(username='username_example'), - method='DELETE') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/user/{username}'.format(username='username_example'), + method='DELETE') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_get_user_by_name(self): - """ - Test case for get_user_by_name + """Test case for get_user_by_name Get user by user name """ - response = self.client.open('/v2/user/{username}'.format(username='username_example'), - method='GET') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/user/{username}'.format(username='username_example'), + method='GET') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_login_user(self): - """ - Test case for login_user + """Test case for login_user Logs user into the system """ query_string = [('username', 'username_example'), ('password', 'password_example')] - response = self.client.open('/v2/user/login', - method='GET', - query_string=query_string) - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/user/login', + method='GET', + query_string=query_string) + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_logout_user(self): - """ - Test case for logout_user + """Test case for logout_user Logs out current logged in user session """ - response = self.client.open('/v2/user/logout', - method='GET') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/user/logout', + method='GET') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_update_user(self): - """ - Test case for update_user + """Test case for update_user Updated user """ body = User() - response = self.client.open('/v2/user/{username}'.format(username='username_example'), - method='PUT', - data=json.dumps(body), - content_type='application/json') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/user/{username}'.format(username='username_example'), + method='PUT', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) if __name__ == '__main__': diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/util.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/util.py index 40c72d43ebd..527d1424c3d 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger_server/util.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/util.py @@ -1,11 +1,11 @@ -from typing import GenericMeta -from datetime import datetime, date -from six import integer_types, iteritems +import datetime + +import six +import typing def _deserialize(data, klass): - """ - Deserializes dict, list, str into an object. + """Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. @@ -15,15 +15,15 @@ def _deserialize(data, klass): if data is None: return None - if klass in integer_types or klass in (float, str, bool): + if klass in six.integer_types or klass in (float, str, bool): return _deserialize_primitive(data, klass) elif klass == object: return _deserialize_object(data) - elif klass == date: + elif klass == datetime.date: return deserialize_date(data) - elif klass == datetime: + elif klass == datetime.datetime: return deserialize_datetime(data) - elif type(klass) == GenericMeta: + elif type(klass) == typing.GenericMeta: if klass.__extra__ == list: return _deserialize_list(data, klass.__args__[0]) if klass.__extra__ == dict: @@ -33,8 +33,7 @@ def _deserialize(data, klass): def _deserialize_primitive(data, klass): - """ - Deserializes to primitive type. + """Deserializes to primitive type. :param data: data to deserialize. :param klass: class literal. @@ -45,15 +44,14 @@ def _deserialize_primitive(data, klass): try: value = klass(data) except UnicodeEncodeError: - value = unicode(data) + value = six.u(data) except TypeError: value = data return value def _deserialize_object(value): - """ - Return a original value. + """Return a original value. :return: object. """ @@ -61,8 +59,7 @@ def _deserialize_object(value): def deserialize_date(string): - """ - Deserializes string to date. + """Deserializes string to date. :param string: str. :type string: str @@ -77,8 +74,7 @@ def deserialize_date(string): def deserialize_datetime(string): - """ - Deserializes string to datetime. + """Deserializes string to datetime. The string should be in iso8601 datetime format. @@ -95,8 +91,7 @@ def deserialize_datetime(string): def deserialize_model(data, klass): - """ - Deserializes list or dict to model. + """Deserializes list or dict to model. :param data: dict, list. :type data: dict | list @@ -108,7 +103,7 @@ def deserialize_model(data, klass): if not instance.swagger_types: return data - for attr, attr_type in iteritems(instance.swagger_types): + for attr, attr_type in six.iteritems(instance.swagger_types): if data is not None \ and instance.attribute_map[attr] in data \ and isinstance(data, (list, dict)): @@ -119,8 +114,7 @@ def deserialize_model(data, klass): def _deserialize_list(data, boxed_type): - """ - Deserializes a list and its elements. + """Deserializes a list and its elements. :param data: list to deserialize. :type data: list @@ -133,10 +127,8 @@ def _deserialize_list(data, boxed_type): for sub_data in data] - def _deserialize_dict(data, boxed_type): - """ - Deserializes a dict and its elements. + """Deserializes a dict and its elements. :param data: dict to deserialize. :type data: dict @@ -146,4 +138,4 @@ def _deserialize_dict(data, boxed_type): :rtype: dict """ return {k: _deserialize(v, boxed_type) - for k, v in iteritems(data)} + for k, v in six.iteritems(data)} diff --git a/samples/server/petstore/flaskConnexion-python2/tox.ini b/samples/server/petstore/flaskConnexion-python2/tox.ini index fe94589593a..b633a1f0598 100644 --- a/samples/server/petstore/flaskConnexion-python2/tox.ini +++ b/samples/server/petstore/flaskConnexion-python2/tox.ini @@ -4,7 +4,7 @@ envlist = py27, py35 [testenv] deps=-r{toxinidir}/requirements.txt -r{toxinidir}/test-requirements.txt - + commands= nosetests \ [] \ No newline at end of file diff --git a/samples/server/petstore/flaskConnexion/git_push.sh b/samples/server/petstore/flaskConnexion/git_push.sh index ed374619b13..792320114fb 100644 --- a/samples/server/petstore/flaskConnexion/git_push.sh +++ b/samples/server/petstore/flaskConnexion/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/server/petstore/flaskConnexion/setup.py b/samples/server/petstore/flaskConnexion/setup.py index 7a1ce575d35..be5dce52ab7 100644 --- a/samples/server/petstore/flaskConnexion/setup.py +++ b/samples/server/petstore/flaskConnexion/setup.py @@ -26,6 +26,8 @@ setup( packages=find_packages(), package_data={'': ['swagger/swagger.yaml']}, include_package_data=True, + entry_points={ + 'console_scripts': ['swagger_server=swagger_server.__main__:main']}, long_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. """ diff --git a/samples/server/petstore/flaskConnexion/swagger_server/__main__.py b/samples/server/petstore/flaskConnexion/swagger_server/__main__.py index b0d689211d2..734cc4b3dd2 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/__main__.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/__main__.py @@ -1,11 +1,16 @@ #!/usr/bin/env python3 import connexion -from .encoder import JSONEncoder + +from swagger_server import encoder + + +def main(): + app = connexion.App(__name__, specification_dir='./swagger/') + app.app.json_encoder = encoder.JSONEncoder + app.add_api('swagger.yaml', arguments={'title': 'Swagger Petstore'}) + app.run(port=8080) if __name__ == '__main__': - app = connexion.App(__name__, specification_dir='./swagger/') - app.app.json_encoder = JSONEncoder - app.add_api('swagger.yaml', arguments={'title': '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.'}) - app.run(port=8080) + main() diff --git a/samples/server/petstore/flaskConnexion/swagger_server/controllers/pet_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/controllers/pet_controller.py index 5a999aae88f..5de865c908a 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/controllers/pet_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/controllers/pet_controller.py @@ -1,30 +1,31 @@ import connexion -from swagger_server.models.api_response import ApiResponse -from swagger_server.models.pet import Pet -from datetime import date, datetime -from typing import List, Dict -from six import iteritems -from ..util import deserialize_date, deserialize_datetime +import six + +from swagger_server.models.api_response import ApiResponse # noqa: E501 +from swagger_server.models.pet import Pet # noqa: E501 +from swagger_server import util -def add_pet(body): - """ - Add a new pet to the store - +def add_pet(body): # noqa: E501 + """Add a new pet to the store + + # noqa: E501 + :param body: Pet object that needs to be added to the store :type body: dict | bytes :rtype: None """ if connexion.request.is_json: - body = Pet.from_dict(connexion.request.get_json()) + body = Pet.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' -def delete_pet(petId, api_key=None): - """ - Deletes a pet - +def delete_pet(petId, api_key=None): # noqa: E501 + """Deletes a pet + + # noqa: E501 + :param petId: Pet id to delete :type petId: int :param api_key: @@ -35,10 +36,11 @@ def delete_pet(petId, api_key=None): return 'do some magic!' -def find_pets_by_status(status): - """ - Finds Pets by status - Multiple status values can be provided with comma separated strings +def find_pets_by_status(status): # noqa: E501 + """Finds Pets by status + + Multiple status values can be provided with comma separated strings # noqa: E501 + :param status: Status values that need to be considered for filter :type status: List[str] @@ -47,10 +49,11 @@ def find_pets_by_status(status): return 'do some magic!' -def find_pets_by_tags(tags): - """ - Finds Pets by tags - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. +def find_pets_by_tags(tags): # noqa: E501 + """Finds Pets by tags + + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. # noqa: E501 + :param tags: Tags to filter by :type tags: List[str] @@ -59,10 +62,11 @@ def find_pets_by_tags(tags): return 'do some magic!' -def get_pet_by_id(petId): - """ - Find pet by ID - Returns a single pet +def get_pet_by_id(petId): # noqa: E501 + """Find pet by ID + + Returns a single pet # noqa: E501 + :param petId: ID of pet to return :type petId: int @@ -71,24 +75,26 @@ def get_pet_by_id(petId): return 'do some magic!' -def update_pet(body): - """ - Update an existing pet - +def update_pet(body): # noqa: E501 + """Update an existing pet + + # noqa: E501 + :param body: Pet object that needs to be added to the store :type body: dict | bytes :rtype: None """ if connexion.request.is_json: - body = Pet.from_dict(connexion.request.get_json()) + body = Pet.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' -def update_pet_with_form(petId, name=None, status=None): - """ - Updates a pet in the store with form data - +def update_pet_with_form(petId, name=None, status=None): # noqa: E501 + """Updates a pet in the store with form data + + # noqa: E501 + :param petId: ID of pet that needs to be updated :type petId: int :param name: Updated name of the pet @@ -101,10 +107,11 @@ def update_pet_with_form(petId, name=None, status=None): return 'do some magic!' -def upload_file(petId, additionalMetadata=None, file=None): - """ - uploads an image - +def upload_file(petId, additionalMetadata=None, file=None): # noqa: E501 + """uploads an image + + # noqa: E501 + :param petId: ID of pet to update :type petId: int :param additionalMetadata: Additional data to pass to server diff --git a/samples/server/petstore/flaskConnexion/swagger_server/controllers/store_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/controllers/store_controller.py index 0cdcaf445dc..eae3546c21e 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/controllers/store_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/controllers/store_controller.py @@ -1,15 +1,15 @@ import connexion -from swagger_server.models.order import Order -from datetime import date, datetime -from typing import List, Dict -from six import iteritems -from ..util import deserialize_date, deserialize_datetime +import six + +from swagger_server.models.order import Order # noqa: E501 +from swagger_server import util -def delete_order(orderId): - """ - Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors +def delete_order(orderId): # noqa: E501 + """Delete purchase order by ID + + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors # noqa: E501 + :param orderId: ID of the order that needs to be deleted :type orderId: str @@ -18,20 +18,22 @@ def delete_order(orderId): return 'do some magic!' -def get_inventory(): - """ - Returns pet inventories by status - Returns a map of status codes to quantities +def get_inventory(): # noqa: E501 + """Returns pet inventories by status + + Returns a map of status codes to quantities # noqa: E501 + :rtype: Dict[str, int] """ return 'do some magic!' -def get_order_by_id(orderId): - """ - Find purchase order by ID - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions +def get_order_by_id(orderId): # noqa: E501 + """Find purchase order by ID + + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions # noqa: E501 + :param orderId: ID of pet that needs to be fetched :type orderId: int @@ -40,15 +42,16 @@ def get_order_by_id(orderId): return 'do some magic!' -def place_order(body): - """ - Place an order for a pet - +def place_order(body): # noqa: E501 + """Place an order for a pet + + # noqa: E501 + :param body: order placed for purchasing the pet :type body: dict | bytes :rtype: Order """ if connexion.request.is_json: - body = Order.from_dict(connexion.request.get_json()) + body = Order.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion/swagger_server/controllers/user_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/controllers/user_controller.py index 9a88626c5b8..c7c3ee3519a 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/controllers/user_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/controllers/user_controller.py @@ -1,57 +1,60 @@ import connexion -from swagger_server.models.user import User -from datetime import date, datetime -from typing import List, Dict -from six import iteritems -from ..util import deserialize_date, deserialize_datetime +import six + +from swagger_server.models.user import User # noqa: E501 +from swagger_server import util -def create_user(body): - """ - Create user - This can only be done by the logged in user. +def create_user(body): # noqa: E501 + """Create user + + This can only be done by the logged in user. # noqa: E501 + :param body: Created user object :type body: dict | bytes :rtype: None """ if connexion.request.is_json: - body = User.from_dict(connexion.request.get_json()) + body = User.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' -def create_users_with_array_input(body): - """ - Creates list of users with given input array - +def create_users_with_array_input(body): # noqa: E501 + """Creates list of users with given input array + + # noqa: E501 + :param body: List of user object :type body: list | bytes :rtype: None """ if connexion.request.is_json: - body = [User.from_dict(d) for d in connexion.request.get_json()] + body = [User.from_dict(d) for d in connexion.request.get_json()] # noqa: E501 return 'do some magic!' -def create_users_with_list_input(body): - """ - Creates list of users with given input array - +def create_users_with_list_input(body): # noqa: E501 + """Creates list of users with given input array + + # noqa: E501 + :param body: List of user object :type body: list | bytes :rtype: None """ if connexion.request.is_json: - body = [User.from_dict(d) for d in connexion.request.get_json()] + body = [User.from_dict(d) for d in connexion.request.get_json()] # noqa: E501 return 'do some magic!' -def delete_user(username): - """ - Delete user - This can only be done by the logged in user. +def delete_user(username): # noqa: E501 + """Delete user + + This can only be done by the logged in user. # noqa: E501 + :param username: The name that needs to be deleted :type username: str @@ -60,10 +63,11 @@ def delete_user(username): return 'do some magic!' -def get_user_by_name(username): - """ - Get user by user name - +def get_user_by_name(username): # noqa: E501 + """Get user by user name + + # noqa: E501 + :param username: The name that needs to be fetched. Use user1 for testing. :type username: str @@ -72,10 +76,11 @@ def get_user_by_name(username): return 'do some magic!' -def login_user(username, password): - """ - Logs user into the system - +def login_user(username, password): # noqa: E501 + """Logs user into the system + + # noqa: E501 + :param username: The user name for login :type username: str :param password: The password for login in clear text @@ -86,20 +91,22 @@ def login_user(username, password): return 'do some magic!' -def logout_user(): - """ - Logs out current logged in user session - +def logout_user(): # noqa: E501 + """Logs out current logged in user session + + # noqa: E501 + :rtype: None """ return 'do some magic!' -def update_user(username, body): - """ - Updated user - This can only be done by the logged in user. +def update_user(username, body): # noqa: E501 + """Updated user + + This can only be done by the logged in user. # noqa: E501 + :param username: name that need to be deleted :type username: str :param body: Updated user object @@ -108,5 +115,5 @@ def update_user(username, body): :rtype: None """ if connexion.request.is_json: - body = User.from_dict(connexion.request.get_json()) + body = User.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion/swagger_server/encoder.py b/samples/server/petstore/flaskConnexion/swagger_server/encoder.py index 3ff8cad5d72..61ba4721961 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/encoder.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/encoder.py @@ -1,6 +1,8 @@ -from six import iteritems -from swagger_server.models.base_model_ import Model from connexion.apps.flask_app import FlaskJSONEncoder +import six + +from swagger_server.models.base_model_ import Model + class JSONEncoder(FlaskJSONEncoder): include_nulls = False @@ -8,11 +10,11 @@ class JSONEncoder(FlaskJSONEncoder): def default(self, o): if isinstance(o, Model): dikt = {} - for attr, _ in iteritems(o.swagger_types): + for attr, _ in six.iteritems(o.swagger_types): value = getattr(o, attr) if value is None and not self.include_nulls: continue attr = o.attribute_map[attr] dikt[attr] = value return dikt - return FlaskJSONEncoder.default(self, o) \ No newline at end of file + return FlaskJSONEncoder.default(self, o) diff --git a/samples/server/petstore/flaskConnexion/swagger_server/models/__init__.py b/samples/server/petstore/flaskConnexion/swagger_server/models/__init__.py index 6571ad28e0f..fcf8253348d 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/models/__init__.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/models/__init__.py @@ -1,10 +1,11 @@ # coding: utf-8 +# flake8: noqa from __future__ import absolute_import # import models into model package -from .api_response import ApiResponse -from .category import Category -from .order import Order -from .pet import Pet -from .tag import Tag -from .user import User +from swagger_server.models.api_response import ApiResponse +from swagger_server.models.category import Category +from swagger_server.models.order import Order +from swagger_server.models.pet import Pet +from swagger_server.models.tag import Tag +from swagger_server.models.user import User diff --git a/samples/server/petstore/flaskConnexion/swagger_server/models/api_response.py b/samples/server/petstore/flaskConnexion/swagger_server/models/api_response.py index 8b7cecc3398..17e3d36ce61 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/models/api_response.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/models/api_response.py @@ -1,28 +1,28 @@ # coding: utf-8 from __future__ import absolute_import -from .base_model_ import Model -from datetime import date, datetime -from typing import List, Dict -from ..util import deserialize_model +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server import util class ApiResponse(Model): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ + def __init__(self, code: int=None, type: str=None, message: str=None): # noqa: E501 + """ApiResponse - a model defined in Swagger - def __init__(self, code: int=None, type: str=None, message: str=None): - """ - ApiResponse - a model defined in Swagger - - :param code: The code of this ApiResponse. + :param code: The code of this ApiResponse. # noqa: E501 :type code: int - :param type: The type of this ApiResponse. + :param type: The type of this ApiResponse. # noqa: E501 :type type: str - :param message: The message of this ApiResponse. + :param message: The message of this ApiResponse. # noqa: E501 :type message: str """ self.swagger_types = { @@ -43,20 +43,19 @@ class ApiResponse(Model): @classmethod def from_dict(cls, dikt) -> 'ApiResponse': - """ - Returns the dict as a model + """Returns the dict as a model :param dikt: A dict. :type: dict - :return: The ApiResponse of this ApiResponse. + :return: The ApiResponse of this ApiResponse. # noqa: E501 :rtype: ApiResponse """ - return deserialize_model(dikt, cls) + return util.deserialize_model(dikt, cls) @property def code(self) -> int: - """ - Gets the code of this ApiResponse. + """Gets the code of this ApiResponse. + :return: The code of this ApiResponse. :rtype: int @@ -65,8 +64,8 @@ class ApiResponse(Model): @code.setter def code(self, code: int): - """ - Sets the code of this ApiResponse. + """Sets the code of this ApiResponse. + :param code: The code of this ApiResponse. :type code: int @@ -76,8 +75,8 @@ class ApiResponse(Model): @property def type(self) -> str: - """ - Gets the type of this ApiResponse. + """Gets the type of this ApiResponse. + :return: The type of this ApiResponse. :rtype: str @@ -86,8 +85,8 @@ class ApiResponse(Model): @type.setter def type(self, type: str): - """ - Sets the type of this ApiResponse. + """Sets the type of this ApiResponse. + :param type: The type of this ApiResponse. :type type: str @@ -97,8 +96,8 @@ class ApiResponse(Model): @property def message(self) -> str: - """ - Gets the message of this ApiResponse. + """Gets the message of this ApiResponse. + :return: The message of this ApiResponse. :rtype: str @@ -107,12 +106,11 @@ class ApiResponse(Model): @message.setter def message(self, message: str): - """ - Sets the message of this ApiResponse. + """Sets the message of this ApiResponse. + :param message: The message of this ApiResponse. :type message: str """ self._message = message - diff --git a/samples/server/petstore/flaskConnexion/swagger_server/models/base_model_.py b/samples/server/petstore/flaskConnexion/swagger_server/models/base_model_.py index 5202b30fb63..97999c3d323 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/models/base_model_.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/models/base_model_.py @@ -1,34 +1,35 @@ -from pprint import pformat -from typing import TypeVar, Type -from six import iteritems -from ..util import deserialize_model +import pprint -T = TypeVar('T') +import six +import typing + +from swagger_server import util + +T = typing.TypeVar('T') class Model(object): - # swaggerTypes: The key is attribute name and the value is attribute type. + # swaggerTypes: The key is attribute name and the + # value is attribute type. swagger_types = {} - # attributeMap: The key is attribute name and the value is json key in definition. + # attributeMap: The key is attribute name and the + # value is json key in definition. attribute_map = {} @classmethod - def from_dict(cls: Type[T], dikt) -> T: - """ - Returns the dict as a model - """ - return deserialize_model(dikt, cls) + def from_dict(cls: typing.Type[T], dikt) -> T: + """Returns the dict as a model""" + return util.deserialize_model(dikt, cls) def to_dict(self): - """ - Returns the model properties as a dict + """Returns the model properties as a dict :rtype: dict """ result = {} - for attr, _ in iteritems(self.swagger_types): + for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( @@ -49,27 +50,20 @@ class Model(object): return result def to_str(self): - """ - Returns the string representation of the model + """Returns the string representation of the model :rtype: str """ - return pformat(self.to_dict()) + return pprint.pformat(self.to_dict()) def __repr__(self): - """ - For `print` and `pprint` - """ + """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): - """ - Returns true if both objects are equal - """ + """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 \ No newline at end of file + """Returns true if both objects are not equal""" + return not self == other diff --git a/samples/server/petstore/flaskConnexion/swagger_server/models/category.py b/samples/server/petstore/flaskConnexion/swagger_server/models/category.py index 42657e8447d..5a5bab5913d 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/models/category.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/models/category.py @@ -1,26 +1,26 @@ # coding: utf-8 from __future__ import absolute_import -from .base_model_ import Model -from datetime import date, datetime -from typing import List, Dict -from ..util import deserialize_model +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server import util class Category(Model): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ + def __init__(self, id: int=None, name: str=None): # noqa: E501 + """Category - a model defined in Swagger - def __init__(self, id: int=None, name: str=None): - """ - Category - a model defined in Swagger - - :param id: The id of this Category. + :param id: The id of this Category. # noqa: E501 :type id: int - :param name: The name of this Category. + :param name: The name of this Category. # noqa: E501 :type name: str """ self.swagger_types = { @@ -38,20 +38,19 @@ class Category(Model): @classmethod def from_dict(cls, dikt) -> 'Category': - """ - Returns the dict as a model + """Returns the dict as a model :param dikt: A dict. :type: dict - :return: The Category of this Category. + :return: The Category of this Category. # noqa: E501 :rtype: Category """ - return deserialize_model(dikt, cls) + return util.deserialize_model(dikt, cls) @property def id(self) -> int: - """ - Gets the id of this Category. + """Gets the id of this Category. + :return: The id of this Category. :rtype: int @@ -60,8 +59,8 @@ class Category(Model): @id.setter def id(self, id: int): - """ - Sets the id of this Category. + """Sets the id of this Category. + :param id: The id of this Category. :type id: int @@ -71,8 +70,8 @@ class Category(Model): @property def name(self) -> str: - """ - Gets the name of this Category. + """Gets the name of this Category. + :return: The name of this Category. :rtype: str @@ -81,12 +80,11 @@ class Category(Model): @name.setter def name(self, name: str): - """ - Sets the name of this Category. + """Sets the name of this Category. + :param name: The name of this Category. :type name: str """ self._name = name - diff --git a/samples/server/petstore/flaskConnexion/swagger_server/models/order.py b/samples/server/petstore/flaskConnexion/swagger_server/models/order.py index deffb5236b2..5b36925d07f 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/models/order.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/models/order.py @@ -1,34 +1,34 @@ # coding: utf-8 from __future__ import absolute_import -from .base_model_ import Model -from datetime import date, datetime -from typing import List, Dict -from ..util import deserialize_model +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server import util class Order(Model): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ + def __init__(self, id: int=None, pet_id: int=None, quantity: int=None, ship_date: datetime=None, status: str=None, complete: bool=False): # noqa: E501 + """Order - a model defined in Swagger - def __init__(self, id: int=None, pet_id: int=None, quantity: int=None, ship_date: datetime=None, status: str=None, complete: bool=False): - """ - Order - a model defined in Swagger - - :param id: The id of this Order. + :param id: The id of this Order. # noqa: E501 :type id: int - :param pet_id: The pet_id of this Order. + :param pet_id: The pet_id of this Order. # noqa: E501 :type pet_id: int - :param quantity: The quantity of this Order. + :param quantity: The quantity of this Order. # noqa: E501 :type quantity: int - :param ship_date: The ship_date of this Order. + :param ship_date: The ship_date of this Order. # noqa: E501 :type ship_date: datetime - :param status: The status of this Order. + :param status: The status of this Order. # noqa: E501 :type status: str - :param complete: The complete of this Order. + :param complete: The complete of this Order. # noqa: E501 :type complete: bool """ self.swagger_types = { @@ -58,20 +58,19 @@ class Order(Model): @classmethod def from_dict(cls, dikt) -> 'Order': - """ - Returns the dict as a model + """Returns the dict as a model :param dikt: A dict. :type: dict - :return: The Order of this Order. + :return: The Order of this Order. # noqa: E501 :rtype: Order """ - return deserialize_model(dikt, cls) + return util.deserialize_model(dikt, cls) @property def id(self) -> int: - """ - Gets the id of this Order. + """Gets the id of this Order. + :return: The id of this Order. :rtype: int @@ -80,8 +79,8 @@ class Order(Model): @id.setter def id(self, id: int): - """ - Sets the id of this Order. + """Sets the id of this Order. + :param id: The id of this Order. :type id: int @@ -91,8 +90,8 @@ class Order(Model): @property def pet_id(self) -> int: - """ - Gets the pet_id of this Order. + """Gets the pet_id of this Order. + :return: The pet_id of this Order. :rtype: int @@ -101,8 +100,8 @@ class Order(Model): @pet_id.setter def pet_id(self, pet_id: int): - """ - Sets the pet_id of this Order. + """Sets the pet_id of this Order. + :param pet_id: The pet_id of this Order. :type pet_id: int @@ -112,8 +111,8 @@ class Order(Model): @property def quantity(self) -> int: - """ - Gets the quantity of this Order. + """Gets the quantity of this Order. + :return: The quantity of this Order. :rtype: int @@ -122,8 +121,8 @@ class Order(Model): @quantity.setter def quantity(self, quantity: int): - """ - Sets the quantity of this Order. + """Sets the quantity of this Order. + :param quantity: The quantity of this Order. :type quantity: int @@ -133,8 +132,8 @@ class Order(Model): @property def ship_date(self) -> datetime: - """ - Gets the ship_date of this Order. + """Gets the ship_date of this Order. + :return: The ship_date of this Order. :rtype: datetime @@ -143,8 +142,8 @@ class Order(Model): @ship_date.setter def ship_date(self, ship_date: datetime): - """ - Sets the ship_date of this Order. + """Sets the ship_date of this Order. + :param ship_date: The ship_date of this Order. :type ship_date: datetime @@ -154,9 +153,9 @@ class Order(Model): @property def status(self) -> str: - """ - Gets the status of this Order. - Order Status + """Gets the status of this Order. + + Order Status # noqa: E501 :return: The status of this Order. :rtype: str @@ -165,14 +164,14 @@ class Order(Model): @status.setter def status(self, status: str): - """ - Sets the status of this Order. - Order Status + """Sets the status of this Order. + + Order Status # noqa: E501 :param status: The status of this Order. :type status: str """ - allowed_values = ["placed", "approved", "delivered"] + allowed_values = ["placed", "approved", "delivered"] # noqa: E501 if status not in allowed_values: raise ValueError( "Invalid value for `status` ({0}), must be one of {1}" @@ -183,8 +182,8 @@ class Order(Model): @property def complete(self) -> bool: - """ - Gets the complete of this Order. + """Gets the complete of this Order. + :return: The complete of this Order. :rtype: bool @@ -193,12 +192,11 @@ class Order(Model): @complete.setter def complete(self, complete: bool): - """ - Sets the complete of this Order. + """Sets the complete of this Order. + :param complete: The complete of this Order. :type complete: bool """ self._complete = complete - diff --git a/samples/server/petstore/flaskConnexion/swagger_server/models/pet.py b/samples/server/petstore/flaskConnexion/swagger_server/models/pet.py index 30173e024fb..5fa728911de 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/models/pet.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/models/pet.py @@ -1,36 +1,36 @@ # coding: utf-8 from __future__ import absolute_import -from swagger_server.models.category import Category -from swagger_server.models.tag import Tag -from .base_model_ import Model -from datetime import date, datetime -from typing import List, Dict -from ..util import deserialize_model +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server.models.category import Category # noqa: F401,E501 +from swagger_server.models.tag import Tag # noqa: F401,E501 +from swagger_server import util class Pet(Model): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ + def __init__(self, id: int=None, category: Category=None, name: str=None, photo_urls: List[str]=None, tags: List[Tag]=None, status: str=None): # noqa: E501 + """Pet - a model defined in Swagger - def __init__(self, id: int=None, category: Category=None, name: str=None, photo_urls: List[str]=None, tags: List[Tag]=None, status: str=None): - """ - Pet - a model defined in Swagger - - :param id: The id of this Pet. + :param id: The id of this Pet. # noqa: E501 :type id: int - :param category: The category of this Pet. + :param category: The category of this Pet. # noqa: E501 :type category: Category - :param name: The name of this Pet. + :param name: The name of this Pet. # noqa: E501 :type name: str - :param photo_urls: The photo_urls of this Pet. + :param photo_urls: The photo_urls of this Pet. # noqa: E501 :type photo_urls: List[str] - :param tags: The tags of this Pet. + :param tags: The tags of this Pet. # noqa: E501 :type tags: List[Tag] - :param status: The status of this Pet. + :param status: The status of this Pet. # noqa: E501 :type status: str """ self.swagger_types = { @@ -60,20 +60,19 @@ class Pet(Model): @classmethod def from_dict(cls, dikt) -> 'Pet': - """ - Returns the dict as a model + """Returns the dict as a model :param dikt: A dict. :type: dict - :return: The Pet of this Pet. + :return: The Pet of this Pet. # noqa: E501 :rtype: Pet """ - return deserialize_model(dikt, cls) + return util.deserialize_model(dikt, cls) @property def id(self) -> int: - """ - Gets the id of this Pet. + """Gets the id of this Pet. + :return: The id of this Pet. :rtype: int @@ -82,8 +81,8 @@ class Pet(Model): @id.setter def id(self, id: int): - """ - Sets the id of this Pet. + """Sets the id of this Pet. + :param id: The id of this Pet. :type id: int @@ -93,8 +92,8 @@ class Pet(Model): @property def category(self) -> Category: - """ - Gets the category of this Pet. + """Gets the category of this Pet. + :return: The category of this Pet. :rtype: Category @@ -103,8 +102,8 @@ class Pet(Model): @category.setter def category(self, category: Category): - """ - Sets the category of this Pet. + """Sets the category of this Pet. + :param category: The category of this Pet. :type category: Category @@ -114,8 +113,8 @@ class Pet(Model): @property def name(self) -> str: - """ - Gets the name of this Pet. + """Gets the name of this Pet. + :return: The name of this Pet. :rtype: str @@ -124,21 +123,21 @@ class Pet(Model): @name.setter def name(self, name: str): - """ - Sets the name of this Pet. + """Sets the name of this Pet. + :param name: The name of this Pet. :type name: str """ if name is None: - raise ValueError("Invalid value for `name`, must not be `None`") + raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name @property def photo_urls(self) -> List[str]: - """ - Gets the photo_urls of this Pet. + """Gets the photo_urls of this Pet. + :return: The photo_urls of this Pet. :rtype: List[str] @@ -147,21 +146,21 @@ class Pet(Model): @photo_urls.setter def photo_urls(self, photo_urls: List[str]): - """ - Sets the photo_urls of this Pet. + """Sets the photo_urls of this Pet. + :param photo_urls: The photo_urls of this Pet. :type photo_urls: List[str] """ if photo_urls is None: - raise ValueError("Invalid value for `photo_urls`, must not be `None`") + raise ValueError("Invalid value for `photo_urls`, must not be `None`") # noqa: E501 self._photo_urls = photo_urls @property def tags(self) -> List[Tag]: - """ - Gets the tags of this Pet. + """Gets the tags of this Pet. + :return: The tags of this Pet. :rtype: List[Tag] @@ -170,8 +169,8 @@ class Pet(Model): @tags.setter def tags(self, tags: List[Tag]): - """ - Sets the tags of this Pet. + """Sets the tags of this Pet. + :param tags: The tags of this Pet. :type tags: List[Tag] @@ -181,9 +180,9 @@ class Pet(Model): @property def status(self) -> str: - """ - Gets the status of this Pet. - pet status in the store + """Gets the status of this Pet. + + pet status in the store # noqa: E501 :return: The status of this Pet. :rtype: str @@ -192,14 +191,14 @@ class Pet(Model): @status.setter def status(self, status: str): - """ - Sets the status of this Pet. - pet status in the store + """Sets the status of this Pet. + + pet status in the store # noqa: E501 :param status: The status of this Pet. :type status: str """ - allowed_values = ["available", "pending", "sold"] + allowed_values = ["available", "pending", "sold"] # noqa: E501 if status not in allowed_values: raise ValueError( "Invalid value for `status` ({0}), must be one of {1}" @@ -207,4 +206,3 @@ class Pet(Model): ) self._status = status - diff --git a/samples/server/petstore/flaskConnexion/swagger_server/models/tag.py b/samples/server/petstore/flaskConnexion/swagger_server/models/tag.py index 9931b7476b1..62ba5b21be8 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/models/tag.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/models/tag.py @@ -1,26 +1,26 @@ # coding: utf-8 from __future__ import absolute_import -from .base_model_ import Model -from datetime import date, datetime -from typing import List, Dict -from ..util import deserialize_model +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server import util class Tag(Model): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ + def __init__(self, id: int=None, name: str=None): # noqa: E501 + """Tag - a model defined in Swagger - def __init__(self, id: int=None, name: str=None): - """ - Tag - a model defined in Swagger - - :param id: The id of this Tag. + :param id: The id of this Tag. # noqa: E501 :type id: int - :param name: The name of this Tag. + :param name: The name of this Tag. # noqa: E501 :type name: str """ self.swagger_types = { @@ -38,20 +38,19 @@ class Tag(Model): @classmethod def from_dict(cls, dikt) -> 'Tag': - """ - Returns the dict as a model + """Returns the dict as a model :param dikt: A dict. :type: dict - :return: The Tag of this Tag. + :return: The Tag of this Tag. # noqa: E501 :rtype: Tag """ - return deserialize_model(dikt, cls) + return util.deserialize_model(dikt, cls) @property def id(self) -> int: - """ - Gets the id of this Tag. + """Gets the id of this Tag. + :return: The id of this Tag. :rtype: int @@ -60,8 +59,8 @@ class Tag(Model): @id.setter def id(self, id: int): - """ - Sets the id of this Tag. + """Sets the id of this Tag. + :param id: The id of this Tag. :type id: int @@ -71,8 +70,8 @@ class Tag(Model): @property def name(self) -> str: - """ - Gets the name of this Tag. + """Gets the name of this Tag. + :return: The name of this Tag. :rtype: str @@ -81,12 +80,11 @@ class Tag(Model): @name.setter def name(self, name: str): - """ - Sets the name of this Tag. + """Sets the name of this Tag. + :param name: The name of this Tag. :type name: str """ self._name = name - diff --git a/samples/server/petstore/flaskConnexion/swagger_server/models/user.py b/samples/server/petstore/flaskConnexion/swagger_server/models/user.py index c4ea4d373bc..bf1fd963c70 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/models/user.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/models/user.py @@ -1,38 +1,38 @@ # coding: utf-8 from __future__ import absolute_import -from .base_model_ import Model -from datetime import date, datetime -from typing import List, Dict -from ..util import deserialize_model +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server import util class User(Model): - """ - NOTE: This class is auto generated by the swagger code generator program. + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ + def __init__(self, id: int=None, username: str=None, first_name: str=None, last_name: str=None, email: str=None, password: str=None, phone: str=None, user_status: int=None): # noqa: E501 + """User - a model defined in Swagger - def __init__(self, id: int=None, username: str=None, first_name: str=None, last_name: str=None, email: str=None, password: str=None, phone: str=None, user_status: int=None): - """ - User - a model defined in Swagger - - :param id: The id of this User. + :param id: The id of this User. # noqa: E501 :type id: int - :param username: The username of this User. + :param username: The username of this User. # noqa: E501 :type username: str - :param first_name: The first_name of this User. + :param first_name: The first_name of this User. # noqa: E501 :type first_name: str - :param last_name: The last_name of this User. + :param last_name: The last_name of this User. # noqa: E501 :type last_name: str - :param email: The email of this User. + :param email: The email of this User. # noqa: E501 :type email: str - :param password: The password of this User. + :param password: The password of this User. # noqa: E501 :type password: str - :param phone: The phone of this User. + :param phone: The phone of this User. # noqa: E501 :type phone: str - :param user_status: The user_status of this User. + :param user_status: The user_status of this User. # noqa: E501 :type user_status: int """ self.swagger_types = { @@ -68,20 +68,19 @@ class User(Model): @classmethod def from_dict(cls, dikt) -> 'User': - """ - Returns the dict as a model + """Returns the dict as a model :param dikt: A dict. :type: dict - :return: The User of this User. + :return: The User of this User. # noqa: E501 :rtype: User """ - return deserialize_model(dikt, cls) + return util.deserialize_model(dikt, cls) @property def id(self) -> int: - """ - Gets the id of this User. + """Gets the id of this User. + :return: The id of this User. :rtype: int @@ -90,8 +89,8 @@ class User(Model): @id.setter def id(self, id: int): - """ - Sets the id of this User. + """Sets the id of this User. + :param id: The id of this User. :type id: int @@ -101,8 +100,8 @@ class User(Model): @property def username(self) -> str: - """ - Gets the username of this User. + """Gets the username of this User. + :return: The username of this User. :rtype: str @@ -111,8 +110,8 @@ class User(Model): @username.setter def username(self, username: str): - """ - Sets the username of this User. + """Sets the username of this User. + :param username: The username of this User. :type username: str @@ -122,8 +121,8 @@ class User(Model): @property def first_name(self) -> str: - """ - Gets the first_name of this User. + """Gets the first_name of this User. + :return: The first_name of this User. :rtype: str @@ -132,8 +131,8 @@ class User(Model): @first_name.setter def first_name(self, first_name: str): - """ - Sets the first_name of this User. + """Sets the first_name of this User. + :param first_name: The first_name of this User. :type first_name: str @@ -143,8 +142,8 @@ class User(Model): @property def last_name(self) -> str: - """ - Gets the last_name of this User. + """Gets the last_name of this User. + :return: The last_name of this User. :rtype: str @@ -153,8 +152,8 @@ class User(Model): @last_name.setter def last_name(self, last_name: str): - """ - Sets the last_name of this User. + """Sets the last_name of this User. + :param last_name: The last_name of this User. :type last_name: str @@ -164,8 +163,8 @@ class User(Model): @property def email(self) -> str: - """ - Gets the email of this User. + """Gets the email of this User. + :return: The email of this User. :rtype: str @@ -174,8 +173,8 @@ class User(Model): @email.setter def email(self, email: str): - """ - Sets the email of this User. + """Sets the email of this User. + :param email: The email of this User. :type email: str @@ -185,8 +184,8 @@ class User(Model): @property def password(self) -> str: - """ - Gets the password of this User. + """Gets the password of this User. + :return: The password of this User. :rtype: str @@ -195,8 +194,8 @@ class User(Model): @password.setter def password(self, password: str): - """ - Sets the password of this User. + """Sets the password of this User. + :param password: The password of this User. :type password: str @@ -206,8 +205,8 @@ class User(Model): @property def phone(self) -> str: - """ - Gets the phone of this User. + """Gets the phone of this User. + :return: The phone of this User. :rtype: str @@ -216,8 +215,8 @@ class User(Model): @phone.setter def phone(self, phone: str): - """ - Sets the phone of this User. + """Sets the phone of this User. + :param phone: The phone of this User. :type phone: str @@ -227,9 +226,9 @@ class User(Model): @property def user_status(self) -> int: - """ - Gets the user_status of this User. - User Status + """Gets the user_status of this User. + + User Status # noqa: E501 :return: The user_status of this User. :rtype: int @@ -238,13 +237,12 @@ class User(Model): @user_status.setter def user_status(self, user_status: int): - """ - Sets the user_status of this User. - User Status + """Sets the user_status of this User. + + User Status # noqa: E501 :param user_status: The user_status of this User. :type user_status: int """ self._user_status = user_status - diff --git a/samples/server/petstore/flaskConnexion/swagger_server/swagger/swagger.yaml b/samples/server/petstore/flaskConnexion/swagger_server/swagger/swagger.yaml index 32000d3c2dc..ba2a870047d 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/swagger/swagger.yaml +++ b/samples/server/petstore/flaskConnexion/swagger_server/swagger/swagger.yaml @@ -108,11 +108,11 @@ paths: type: "array" items: type: "string" - default: "available" enum: - "available" - "pending" - "sold" + default: "available" collectionFormat: "csv" responses: 200: @@ -627,12 +627,12 @@ definitions: title: "Pet Order" description: "An order for a pets from the pet store" example: - petId: 6 - quantity: 1 id: 0 - shipDate: "2000-01-23T04:56:07.000+00:00" + petId: 6 complete: false status: "placed" + quantity: 1 + shipDate: "2000-01-23T04:56:07.000+00:00" xml: name: "Order" Category: @@ -646,8 +646,8 @@ definitions: title: "Pet catehgry" description: "A category for a pet" example: - name: "name" id: 6 + name: "name" xml: name: "Category" User: @@ -675,14 +675,14 @@ definitions: title: "a User" description: "A User who is purchasing from the pet store" example: - firstName: "firstName" - lastName: "lastName" - password: "password" - userStatus: 6 - phone: "phone" id: 0 - email: "email" + lastName: "lastName" + phone: "phone" username: "username" + email: "email" + userStatus: 6 + firstName: "firstName" + password: "password" xml: name: "User" Tag: @@ -696,8 +696,8 @@ definitions: title: "Pet Tag" description: "A tag for a pet" example: - name: "name" id: 1 + name: "name" xml: name: "Tag" Pet: @@ -738,20 +738,20 @@ definitions: title: "a Pet" description: "A pet for sale in the pet store" example: + tags: + - id: 1 + name: "name" + - id: 1 + name: "name" + id: 0 + category: + id: 6 + name: "name" + status: "available" + name: "doggie" photoUrls: - "photoUrls" - "photoUrls" - name: "doggie" - id: 0 - category: - name: "name" - id: 6 - tags: - - name: "name" - id: 1 - - name: "name" - id: 1 - status: "available" xml: name: "Pet" ApiResponse: @@ -767,9 +767,9 @@ definitions: title: "An uploaded response" description: "Describes the result of uploading an image resource" example: + message: "message" code: 0 type: "type" - message: "message" externalDocs: description: "Find out more about Swagger" url: "http://swagger.io" diff --git a/samples/server/petstore/flaskConnexion/swagger_server/test/__init__.py b/samples/server/petstore/flaskConnexion/swagger_server/test/__init__.py index 77b10c3a012..644506301ce 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/test/__init__.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/test/__init__.py @@ -1,8 +1,10 @@ -from flask_testing import TestCase -from ..encoder import JSONEncoder -import connexion import logging +import connexion +from flask_testing import TestCase + +from swagger_server.encoder import JSONEncoder + class BaseTestCase(TestCase): diff --git a/samples/server/petstore/flaskConnexion/swagger_server/test/test_pet_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/test/test_pet_controller.py index b99269a991a..fb4c34ea3e1 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/test/test_pet_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/test/test_pet_controller.py @@ -2,115 +2,124 @@ from __future__ import absolute_import -from swagger_server.models.api_response import ApiResponse -from swagger_server.models.pet import Pet -from . import BaseTestCase -from six import BytesIO from flask import json +from six import BytesIO + +from swagger_server.models.api_response import ApiResponse # noqa: E501 +from swagger_server.models.pet import Pet # noqa: E501 +from swagger_server.test import BaseTestCase class TestPetController(BaseTestCase): - """ PetController integration test stubs """ + """PetController integration test stubs""" def test_add_pet(self): - """ - Test case for add_pet + """Test case for add_pet Add a new pet to the store """ body = Pet() - response = self.client.open('/v2/pet', - method='POST', - data=json.dumps(body), - content_type='application/json') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/pet', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_delete_pet(self): - """ - Test case for delete_pet + """Test case for delete_pet Deletes a pet """ headers = [('api_key', 'api_key_example')] - response = self.client.open('/v2/pet/{petId}'.format(petId=789), - method='DELETE', - headers=headers) - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/pet/{petId}'.format(petId=789), + method='DELETE', + headers=headers) + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_find_pets_by_status(self): - """ - Test case for find_pets_by_status + """Test case for find_pets_by_status Finds Pets by status """ query_string = [('status', 'available')] - response = self.client.open('/v2/pet/findByStatus', - method='GET', - query_string=query_string) - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/pet/findByStatus', + method='GET', + query_string=query_string) + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_find_pets_by_tags(self): - """ - Test case for find_pets_by_tags + """Test case for find_pets_by_tags Finds Pets by tags """ query_string = [('tags', 'tags_example')] - response = self.client.open('/v2/pet/findByTags', - method='GET', - query_string=query_string) - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/pet/findByTags', + method='GET', + query_string=query_string) + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_get_pet_by_id(self): - """ - Test case for get_pet_by_id + """Test case for get_pet_by_id Find pet by ID """ - response = self.client.open('/v2/pet/{petId}'.format(petId=789), - method='GET') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/pet/{petId}'.format(petId=789), + method='GET') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_update_pet(self): - """ - Test case for update_pet + """Test case for update_pet Update an existing pet """ body = Pet() - response = self.client.open('/v2/pet', - method='PUT', - data=json.dumps(body), - content_type='application/json') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/pet', + method='PUT', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_update_pet_with_form(self): - """ - Test case for update_pet_with_form + """Test case for update_pet_with_form Updates a pet in the store with form data """ data = dict(name='name_example', status='status_example') - response = self.client.open('/v2/pet/{petId}'.format(petId=789), - method='POST', - data=data, - content_type='application/x-www-form-urlencoded') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/pet/{petId}'.format(petId=789), + method='POST', + data=data, + content_type='application/x-www-form-urlencoded') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_upload_file(self): - """ - Test case for upload_file + """Test case for upload_file uploads an image """ data = dict(additionalMetadata='additionalMetadata_example', file=(BytesIO(b'some file data'), 'file.txt')) - response = self.client.open('/v2/pet/{petId}/uploadImage'.format(petId=789), - method='POST', - data=data, - content_type='multipart/form-data') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/pet/{petId}/uploadImage'.format(petId=789), + method='POST', + data=data, + content_type='multipart/form-data') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) if __name__ == '__main__': diff --git a/samples/server/petstore/flaskConnexion/swagger_server/test/test_store_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/test/test_store_controller.py index 0a5360b4e25..854e18600fc 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/test/test_store_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/test/test_store_controller.py @@ -2,57 +2,62 @@ from __future__ import absolute_import -from swagger_server.models.order import Order -from . import BaseTestCase -from six import BytesIO from flask import json +from six import BytesIO + +from swagger_server.models.order import Order # noqa: E501 +from swagger_server.test import BaseTestCase class TestStoreController(BaseTestCase): - """ StoreController integration test stubs """ + """StoreController integration test stubs""" def test_delete_order(self): - """ - Test case for delete_order + """Test case for delete_order Delete purchase order by ID """ - response = self.client.open('/v2/store/order/{orderId}'.format(orderId='orderId_example'), - method='DELETE') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/store/order/{orderId}'.format(orderId='orderId_example'), + method='DELETE') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_get_inventory(self): - """ - Test case for get_inventory + """Test case for get_inventory Returns pet inventories by status """ - response = self.client.open('/v2/store/inventory', - method='GET') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/store/inventory', + method='GET') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_get_order_by_id(self): - """ - Test case for get_order_by_id + """Test case for get_order_by_id Find purchase order by ID """ - response = self.client.open('/v2/store/order/{orderId}'.format(orderId=5), - method='GET') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/store/order/{orderId}'.format(orderId=5), + method='GET') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_place_order(self): - """ - Test case for place_order + """Test case for place_order Place an order for a pet """ body = Order() - response = self.client.open('/v2/store/order', - method='POST', - data=json.dumps(body), - content_type='application/json') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/store/order', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) if __name__ == '__main__': diff --git a/samples/server/petstore/flaskConnexion/swagger_server/test/test_user_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/test/test_user_controller.py index 867de3c0150..30e1885afab 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/test/test_user_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/test/test_user_controller.py @@ -2,109 +2,118 @@ from __future__ import absolute_import -from swagger_server.models.user import User -from . import BaseTestCase -from six import BytesIO from flask import json +from six import BytesIO + +from swagger_server.models.user import User # noqa: E501 +from swagger_server.test import BaseTestCase class TestUserController(BaseTestCase): - """ UserController integration test stubs """ + """UserController integration test stubs""" def test_create_user(self): - """ - Test case for create_user + """Test case for create_user Create user """ body = User() - response = self.client.open('/v2/user', - method='POST', - data=json.dumps(body), - content_type='application/json') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/user', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_create_users_with_array_input(self): - """ - Test case for create_users_with_array_input + """Test case for create_users_with_array_input Creates list of users with given input array """ body = [User()] - response = self.client.open('/v2/user/createWithArray', - method='POST', - data=json.dumps(body), - content_type='application/json') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/user/createWithArray', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_create_users_with_list_input(self): - """ - Test case for create_users_with_list_input + """Test case for create_users_with_list_input Creates list of users with given input array """ body = [User()] - response = self.client.open('/v2/user/createWithList', - method='POST', - data=json.dumps(body), - content_type='application/json') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/user/createWithList', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_delete_user(self): - """ - Test case for delete_user + """Test case for delete_user Delete user """ - response = self.client.open('/v2/user/{username}'.format(username='username_example'), - method='DELETE') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/user/{username}'.format(username='username_example'), + method='DELETE') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_get_user_by_name(self): - """ - Test case for get_user_by_name + """Test case for get_user_by_name Get user by user name """ - response = self.client.open('/v2/user/{username}'.format(username='username_example'), - method='GET') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/user/{username}'.format(username='username_example'), + method='GET') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_login_user(self): - """ - Test case for login_user + """Test case for login_user Logs user into the system """ query_string = [('username', 'username_example'), ('password', 'password_example')] - response = self.client.open('/v2/user/login', - method='GET', - query_string=query_string) - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/user/login', + method='GET', + query_string=query_string) + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_logout_user(self): - """ - Test case for logout_user + """Test case for logout_user Logs out current logged in user session """ - response = self.client.open('/v2/user/logout', - method='GET') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/user/logout', + method='GET') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) def test_update_user(self): - """ - Test case for update_user + """Test case for update_user Updated user """ body = User() - response = self.client.open('/v2/user/{username}'.format(username='username_example'), - method='PUT', - data=json.dumps(body), - content_type='application/json') - self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + response = self.client.open( + '/v2/user/{username}'.format(username='username_example'), + method='PUT', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) if __name__ == '__main__': diff --git a/samples/server/petstore/flaskConnexion/swagger_server/util.py b/samples/server/petstore/flaskConnexion/swagger_server/util.py index 40c72d43ebd..527d1424c3d 100644 --- a/samples/server/petstore/flaskConnexion/swagger_server/util.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/util.py @@ -1,11 +1,11 @@ -from typing import GenericMeta -from datetime import datetime, date -from six import integer_types, iteritems +import datetime + +import six +import typing def _deserialize(data, klass): - """ - Deserializes dict, list, str into an object. + """Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. @@ -15,15 +15,15 @@ def _deserialize(data, klass): if data is None: return None - if klass in integer_types or klass in (float, str, bool): + if klass in six.integer_types or klass in (float, str, bool): return _deserialize_primitive(data, klass) elif klass == object: return _deserialize_object(data) - elif klass == date: + elif klass == datetime.date: return deserialize_date(data) - elif klass == datetime: + elif klass == datetime.datetime: return deserialize_datetime(data) - elif type(klass) == GenericMeta: + elif type(klass) == typing.GenericMeta: if klass.__extra__ == list: return _deserialize_list(data, klass.__args__[0]) if klass.__extra__ == dict: @@ -33,8 +33,7 @@ def _deserialize(data, klass): def _deserialize_primitive(data, klass): - """ - Deserializes to primitive type. + """Deserializes to primitive type. :param data: data to deserialize. :param klass: class literal. @@ -45,15 +44,14 @@ def _deserialize_primitive(data, klass): try: value = klass(data) except UnicodeEncodeError: - value = unicode(data) + value = six.u(data) except TypeError: value = data return value def _deserialize_object(value): - """ - Return a original value. + """Return a original value. :return: object. """ @@ -61,8 +59,7 @@ def _deserialize_object(value): def deserialize_date(string): - """ - Deserializes string to date. + """Deserializes string to date. :param string: str. :type string: str @@ -77,8 +74,7 @@ def deserialize_date(string): def deserialize_datetime(string): - """ - Deserializes string to datetime. + """Deserializes string to datetime. The string should be in iso8601 datetime format. @@ -95,8 +91,7 @@ def deserialize_datetime(string): def deserialize_model(data, klass): - """ - Deserializes list or dict to model. + """Deserializes list or dict to model. :param data: dict, list. :type data: dict | list @@ -108,7 +103,7 @@ def deserialize_model(data, klass): if not instance.swagger_types: return data - for attr, attr_type in iteritems(instance.swagger_types): + for attr, attr_type in six.iteritems(instance.swagger_types): if data is not None \ and instance.attribute_map[attr] in data \ and isinstance(data, (list, dict)): @@ -119,8 +114,7 @@ def deserialize_model(data, klass): def _deserialize_list(data, boxed_type): - """ - Deserializes a list and its elements. + """Deserializes a list and its elements. :param data: list to deserialize. :type data: list @@ -133,10 +127,8 @@ def _deserialize_list(data, boxed_type): for sub_data in data] - def _deserialize_dict(data, boxed_type): - """ - Deserializes a dict and its elements. + """Deserializes a dict and its elements. :param data: dict to deserialize. :type data: dict @@ -146,4 +138,4 @@ def _deserialize_dict(data, boxed_type): :rtype: dict """ return {k: _deserialize(v, boxed_type) - for k, v in iteritems(data)} + for k, v in six.iteritems(data)} diff --git a/samples/server/petstore/flaskConnexion/tox.ini b/samples/server/petstore/flaskConnexion/tox.ini index b696749b3a1..3e0b644eec4 100644 --- a/samples/server/petstore/flaskConnexion/tox.ini +++ b/samples/server/petstore/flaskConnexion/tox.ini @@ -4,7 +4,7 @@ envlist = py35 [testenv] deps=-r{toxinidir}/requirements.txt -r{toxinidir}/test-requirements.txt - + commands= nosetests \ [] \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Category.java index fb9207f4b5d..9f0206575f5 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Category.java @@ -92,21 +92,5 @@ public class Category { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/ModelApiResponse.java index 05911012313..07493e84825 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/ModelApiResponse.java @@ -114,21 +114,5 @@ public class ModelApiResponse { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Order.java index 987ef07d460..cdc21f722c9 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Order.java @@ -215,21 +215,5 @@ public class Order { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Pet.java index 430bbe805ce..5e5ff376294 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Pet.java @@ -234,21 +234,5 @@ public class Pet { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Tag.java index 709fef2cf11..15a8774252a 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Tag.java @@ -92,21 +92,5 @@ public class Tag { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/User.java b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/User.java index ba41fb76f80..689de768893 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/User.java @@ -224,21 +224,5 @@ public class User { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-controller-only/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework-controller-only/app/controllers/PetApiController.java index 74f975466b1..4ccf6a2aea9 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/controllers/PetApiController.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/controllers/PetApiController.java @@ -18,6 +18,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -25,10 +26,12 @@ import swagger.SwaggerUtils.ApiAction; public class PetApiController extends Controller { private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private PetApiController() { + private PetApiController(Configuration configuration) { mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -38,7 +41,9 @@ public class PetApiController extends Controller { Pet body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Pet.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -98,7 +103,9 @@ public class PetApiController extends Controller { Pet body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Pet.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } diff --git a/samples/server/petstore/java-play-framework-controller-only/app/controllers/StoreApiController.java b/samples/server/petstore/java-play-framework-controller-only/app/controllers/StoreApiController.java index a0cc3e27d57..3482251783b 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/controllers/StoreApiController.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/controllers/StoreApiController.java @@ -17,6 +17,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -24,10 +25,12 @@ import swagger.SwaggerUtils.ApiAction; public class StoreApiController extends Controller { private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private StoreApiController() { + private StoreApiController(Configuration configuration) { mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -52,7 +55,9 @@ public class StoreApiController extends Controller { Order body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Order.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } diff --git a/samples/server/petstore/java-play-framework-controller-only/app/controllers/UserApiController.java b/samples/server/petstore/java-play-framework-controller-only/app/controllers/UserApiController.java index ec0b0d53ef0..862e317a341 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/controllers/UserApiController.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/controllers/UserApiController.java @@ -17,6 +17,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -24,10 +25,12 @@ import swagger.SwaggerUtils.ApiAction; public class UserApiController extends Controller { private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private UserApiController() { + private UserApiController(Configuration configuration) { mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -37,7 +40,9 @@ public class UserApiController extends Controller { User body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), User.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -50,8 +55,10 @@ public class UserApiController extends Controller { List body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); - for (User curItem : body) { - curItem.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + for (User curItem : body) { + SwaggerUtils.validate(curItem); + } } } else { throw new IllegalArgumentException("'body' parameter is required"); @@ -65,8 +72,10 @@ public class UserApiController extends Controller { List body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); - for (User curItem : body) { - curItem.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + for (User curItem : body) { + SwaggerUtils.validate(curItem); + } } } else { throw new IllegalArgumentException("'body' parameter is required"); @@ -114,7 +123,9 @@ public class UserApiController extends Controller { User body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), User.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } diff --git a/samples/server/petstore/java-play-framework-controller-only/app/swagger/SwaggerUtils.java b/samples/server/petstore/java-play-framework-controller-only/app/swagger/SwaggerUtils.java index c7d8bd3de9e..d4900e02167 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/swagger/SwaggerUtils.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/swagger/SwaggerUtils.java @@ -9,6 +9,11 @@ import java.lang.annotation.Target; import java.text.SimpleDateFormat; import java.util.*; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + public class SwaggerUtils { @With(ApiCall.class) @@ -17,6 +22,22 @@ public class SwaggerUtils { public @interface ApiAction { } + public static void validate(T obj) { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + Set> constraintViolations = validator.validate(obj); + if (constraintViolations.size() > 0) { + StringBuilder errors = new StringBuilder(); + for (ConstraintViolation contraintes : constraintViolations) { + errors.append(String.format("%s.%s %s\n", + contraintes.getRootBeanClass().getSimpleName(), + contraintes.getPropertyPath(), + contraintes.getMessage())); + } + throw new RuntimeException("Bean validation : " + errors); + } + } + public static List parametersToList(String collectionFormat, String[] values){ List params = new ArrayList<>(); diff --git a/samples/server/petstore/java-play-framework-controller-only/conf/application.conf b/samples/server/petstore/java-play-framework-controller-only/conf/application.conf index 514ce684a77..c147af52f25 100644 --- a/samples/server/petstore/java-play-framework-controller-only/conf/application.conf +++ b/samples/server/petstore/java-play-framework-controller-only/conf/application.conf @@ -17,6 +17,15 @@ play.filters.headers.contentSecurityPolicy=null +# When using bean validation with the swagger api, the validator will check that every constraint is respected +# This is very useful when testing but could add a lot of overhead if you return a lot of data. Benchmark have +# shown that the time it takes to validate is exponential. +# If this is a concern in your application, or if you don't want to validate the output coming from your API for +# respecting its contract, set the "output" property below to "false". Since there is not a lot of data as input for +# an endpoint, I highly suggest you let the "input" property set to true. +useInputBeanValidation=true +useOutputBeanValidation=true + play.http.errorHandler="swagger.ErrorHandler" ## Akka diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesClass.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesClass.java index 7ad3b29d780..0d1d7a1fd98 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesClass.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesClass.java @@ -112,21 +112,5 @@ public class AdditionalPropertiesClass { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Animal.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Animal.java index 0b52bbf6382..2202fe1078e 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Animal.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Animal.java @@ -95,21 +95,5 @@ public class Animal { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AnimalFarm.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AnimalFarm.java index 44f4227ba5d..13a90b97be2 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AnimalFarm.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AnimalFarm.java @@ -51,21 +51,5 @@ public class AnimalFarm extends ArrayList { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayOfArrayOfNumberOnly.java index 19f3a4841b4..ebeb622cd16 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayOfArrayOfNumberOnly.java @@ -82,21 +82,5 @@ public class ArrayOfArrayOfNumberOnly { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayOfNumberOnly.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayOfNumberOnly.java index 4d232db89ef..193c2f77177 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayOfNumberOnly.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayOfNumberOnly.java @@ -82,21 +82,5 @@ public class ArrayOfNumberOnly { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayTest.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayTest.java index 3fc13073c1a..80cefa109d6 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayTest.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayTest.java @@ -143,21 +143,5 @@ public class ArrayTest { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Capitalization.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Capitalization.java index 1469630f874..f78ceeb9d0b 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Capitalization.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Capitalization.java @@ -180,21 +180,5 @@ public class Capitalization { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Cat.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Cat.java index ad587a0540e..a87f399d687 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Cat.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Cat.java @@ -72,21 +72,5 @@ public class Cat extends Animal { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Category.java index 572cd6ef3d2..c2a4222a8aa 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Category.java @@ -92,21 +92,5 @@ public class Category { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ClassModel.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ClassModel.java index 37313d2860b..ee8cd40ca40 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ClassModel.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ClassModel.java @@ -70,21 +70,5 @@ public class ClassModel { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Client.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Client.java index 8e4618db6b6..f14be52cf46 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Client.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Client.java @@ -70,21 +70,5 @@ public class Client { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Dog.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Dog.java index bd7ad700daa..27e3f5fdb25 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Dog.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Dog.java @@ -72,21 +72,5 @@ public class Dog extends Animal { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/EnumArrays.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/EnumArrays.java index a8f126b5124..a82c9ee422d 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/EnumArrays.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/EnumArrays.java @@ -164,21 +164,5 @@ public class EnumArrays { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/EnumTest.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/EnumTest.java index 165a4b02a0e..8b202da4f10 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/EnumTest.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/EnumTest.java @@ -233,21 +233,5 @@ public class EnumTest { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/FormatTest.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/FormatTest.java index b3293abc73b..5e70176abc7 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/FormatTest.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/FormatTest.java @@ -369,21 +369,5 @@ public class FormatTest { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/HasOnlyReadOnly.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/HasOnlyReadOnly.java index bc1644d165c..17d09b40692 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/HasOnlyReadOnly.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/HasOnlyReadOnly.java @@ -92,21 +92,5 @@ public class HasOnlyReadOnly { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/MapTest.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/MapTest.java index 3d8ced1fc41..7cd05af295f 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/MapTest.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/MapTest.java @@ -143,21 +143,5 @@ public class MapTest { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/MixedPropertiesAndAdditionalPropertiesClass.java index 3d8314f1e1c..e52678fa5c4 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/MixedPropertiesAndAdditionalPropertiesClass.java @@ -131,21 +131,5 @@ public class MixedPropertiesAndAdditionalPropertiesClass { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Model200Response.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Model200Response.java index 7e63d2a2ab9..1e0db95e010 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Model200Response.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Model200Response.java @@ -92,21 +92,5 @@ public class Model200Response { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelApiResponse.java index bdb4c3b1a35..a5505482e08 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelApiResponse.java @@ -114,21 +114,5 @@ public class ModelApiResponse { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelReturn.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelReturn.java index cab65161aae..89d3a0e25ff 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelReturn.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelReturn.java @@ -70,21 +70,5 @@ public class ModelReturn { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Name.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Name.java index 94466b89fbf..b17faa3cc5c 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Name.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Name.java @@ -137,21 +137,5 @@ public class Name { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/NumberOnly.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/NumberOnly.java index 4c56adea5c6..a54fece6268 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/NumberOnly.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/NumberOnly.java @@ -72,21 +72,5 @@ public class NumberOnly { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Order.java index ba0144ec429..50990892750 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Order.java @@ -215,21 +215,5 @@ public class Order { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/OuterComposite.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/OuterComposite.java index 78288a15e3b..92a8ca4c95a 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/OuterComposite.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/OuterComposite.java @@ -116,21 +116,5 @@ public class OuterComposite { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Pet.java index d1abd7c48aa..aaa139c566d 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Pet.java @@ -234,21 +234,5 @@ public class Pet { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ReadOnlyFirst.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ReadOnlyFirst.java index 1a3e4e7fcc2..693aa7eba34 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ReadOnlyFirst.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ReadOnlyFirst.java @@ -92,21 +92,5 @@ public class ReadOnlyFirst { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/SpecialModelName.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/SpecialModelName.java index fa827dbd77f..ff398610850 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/SpecialModelName.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/SpecialModelName.java @@ -70,21 +70,5 @@ public class SpecialModelName { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Tag.java index 033f9d61bd7..5426c883569 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Tag.java @@ -92,21 +92,5 @@ public class Tag { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/User.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/User.java index a479bb5e5f0..0308cc92681 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/User.java @@ -224,21 +224,5 @@ public class User { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/AnotherFakeApiController.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/AnotherFakeApiController.java index 6164019070f..a81d96a90a7 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/AnotherFakeApiController.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/AnotherFakeApiController.java @@ -16,6 +16,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -24,11 +25,13 @@ public class AnotherFakeApiController extends Controller { private final AnotherFakeApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private AnotherFakeApiController(AnotherFakeApiControllerImpInterface imp) { + private AnotherFakeApiController(Configuration configuration, AnotherFakeApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -38,12 +41,16 @@ public class AnotherFakeApiController extends Controller { Client body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Client.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } Client obj = imp.testSpecialTags(body); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiController.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiController.java index d9bcaed20a5..0e9f0e0a580 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiController.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiController.java @@ -20,6 +20,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -28,11 +29,13 @@ public class FakeApiController extends Controller { private final FakeApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private FakeApiController(FakeApiControllerImpInterface imp) { + private FakeApiController(Configuration configuration, FakeApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -42,7 +45,9 @@ public class FakeApiController extends Controller { Boolean body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Boolean.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { body = null; } @@ -57,12 +62,16 @@ public class FakeApiController extends Controller { OuterComposite body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), OuterComposite.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { body = null; } OuterComposite obj = imp.fakeOuterCompositeSerialize(body); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -73,12 +82,16 @@ public class FakeApiController extends Controller { BigDecimal body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), BigDecimal.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { body = null; } BigDecimal obj = imp.fakeOuterNumberSerialize(body); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -89,7 +102,9 @@ public class FakeApiController extends Controller { String body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), String.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { body = null; } @@ -104,12 +119,16 @@ public class FakeApiController extends Controller { Client body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Client.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } Client obj = imp.testClientModel(body); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -140,7 +159,7 @@ public class FakeApiController extends Controller { String valuenumber = (request().body().asMultipartFormData().asFormUrlEncoded().get("number"))[0]; BigDecimal number; if (valuenumber != null) { - number = Float.parseFloat(valuenumber); + number = new BigDecimal(valuenumber); } else { throw new IllegalArgumentException("'number' parameter is required"); } @@ -175,21 +194,21 @@ public class FakeApiController extends Controller { String value_byte = (request().body().asMultipartFormData().asFormUrlEncoded().get("byte"))[0]; byte[] _byte; if (value_byte != null) { - _byte = value_byte; + _byte = value_byte.getBytes(); } else { throw new IllegalArgumentException("'byte' parameter is required"); } String valuebinary = (request().body().asMultipartFormData().asFormUrlEncoded().get("binary"))[0]; byte[] binary; if (valuebinary != null) { - binary = valuebinary; + binary = valuebinary.getBytes(); } else { binary = null; } String valuedate = (request().body().asMultipartFormData().asFormUrlEncoded().get("date"))[0]; LocalDate date; if (valuedate != null) { - date = valuedate; + date = LocalDate.parse(valuedate); } else { date = null; } @@ -280,6 +299,22 @@ public class FakeApiController extends Controller { return ok(); } + @ApiAction + public Result testInlineAdditionalProperties() throws Exception { + JsonNode nodeparam = request().body().asJson(); + Object param; + if (nodeparam != null) { + param = mapper.readValue(nodeparam.toString(), Object.class); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(param); + } + } else { + throw new IllegalArgumentException("'param' parameter is required"); + } + imp.testInlineAdditionalProperties(param); + return ok(); + } + @ApiAction public Result testJsonFormData() throws Exception { String valueparam = (request().body().asMultipartFormData().asFormUrlEncoded().get("param"))[0]; diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiControllerImp.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiControllerImp.java index 36a6affba94..f4d890300e1 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiControllerImp.java @@ -17,7 +17,7 @@ public class FakeApiControllerImp implements FakeApiControllerImpInterface { @Override public Boolean fakeOuterBooleanSerialize(Boolean body) throws Exception { //Do your magic!!! - return new Boolean(); + return new Boolean(true); } @Override @@ -29,7 +29,7 @@ public class FakeApiControllerImp implements FakeApiControllerImpInterface { @Override public BigDecimal fakeOuterNumberSerialize(BigDecimal body) throws Exception { //Do your magic!!! - return new BigDecimal(); + return new BigDecimal(1.0); } @Override @@ -47,19 +47,21 @@ public class FakeApiControllerImp implements FakeApiControllerImpInterface { @Override public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws Exception { //Do your magic!!! - } @Override public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws Exception { //Do your magic!!! - + } + + @Override + public void testInlineAdditionalProperties(Object param) throws Exception { + //Do your magic!!! } @Override public void testJsonFormData(String param, String param2) throws Exception { //Do your magic!!! - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiControllerImpInterface.java index 210755319d2..48828746e09 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiControllerImpInterface.java @@ -29,6 +29,8 @@ public interface FakeApiControllerImpInterface { void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws Exception; + void testInlineAdditionalProperties(Object param) throws Exception; + void testJsonFormData(String param, String param2) throws Exception; } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeClassnameTags123ApiController.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeClassnameTags123ApiController.java index 785c5da877f..89c227fa5db 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeClassnameTags123ApiController.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeClassnameTags123ApiController.java @@ -16,6 +16,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -24,11 +25,13 @@ public class FakeClassnameTags123ApiController extends Controller { private final FakeClassnameTags123ApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private FakeClassnameTags123ApiController(FakeClassnameTags123ApiControllerImpInterface imp) { + private FakeClassnameTags123ApiController(Configuration configuration, FakeClassnameTags123ApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -38,12 +41,16 @@ public class FakeClassnameTags123ApiController extends Controller { Client body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Client.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } Client obj = imp.testClassname(body); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiController.java index 2ecdbcbdc0b..cab362abda5 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiController.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiController.java @@ -18,6 +18,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -26,11 +27,13 @@ public class PetApiController extends Controller { private final PetApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private PetApiController(PetApiControllerImpInterface imp) { + private PetApiController(Configuration configuration, PetApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -40,7 +43,9 @@ public class PetApiController extends Controller { Pet body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Pet.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -74,8 +79,10 @@ public class PetApiController extends Controller { status.add(curParam); } List obj = imp.findPetsByStatus(status); - for (Pet curItem : obj) { - curItem.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + for (Pet curItem : obj) { + SwaggerUtils.validate(curItem); + } } JsonNode result = mapper.valueToTree(obj); return ok(result); @@ -94,8 +101,10 @@ public class PetApiController extends Controller { tags.add(curParam); } List obj = imp.findPetsByTags(tags); - for (Pet curItem : obj) { - curItem.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + for (Pet curItem : obj) { + SwaggerUtils.validate(curItem); + } } JsonNode result = mapper.valueToTree(obj); return ok(result); @@ -104,7 +113,9 @@ public class PetApiController extends Controller { @ApiAction public Result getPetById(Long petId) throws Exception { Pet obj = imp.getPetById(petId); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -115,7 +126,9 @@ public class PetApiController extends Controller { Pet body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Pet.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -154,7 +167,9 @@ public class PetApiController extends Controller { } Http.MultipartFormData.FilePart file = request().body().asMultipartFormData().getFile("file"); ModelApiResponse obj = imp.uploadFile(petId, additionalMetadata, file); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiControllerImp.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiControllerImp.java index c5ef552623e..c025993f7c1 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiControllerImp.java @@ -15,13 +15,11 @@ public class PetApiControllerImp implements PetApiControllerImpInterface { @Override public void addPet(Pet body) throws Exception { //Do your magic!!! - } @Override public void deletePet(Long petId, String apiKey) throws Exception { //Do your magic!!! - } @Override @@ -45,13 +43,11 @@ public class PetApiControllerImp implements PetApiControllerImpInterface { @Override public void updatePet(Pet body) throws Exception { //Do your magic!!! - } @Override public void updatePetWithForm(Long petId, String name, String status) throws Exception { //Do your magic!!! - } @Override diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiController.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiController.java index 8254d1f992e..c94c5aa111a 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiController.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiController.java @@ -17,6 +17,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -25,11 +26,13 @@ public class StoreApiController extends Controller { private final StoreApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private StoreApiController(StoreApiControllerImpInterface imp) { + private StoreApiController(Configuration configuration, StoreApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -49,7 +52,9 @@ public class StoreApiController extends Controller { @ApiAction public Result getOrderById( @Min(1) @Max(5)Long orderId) throws Exception { Order obj = imp.getOrderById(orderId); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -60,12 +65,16 @@ public class StoreApiController extends Controller { Order body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Order.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } Order obj = imp.placeOrder(body); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiControllerImp.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiControllerImp.java index 88fce8c14ed..7c57d3d096c 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiControllerImp.java @@ -14,7 +14,6 @@ public class StoreApiControllerImp implements StoreApiControllerImpInterface { @Override public void deleteOrder(String orderId) throws Exception { //Do your magic!!! - } @Override diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiController.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiController.java index b0676d8e3d5..245d076858a 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiController.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiController.java @@ -17,6 +17,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -25,11 +26,13 @@ public class UserApiController extends Controller { private final UserApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private UserApiController(UserApiControllerImpInterface imp) { + private UserApiController(Configuration configuration, UserApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -39,7 +42,9 @@ public class UserApiController extends Controller { User body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), User.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -53,8 +58,10 @@ public class UserApiController extends Controller { List body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); - for (User curItem : body) { - curItem.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + for (User curItem : body) { + SwaggerUtils.validate(curItem); + } } } else { throw new IllegalArgumentException("'body' parameter is required"); @@ -69,8 +76,10 @@ public class UserApiController extends Controller { List body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); - for (User curItem : body) { - curItem.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + for (User curItem : body) { + SwaggerUtils.validate(curItem); + } } } else { throw new IllegalArgumentException("'body' parameter is required"); @@ -88,7 +97,9 @@ public class UserApiController extends Controller { @ApiAction public Result getUserByName(String username) throws Exception { User obj = imp.getUserByName(username); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -126,7 +137,9 @@ public class UserApiController extends Controller { User body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), User.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiControllerImp.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiControllerImp.java index 82b9003b0fc..0ea7a808b9a 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiControllerImp.java @@ -14,25 +14,21 @@ public class UserApiControllerImp implements UserApiControllerImpInterface { @Override public void createUser(User body) throws Exception { //Do your magic!!! - } @Override public void createUsersWithArrayInput(List body) throws Exception { //Do your magic!!! - } @Override public void createUsersWithListInput(List body) throws Exception { //Do your magic!!! - } @Override public void deleteUser(String username) throws Exception { //Do your magic!!! - } @Override @@ -50,13 +46,11 @@ public class UserApiControllerImp implements UserApiControllerImpInterface { @Override public void logoutUser() throws Exception { //Do your magic!!! - } @Override public void updateUser(String username, User body) throws Exception { //Do your magic!!! - } } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/swagger/SwaggerUtils.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/swagger/SwaggerUtils.java index c7d8bd3de9e..d4900e02167 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/swagger/SwaggerUtils.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/swagger/SwaggerUtils.java @@ -9,6 +9,11 @@ import java.lang.annotation.Target; import java.text.SimpleDateFormat; import java.util.*; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + public class SwaggerUtils { @With(ApiCall.class) @@ -17,6 +22,22 @@ public class SwaggerUtils { public @interface ApiAction { } + public static void validate(T obj) { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + Set> constraintViolations = validator.validate(obj); + if (constraintViolations.size() > 0) { + StringBuilder errors = new StringBuilder(); + for (ConstraintViolation contraintes : constraintViolations) { + errors.append(String.format("%s.%s %s\n", + contraintes.getRootBeanClass().getSimpleName(), + contraintes.getPropertyPath(), + contraintes.getMessage())); + } + throw new RuntimeException("Bean validation : " + errors); + } + } + public static List parametersToList(String collectionFormat, String[] values){ List params = new ArrayList<>(); diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/conf/application.conf b/samples/server/petstore/java-play-framework-fake-endpoints/conf/application.conf index a361b74d38e..46ce4312dd3 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/conf/application.conf +++ b/samples/server/petstore/java-play-framework-fake-endpoints/conf/application.conf @@ -17,6 +17,15 @@ play.filters.headers.contentSecurityPolicy=null +# When using bean validation with the swagger api, the validator will check that every constraint is respected +# This is very useful when testing but could add a lot of overhead if you return a lot of data. Benchmark have +# shown that the time it takes to validate is exponential. +# If this is a concern in your application, or if you don't want to validate the output coming from your API for +# respecting its contract, set the "output" property below to "false". Since there is not a lot of data as input for +# an endpoint, I highly suggest you let the "input" property set to true. +useInputBeanValidation=true +useOutputBeanValidation=true + play.http.errorHandler="swagger.ErrorHandler" ## Akka diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/conf/routes b/samples/server/petstore/java-play-framework-fake-endpoints/conf/routes index d3094cd2441..6a342645b5d 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/conf/routes +++ b/samples/server/petstore/java-play-framework-fake-endpoints/conf/routes @@ -16,6 +16,7 @@ POST /v2/fake/outer/string controllers.FakeApiController PATCH /v2/fake controllers.FakeApiController.testClientModel() POST /v2/fake controllers.FakeApiController.testEndpointParameters() GET /v2/fake controllers.FakeApiController.testEnumParameters() +POST /v2/fake/inline-additionalProperties controllers.FakeApiController.testInlineAdditionalProperties() GET /v2/fake/jsonFormData controllers.FakeApiController.testJsonFormData() #Functions for FakeClassnameTags123 API diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/public/swagger.json b/samples/server/petstore/java-play-framework-fake-endpoints/public/swagger.json index 52a10430087..8943dddcaa2 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/public/swagger.json +++ b/samples/server/petstore/java-play-framework-fake-endpoints/public/swagger.json @@ -978,7 +978,8 @@ } }, "x-contentType" : "application/json", - "x-accepts" : "application/json" + "x-accepts" : "application/json", + "missingReturnInfoIfNeeded" : "1.0" } }, "/fake/outer/string" : { @@ -1030,7 +1031,8 @@ } }, "x-contentType" : "application/json", - "x-accepts" : "application/json" + "x-accepts" : "application/json", + "missingReturnInfoIfNeeded" : "true" } }, "/fake/outer/composite" : { @@ -1088,6 +1090,34 @@ "x-accepts" : "application/json" } }, + "/fake/inline-additionalProperties" : { + "post" : { + "tags" : [ "fake" ], + "summary" : "test inline additionalProperties", + "description" : "", + "operationId" : "testInlineAdditionalProperties", + "consumes" : [ "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "param", + "description" : "request body", + "required" : true, + "schema" : { + "type" : "object", + "additionalProperties" : { + "type" : "string" + } + } + } ], + "responses" : { + "200" : { + "description" : "successful operation" + } + }, + "x-contentType" : "application/json", + "x-accepts" : "application/json" + } + }, "/another-fake/dummy" : { "patch" : { "tags" : [ "$another-fake?" ], diff --git a/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/Category.java index 399a6f2646a..44eb3a6bf7a 100644 --- a/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/Category.java @@ -91,6 +91,5 @@ public class Category { } return o.toString().replace("\n", "\n "); } - } diff --git a/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/ModelApiResponse.java index 9b3b2fc7e92..81a2333008b 100644 --- a/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/ModelApiResponse.java @@ -113,6 +113,5 @@ public class ModelApiResponse { } return o.toString().replace("\n", "\n "); } - } diff --git a/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/Order.java index 873a6aebd25..2290a967e4b 100644 --- a/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/Order.java @@ -213,6 +213,5 @@ public class Order { } return o.toString().replace("\n", "\n "); } - } diff --git a/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/Pet.java index e6adacc5d5c..ec14d76b41f 100644 --- a/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/Pet.java @@ -229,6 +229,5 @@ public class Pet { } return o.toString().replace("\n", "\n "); } - } diff --git a/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/Tag.java index cc8a86828f0..80b1d783b33 100644 --- a/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/Tag.java @@ -91,6 +91,5 @@ public class Tag { } return o.toString().replace("\n", "\n "); } - } diff --git a/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/User.java b/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/User.java index 5fc613edfbe..221a9f30591 100644 --- a/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework-no-bean-validation/app/apimodels/User.java @@ -223,6 +223,5 @@ public class User { } return o.toString().replace("\n", "\n "); } - } diff --git a/samples/server/petstore/java-play-framework-no-bean-validation/app/controllers/PetApiControllerImp.java b/samples/server/petstore/java-play-framework-no-bean-validation/app/controllers/PetApiControllerImp.java index 147b7e8bd65..ed9b151a238 100644 --- a/samples/server/petstore/java-play-framework-no-bean-validation/app/controllers/PetApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-bean-validation/app/controllers/PetApiControllerImp.java @@ -14,13 +14,11 @@ public class PetApiControllerImp implements PetApiControllerImpInterface { @Override public void addPet(Pet body) throws Exception { //Do your magic!!! - } @Override public void deletePet(Long petId, String apiKey) throws Exception { //Do your magic!!! - } @Override @@ -44,13 +42,11 @@ public class PetApiControllerImp implements PetApiControllerImpInterface { @Override public void updatePet(Pet body) throws Exception { //Do your magic!!! - } @Override public void updatePetWithForm(Long petId, String name, String status) throws Exception { //Do your magic!!! - } @Override diff --git a/samples/server/petstore/java-play-framework-no-bean-validation/app/controllers/StoreApiControllerImp.java b/samples/server/petstore/java-play-framework-no-bean-validation/app/controllers/StoreApiControllerImp.java index 181813a0462..b0d2d8f88a1 100644 --- a/samples/server/petstore/java-play-framework-no-bean-validation/app/controllers/StoreApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-bean-validation/app/controllers/StoreApiControllerImp.java @@ -13,7 +13,6 @@ public class StoreApiControllerImp implements StoreApiControllerImpInterface { @Override public void deleteOrder(String orderId) throws Exception { //Do your magic!!! - } @Override diff --git a/samples/server/petstore/java-play-framework-no-bean-validation/app/controllers/UserApiControllerImp.java b/samples/server/petstore/java-play-framework-no-bean-validation/app/controllers/UserApiControllerImp.java index 24d66f17eed..8bf12fe7c82 100644 --- a/samples/server/petstore/java-play-framework-no-bean-validation/app/controllers/UserApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-bean-validation/app/controllers/UserApiControllerImp.java @@ -13,25 +13,21 @@ public class UserApiControllerImp implements UserApiControllerImpInterface { @Override public void createUser(User body) throws Exception { //Do your magic!!! - } @Override public void createUsersWithArrayInput(List body) throws Exception { //Do your magic!!! - } @Override public void createUsersWithListInput(List body) throws Exception { //Do your magic!!! - } @Override public void deleteUser(String username) throws Exception { //Do your magic!!! - } @Override @@ -49,13 +45,11 @@ public class UserApiControllerImp implements UserApiControllerImpInterface { @Override public void logoutUser() throws Exception { //Do your magic!!! - } @Override public void updateUser(String username, User body) throws Exception { //Do your magic!!! - } } diff --git a/samples/server/petstore/java-play-framework-no-bean-validation/app/swagger/SwaggerUtils.java b/samples/server/petstore/java-play-framework-no-bean-validation/app/swagger/SwaggerUtils.java index c7d8bd3de9e..831a59d70be 100644 --- a/samples/server/petstore/java-play-framework-no-bean-validation/app/swagger/SwaggerUtils.java +++ b/samples/server/petstore/java-play-framework-no-bean-validation/app/swagger/SwaggerUtils.java @@ -9,6 +9,7 @@ import java.lang.annotation.Target; import java.text.SimpleDateFormat; import java.util.*; + public class SwaggerUtils { @With(ApiCall.class) @@ -17,6 +18,7 @@ public class SwaggerUtils { public @interface ApiAction { } + public static List parametersToList(String collectionFormat, String[] values){ List params = new ArrayList<>(); diff --git a/samples/server/petstore/java-play-framework-no-bean-validation/conf/application.conf b/samples/server/petstore/java-play-framework-no-bean-validation/conf/application.conf index a361b74d38e..21e3331bf27 100644 --- a/samples/server/petstore/java-play-framework-no-bean-validation/conf/application.conf +++ b/samples/server/petstore/java-play-framework-no-bean-validation/conf/application.conf @@ -17,6 +17,7 @@ play.filters.headers.contentSecurityPolicy=null + play.http.errorHandler="swagger.ErrorHandler" ## Akka diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Category.java index fb9207f4b5d..9f0206575f5 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Category.java @@ -92,21 +92,5 @@ public class Category { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/ModelApiResponse.java index 05911012313..07493e84825 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/ModelApiResponse.java @@ -114,21 +114,5 @@ public class ModelApiResponse { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Order.java index 987ef07d460..cdc21f722c9 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Order.java @@ -215,21 +215,5 @@ public class Order { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Pet.java index 430bbe805ce..5e5ff376294 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Pet.java @@ -234,21 +234,5 @@ public class Pet { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Tag.java index 709fef2cf11..15a8774252a 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Tag.java @@ -92,21 +92,5 @@ public class Tag { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/User.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/User.java index ba41fb76f80..689de768893 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/User.java @@ -224,21 +224,5 @@ public class User { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiController.java index c5fc05efb60..9422ed10ca0 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiController.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiController.java @@ -19,6 +19,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -27,11 +28,13 @@ public class PetApiController extends Controller { private final PetApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private PetApiController(PetApiControllerImpInterface imp) { + private PetApiController(Configuration configuration, PetApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -41,7 +44,9 @@ public class PetApiController extends Controller { Pet body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Pet.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -75,8 +80,10 @@ public class PetApiController extends Controller { status.add(curParam); } List obj = imp.findPetsByStatus(status); - for (Pet curItem : obj) { - curItem.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + for (Pet curItem : obj) { + SwaggerUtils.validate(curItem); + } } JsonNode result = mapper.valueToTree(obj); return ok(result); @@ -95,8 +102,10 @@ public class PetApiController extends Controller { tags.add(curParam); } List obj = imp.findPetsByTags(tags); - for (Pet curItem : obj) { - curItem.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + for (Pet curItem : obj) { + SwaggerUtils.validate(curItem); + } } JsonNode result = mapper.valueToTree(obj); return ok(result); @@ -105,7 +114,9 @@ public class PetApiController extends Controller { @ApiAction public Result getPetById(Long petId) { Pet obj = imp.getPetById(petId); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -116,7 +127,9 @@ public class PetApiController extends Controller { Pet body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Pet.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -155,7 +168,9 @@ public class PetApiController extends Controller { } Http.MultipartFormData.FilePart file = request().body().asMultipartFormData().getFile("file"); ModelApiResponse obj = imp.uploadFile(petId, additionalMetadata, file); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiControllerImp.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiControllerImp.java index bfe0bf69fff..e8d4a8b504a 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiControllerImp.java @@ -15,13 +15,11 @@ public class PetApiControllerImp implements PetApiControllerImpInterface { @Override public void addPet(Pet body) { //Do your magic!!! - } @Override public void deletePet(Long petId, String apiKey) { //Do your magic!!! - } @Override @@ -45,13 +43,11 @@ public class PetApiControllerImp implements PetApiControllerImpInterface { @Override public void updatePet(Pet body) { //Do your magic!!! - } @Override public void updatePetWithForm(Long petId, String name, String status) { //Do your magic!!! - } @Override diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiController.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiController.java index 147561498ea..e98dea01e40 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiController.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiController.java @@ -18,6 +18,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -26,11 +27,13 @@ public class StoreApiController extends Controller { private final StoreApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private StoreApiController(StoreApiControllerImpInterface imp) { + private StoreApiController(Configuration configuration, StoreApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -50,7 +53,9 @@ public class StoreApiController extends Controller { @ApiAction public Result getOrderById( @Min(1) @Max(5)Long orderId) { Order obj = imp.getOrderById(orderId); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -61,12 +66,16 @@ public class StoreApiController extends Controller { Order body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Order.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } Order obj = imp.placeOrder(body); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiControllerImp.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiControllerImp.java index 695b357ad91..6406ee40e1f 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiControllerImp.java @@ -14,7 +14,6 @@ public class StoreApiControllerImp implements StoreApiControllerImpInterface { @Override public void deleteOrder(String orderId) { //Do your magic!!! - } @Override diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiController.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiController.java index a0e94c65233..2afd562c7c8 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiController.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiController.java @@ -18,6 +18,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -26,11 +27,13 @@ public class UserApiController extends Controller { private final UserApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private UserApiController(UserApiControllerImpInterface imp) { + private UserApiController(Configuration configuration, UserApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -40,7 +43,9 @@ public class UserApiController extends Controller { User body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), User.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -54,8 +59,10 @@ public class UserApiController extends Controller { List body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); - for (User curItem : body) { - curItem.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + for (User curItem : body) { + SwaggerUtils.validate(curItem); + } } } else { throw new IllegalArgumentException("'body' parameter is required"); @@ -70,8 +77,10 @@ public class UserApiController extends Controller { List body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); - for (User curItem : body) { - curItem.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + for (User curItem : body) { + SwaggerUtils.validate(curItem); + } } } else { throw new IllegalArgumentException("'body' parameter is required"); @@ -89,7 +98,9 @@ public class UserApiController extends Controller { @ApiAction public Result getUserByName(String username) { User obj = imp.getUserByName(username); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -127,7 +138,9 @@ public class UserApiController extends Controller { User body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), User.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiControllerImp.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiControllerImp.java index aed4ff87261..a6a588b6c8e 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiControllerImp.java @@ -14,25 +14,21 @@ public class UserApiControllerImp implements UserApiControllerImpInterface { @Override public void createUser(User body) { //Do your magic!!! - } @Override public void createUsersWithArrayInput(List body) { //Do your magic!!! - } @Override public void createUsersWithListInput(List body) { //Do your magic!!! - } @Override public void deleteUser(String username) { //Do your magic!!! - } @Override @@ -50,13 +46,11 @@ public class UserApiControllerImp implements UserApiControllerImpInterface { @Override public void logoutUser() { //Do your magic!!! - } @Override public void updateUser(String username, User body) { //Do your magic!!! - } } diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/swagger/SwaggerUtils.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/swagger/SwaggerUtils.java index c7d8bd3de9e..d4900e02167 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/swagger/SwaggerUtils.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/swagger/SwaggerUtils.java @@ -9,6 +9,11 @@ import java.lang.annotation.Target; import java.text.SimpleDateFormat; import java.util.*; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + public class SwaggerUtils { @With(ApiCall.class) @@ -17,6 +22,22 @@ public class SwaggerUtils { public @interface ApiAction { } + public static void validate(T obj) { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + Set> constraintViolations = validator.validate(obj); + if (constraintViolations.size() > 0) { + StringBuilder errors = new StringBuilder(); + for (ConstraintViolation contraintes : constraintViolations) { + errors.append(String.format("%s.%s %s\n", + contraintes.getRootBeanClass().getSimpleName(), + contraintes.getPropertyPath(), + contraintes.getMessage())); + } + throw new RuntimeException("Bean validation : " + errors); + } + } + public static List parametersToList(String collectionFormat, String[] values){ List params = new ArrayList<>(); diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/conf/application.conf b/samples/server/petstore/java-play-framework-no-exception-handling/conf/application.conf index 9b6a9566c96..2b8e956dae5 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/conf/application.conf +++ b/samples/server/petstore/java-play-framework-no-exception-handling/conf/application.conf @@ -17,6 +17,15 @@ play.filters.headers.contentSecurityPolicy=null +# When using bean validation with the swagger api, the validator will check that every constraint is respected +# This is very useful when testing but could add a lot of overhead if you return a lot of data. Benchmark have +# shown that the time it takes to validate is exponential. +# If this is a concern in your application, or if you don't want to validate the output coming from your API for +# respecting its contract, set the "output" property below to "false". Since there is not a lot of data as input for +# an endpoint, I highly suggest you let the "input" property set to true. +useInputBeanValidation=true +useOutputBeanValidation=true + ## Akka # https://www.playframework.com/documentation/latest/ScalaAkka#Configuration diff --git a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Category.java index fb9207f4b5d..9f0206575f5 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Category.java @@ -92,21 +92,5 @@ public class Category { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/ModelApiResponse.java index 05911012313..07493e84825 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/ModelApiResponse.java @@ -114,21 +114,5 @@ public class ModelApiResponse { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Order.java index 987ef07d460..cdc21f722c9 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Order.java @@ -215,21 +215,5 @@ public class Order { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Pet.java index 430bbe805ce..5e5ff376294 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Pet.java @@ -234,21 +234,5 @@ public class Pet { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Tag.java index 709fef2cf11..15a8774252a 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Tag.java @@ -92,21 +92,5 @@ public class Tag { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/User.java b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/User.java index ba41fb76f80..689de768893 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/User.java @@ -224,21 +224,5 @@ public class User { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-interface/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework-no-interface/app/controllers/PetApiController.java index e1f3f0b0a21..eb522b1f8f5 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/controllers/PetApiController.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/controllers/PetApiController.java @@ -18,6 +18,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -26,11 +27,13 @@ public class PetApiController extends Controller { private final PetApiControllerImp imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private PetApiController(PetApiControllerImp imp) { + private PetApiController(Configuration configuration, PetApiControllerImp imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -40,7 +43,9 @@ public class PetApiController extends Controller { Pet body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Pet.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -74,8 +79,10 @@ public class PetApiController extends Controller { status.add(curParam); } List obj = imp.findPetsByStatus(status); - for (Pet curItem : obj) { - curItem.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + for (Pet curItem : obj) { + SwaggerUtils.validate(curItem); + } } JsonNode result = mapper.valueToTree(obj); return ok(result); @@ -94,8 +101,10 @@ public class PetApiController extends Controller { tags.add(curParam); } List obj = imp.findPetsByTags(tags); - for (Pet curItem : obj) { - curItem.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + for (Pet curItem : obj) { + SwaggerUtils.validate(curItem); + } } JsonNode result = mapper.valueToTree(obj); return ok(result); @@ -104,7 +113,9 @@ public class PetApiController extends Controller { @ApiAction public Result getPetById(Long petId) throws Exception { Pet obj = imp.getPetById(petId); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -115,7 +126,9 @@ public class PetApiController extends Controller { Pet body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Pet.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -154,7 +167,9 @@ public class PetApiController extends Controller { } Http.MultipartFormData.FilePart file = request().body().asMultipartFormData().getFile("file"); ModelApiResponse obj = imp.uploadFile(petId, additionalMetadata, file); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } diff --git a/samples/server/petstore/java-play-framework-no-interface/app/controllers/PetApiControllerImp.java b/samples/server/petstore/java-play-framework-no-interface/app/controllers/PetApiControllerImp.java index f24f8ee836d..3af35ea5303 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/controllers/PetApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/controllers/PetApiControllerImp.java @@ -15,13 +15,11 @@ public class PetApiControllerImp { public void addPet(Pet body) throws Exception { //Do your magic!!! - } public void deletePet(Long petId, String apiKey) throws Exception { //Do your magic!!! - } @@ -45,13 +43,11 @@ public class PetApiControllerImp { public void updatePet(Pet body) throws Exception { //Do your magic!!! - } public void updatePetWithForm(Long petId, String name, String status) throws Exception { //Do your magic!!! - } diff --git a/samples/server/petstore/java-play-framework-no-interface/app/controllers/StoreApiController.java b/samples/server/petstore/java-play-framework-no-interface/app/controllers/StoreApiController.java index 2c0b41176ce..e5829bb4d81 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/controllers/StoreApiController.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/controllers/StoreApiController.java @@ -17,6 +17,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -25,11 +26,13 @@ public class StoreApiController extends Controller { private final StoreApiControllerImp imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private StoreApiController(StoreApiControllerImp imp) { + private StoreApiController(Configuration configuration, StoreApiControllerImp imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -49,7 +52,9 @@ public class StoreApiController extends Controller { @ApiAction public Result getOrderById( @Min(1) @Max(5)Long orderId) throws Exception { Order obj = imp.getOrderById(orderId); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -60,12 +65,16 @@ public class StoreApiController extends Controller { Order body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Order.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } Order obj = imp.placeOrder(body); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } diff --git a/samples/server/petstore/java-play-framework-no-interface/app/controllers/StoreApiControllerImp.java b/samples/server/petstore/java-play-framework-no-interface/app/controllers/StoreApiControllerImp.java index e4cbe331a22..119afe97fbf 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/controllers/StoreApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/controllers/StoreApiControllerImp.java @@ -14,7 +14,6 @@ public class StoreApiControllerImp { public void deleteOrder(String orderId) throws Exception { //Do your magic!!! - } diff --git a/samples/server/petstore/java-play-framework-no-interface/app/controllers/UserApiController.java b/samples/server/petstore/java-play-framework-no-interface/app/controllers/UserApiController.java index 05f0a4eefed..8bb48133af9 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/controllers/UserApiController.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/controllers/UserApiController.java @@ -17,6 +17,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -25,11 +26,13 @@ public class UserApiController extends Controller { private final UserApiControllerImp imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private UserApiController(UserApiControllerImp imp) { + private UserApiController(Configuration configuration, UserApiControllerImp imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -39,7 +42,9 @@ public class UserApiController extends Controller { User body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), User.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -53,8 +58,10 @@ public class UserApiController extends Controller { List body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); - for (User curItem : body) { - curItem.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + for (User curItem : body) { + SwaggerUtils.validate(curItem); + } } } else { throw new IllegalArgumentException("'body' parameter is required"); @@ -69,8 +76,10 @@ public class UserApiController extends Controller { List body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); - for (User curItem : body) { - curItem.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + for (User curItem : body) { + SwaggerUtils.validate(curItem); + } } } else { throw new IllegalArgumentException("'body' parameter is required"); @@ -88,7 +97,9 @@ public class UserApiController extends Controller { @ApiAction public Result getUserByName(String username) throws Exception { User obj = imp.getUserByName(username); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -126,7 +137,9 @@ public class UserApiController extends Controller { User body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), User.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } diff --git a/samples/server/petstore/java-play-framework-no-interface/app/controllers/UserApiControllerImp.java b/samples/server/petstore/java-play-framework-no-interface/app/controllers/UserApiControllerImp.java index 06d9b91f681..569811fe095 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/controllers/UserApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/controllers/UserApiControllerImp.java @@ -14,25 +14,21 @@ public class UserApiControllerImp { public void createUser(User body) throws Exception { //Do your magic!!! - } public void createUsersWithArrayInput(List body) throws Exception { //Do your magic!!! - } public void createUsersWithListInput(List body) throws Exception { //Do your magic!!! - } public void deleteUser(String username) throws Exception { //Do your magic!!! - } @@ -50,13 +46,11 @@ public class UserApiControllerImp { public void logoutUser() throws Exception { //Do your magic!!! - } public void updateUser(String username, User body) throws Exception { //Do your magic!!! - } } diff --git a/samples/server/petstore/java-play-framework-no-interface/app/swagger/SwaggerUtils.java b/samples/server/petstore/java-play-framework-no-interface/app/swagger/SwaggerUtils.java index c7d8bd3de9e..d4900e02167 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/swagger/SwaggerUtils.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/swagger/SwaggerUtils.java @@ -9,6 +9,11 @@ import java.lang.annotation.Target; import java.text.SimpleDateFormat; import java.util.*; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + public class SwaggerUtils { @With(ApiCall.class) @@ -17,6 +22,22 @@ public class SwaggerUtils { public @interface ApiAction { } + public static void validate(T obj) { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + Set> constraintViolations = validator.validate(obj); + if (constraintViolations.size() > 0) { + StringBuilder errors = new StringBuilder(); + for (ConstraintViolation contraintes : constraintViolations) { + errors.append(String.format("%s.%s %s\n", + contraintes.getRootBeanClass().getSimpleName(), + contraintes.getPropertyPath(), + contraintes.getMessage())); + } + throw new RuntimeException("Bean validation : " + errors); + } + } + public static List parametersToList(String collectionFormat, String[] values){ List params = new ArrayList<>(); diff --git a/samples/server/petstore/java-play-framework-no-interface/conf/application.conf b/samples/server/petstore/java-play-framework-no-interface/conf/application.conf index 514ce684a77..c147af52f25 100644 --- a/samples/server/petstore/java-play-framework-no-interface/conf/application.conf +++ b/samples/server/petstore/java-play-framework-no-interface/conf/application.conf @@ -17,6 +17,15 @@ play.filters.headers.contentSecurityPolicy=null +# When using bean validation with the swagger api, the validator will check that every constraint is respected +# This is very useful when testing but could add a lot of overhead if you return a lot of data. Benchmark have +# shown that the time it takes to validate is exponential. +# If this is a concern in your application, or if you don't want to validate the output coming from your API for +# respecting its contract, set the "output" property below to "false". Since there is not a lot of data as input for +# an endpoint, I highly suggest you let the "input" property set to true. +useInputBeanValidation=true +useOutputBeanValidation=true + play.http.errorHandler="swagger.ErrorHandler" ## Akka diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Category.java index fb9207f4b5d..9f0206575f5 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Category.java @@ -92,21 +92,5 @@ public class Category { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/ModelApiResponse.java index 05911012313..07493e84825 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/ModelApiResponse.java @@ -114,21 +114,5 @@ public class ModelApiResponse { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Order.java index 987ef07d460..cdc21f722c9 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Order.java @@ -215,21 +215,5 @@ public class Order { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Pet.java index 430bbe805ce..5e5ff376294 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Pet.java @@ -234,21 +234,5 @@ public class Pet { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Tag.java index 709fef2cf11..15a8774252a 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Tag.java @@ -92,21 +92,5 @@ public class Tag { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/User.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/User.java index ba41fb76f80..689de768893 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/User.java @@ -224,21 +224,5 @@ public class User { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiController.java index 2ecdbcbdc0b..cab362abda5 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiController.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiController.java @@ -18,6 +18,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -26,11 +27,13 @@ public class PetApiController extends Controller { private final PetApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private PetApiController(PetApiControllerImpInterface imp) { + private PetApiController(Configuration configuration, PetApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -40,7 +43,9 @@ public class PetApiController extends Controller { Pet body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Pet.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -74,8 +79,10 @@ public class PetApiController extends Controller { status.add(curParam); } List obj = imp.findPetsByStatus(status); - for (Pet curItem : obj) { - curItem.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + for (Pet curItem : obj) { + SwaggerUtils.validate(curItem); + } } JsonNode result = mapper.valueToTree(obj); return ok(result); @@ -94,8 +101,10 @@ public class PetApiController extends Controller { tags.add(curParam); } List obj = imp.findPetsByTags(tags); - for (Pet curItem : obj) { - curItem.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + for (Pet curItem : obj) { + SwaggerUtils.validate(curItem); + } } JsonNode result = mapper.valueToTree(obj); return ok(result); @@ -104,7 +113,9 @@ public class PetApiController extends Controller { @ApiAction public Result getPetById(Long petId) throws Exception { Pet obj = imp.getPetById(petId); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -115,7 +126,9 @@ public class PetApiController extends Controller { Pet body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Pet.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -154,7 +167,9 @@ public class PetApiController extends Controller { } Http.MultipartFormData.FilePart file = request().body().asMultipartFormData().getFile("file"); ModelApiResponse obj = imp.uploadFile(petId, additionalMetadata, file); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiControllerImp.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiControllerImp.java index c5ef552623e..c025993f7c1 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiControllerImp.java @@ -15,13 +15,11 @@ public class PetApiControllerImp implements PetApiControllerImpInterface { @Override public void addPet(Pet body) throws Exception { //Do your magic!!! - } @Override public void deletePet(Long petId, String apiKey) throws Exception { //Do your magic!!! - } @Override @@ -45,13 +43,11 @@ public class PetApiControllerImp implements PetApiControllerImpInterface { @Override public void updatePet(Pet body) throws Exception { //Do your magic!!! - } @Override public void updatePetWithForm(Long petId, String name, String status) throws Exception { //Do your magic!!! - } @Override diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiController.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiController.java index 8254d1f992e..c94c5aa111a 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiController.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiController.java @@ -17,6 +17,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -25,11 +26,13 @@ public class StoreApiController extends Controller { private final StoreApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private StoreApiController(StoreApiControllerImpInterface imp) { + private StoreApiController(Configuration configuration, StoreApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -49,7 +52,9 @@ public class StoreApiController extends Controller { @ApiAction public Result getOrderById( @Min(1) @Max(5)Long orderId) throws Exception { Order obj = imp.getOrderById(orderId); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -60,12 +65,16 @@ public class StoreApiController extends Controller { Order body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Order.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } Order obj = imp.placeOrder(body); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiControllerImp.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiControllerImp.java index 88fce8c14ed..7c57d3d096c 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiControllerImp.java @@ -14,7 +14,6 @@ public class StoreApiControllerImp implements StoreApiControllerImpInterface { @Override public void deleteOrder(String orderId) throws Exception { //Do your magic!!! - } @Override diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiController.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiController.java index b0676d8e3d5..245d076858a 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiController.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiController.java @@ -17,6 +17,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -25,11 +26,13 @@ public class UserApiController extends Controller { private final UserApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private UserApiController(UserApiControllerImpInterface imp) { + private UserApiController(Configuration configuration, UserApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -39,7 +42,9 @@ public class UserApiController extends Controller { User body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), User.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -53,8 +58,10 @@ public class UserApiController extends Controller { List body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); - for (User curItem : body) { - curItem.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + for (User curItem : body) { + SwaggerUtils.validate(curItem); + } } } else { throw new IllegalArgumentException("'body' parameter is required"); @@ -69,8 +76,10 @@ public class UserApiController extends Controller { List body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); - for (User curItem : body) { - curItem.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + for (User curItem : body) { + SwaggerUtils.validate(curItem); + } } } else { throw new IllegalArgumentException("'body' parameter is required"); @@ -88,7 +97,9 @@ public class UserApiController extends Controller { @ApiAction public Result getUserByName(String username) throws Exception { User obj = imp.getUserByName(username); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -126,7 +137,9 @@ public class UserApiController extends Controller { User body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), User.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiControllerImp.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiControllerImp.java index 82b9003b0fc..0ea7a808b9a 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiControllerImp.java @@ -14,25 +14,21 @@ public class UserApiControllerImp implements UserApiControllerImpInterface { @Override public void createUser(User body) throws Exception { //Do your magic!!! - } @Override public void createUsersWithArrayInput(List body) throws Exception { //Do your magic!!! - } @Override public void createUsersWithListInput(List body) throws Exception { //Do your magic!!! - } @Override public void deleteUser(String username) throws Exception { //Do your magic!!! - } @Override @@ -50,13 +46,11 @@ public class UserApiControllerImp implements UserApiControllerImpInterface { @Override public void logoutUser() throws Exception { //Do your magic!!! - } @Override public void updateUser(String username, User body) throws Exception { //Do your magic!!! - } } diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/swagger/SwaggerUtils.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/swagger/SwaggerUtils.java index c7d8bd3de9e..d4900e02167 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/swagger/SwaggerUtils.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/swagger/SwaggerUtils.java @@ -9,6 +9,11 @@ import java.lang.annotation.Target; import java.text.SimpleDateFormat; import java.util.*; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + public class SwaggerUtils { @With(ApiCall.class) @@ -17,6 +22,22 @@ public class SwaggerUtils { public @interface ApiAction { } + public static void validate(T obj) { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + Set> constraintViolations = validator.validate(obj); + if (constraintViolations.size() > 0) { + StringBuilder errors = new StringBuilder(); + for (ConstraintViolation contraintes : constraintViolations) { + errors.append(String.format("%s.%s %s\n", + contraintes.getRootBeanClass().getSimpleName(), + contraintes.getPropertyPath(), + contraintes.getMessage())); + } + throw new RuntimeException("Bean validation : " + errors); + } + } + public static List parametersToList(String collectionFormat, String[] values){ List params = new ArrayList<>(); diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/conf/application.conf b/samples/server/petstore/java-play-framework-no-swagger-ui/conf/application.conf index a361b74d38e..46ce4312dd3 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/conf/application.conf +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/conf/application.conf @@ -17,6 +17,15 @@ play.filters.headers.contentSecurityPolicy=null +# When using bean validation with the swagger api, the validator will check that every constraint is respected +# This is very useful when testing but could add a lot of overhead if you return a lot of data. Benchmark have +# shown that the time it takes to validate is exponential. +# If this is a concern in your application, or if you don't want to validate the output coming from your API for +# respecting its contract, set the "output" property below to "false". Since there is not a lot of data as input for +# an endpoint, I highly suggest you let the "input" property set to true. +useInputBeanValidation=true +useOutputBeanValidation=true + play.http.errorHandler="swagger.ErrorHandler" ## Akka diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Category.java index fb9207f4b5d..9f0206575f5 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Category.java @@ -92,21 +92,5 @@ public class Category { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/ModelApiResponse.java index 05911012313..07493e84825 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/ModelApiResponse.java @@ -114,21 +114,5 @@ public class ModelApiResponse { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Order.java index 987ef07d460..cdc21f722c9 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Order.java @@ -215,21 +215,5 @@ public class Order { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Pet.java index 430bbe805ce..5e5ff376294 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Pet.java @@ -234,21 +234,5 @@ public class Pet { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Tag.java index 709fef2cf11..15a8774252a 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Tag.java @@ -92,21 +92,5 @@ public class Tag { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/User.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/User.java index ba41fb76f80..689de768893 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/User.java @@ -224,21 +224,5 @@ public class User { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiController.java index 7b393595452..ef0030703c6 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiController.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiController.java @@ -18,6 +18,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; @@ -25,11 +26,13 @@ public class PetApiController extends Controller { private final PetApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private PetApiController(PetApiControllerImpInterface imp) { + private PetApiController(Configuration configuration, PetApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -39,7 +42,9 @@ public class PetApiController extends Controller { Pet body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Pet.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -73,8 +78,10 @@ public class PetApiController extends Controller { status.add(curParam); } List obj = imp.findPetsByStatus(status); - for (Pet curItem : obj) { - curItem.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + for (Pet curItem : obj) { + SwaggerUtils.validate(curItem); + } } JsonNode result = mapper.valueToTree(obj); return ok(result); @@ -93,8 +100,10 @@ public class PetApiController extends Controller { tags.add(curParam); } List obj = imp.findPetsByTags(tags); - for (Pet curItem : obj) { - curItem.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + for (Pet curItem : obj) { + SwaggerUtils.validate(curItem); + } } JsonNode result = mapper.valueToTree(obj); return ok(result); @@ -103,7 +112,9 @@ public class PetApiController extends Controller { public Result getPetById(Long petId) throws Exception { Pet obj = imp.getPetById(petId); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -114,7 +125,9 @@ public class PetApiController extends Controller { Pet body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Pet.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -153,7 +166,9 @@ public class PetApiController extends Controller { } Http.MultipartFormData.FilePart file = request().body().asMultipartFormData().getFile("file"); ModelApiResponse obj = imp.uploadFile(petId, additionalMetadata, file); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiControllerImp.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiControllerImp.java index c5ef552623e..c025993f7c1 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiControllerImp.java @@ -15,13 +15,11 @@ public class PetApiControllerImp implements PetApiControllerImpInterface { @Override public void addPet(Pet body) throws Exception { //Do your magic!!! - } @Override public void deletePet(Long petId, String apiKey) throws Exception { //Do your magic!!! - } @Override @@ -45,13 +43,11 @@ public class PetApiControllerImp implements PetApiControllerImpInterface { @Override public void updatePet(Pet body) throws Exception { //Do your magic!!! - } @Override public void updatePetWithForm(Long petId, String name, String status) throws Exception { //Do your magic!!! - } @Override diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiController.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiController.java index 964e48e91a0..16a3e3c8efa 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiController.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiController.java @@ -17,6 +17,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; @@ -24,11 +25,13 @@ public class StoreApiController extends Controller { private final StoreApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private StoreApiController(StoreApiControllerImpInterface imp) { + private StoreApiController(Configuration configuration, StoreApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -48,7 +51,9 @@ public class StoreApiController extends Controller { public Result getOrderById( @Min(1) @Max(5)Long orderId) throws Exception { Order obj = imp.getOrderById(orderId); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -59,12 +64,16 @@ public class StoreApiController extends Controller { Order body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Order.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } Order obj = imp.placeOrder(body); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiControllerImp.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiControllerImp.java index 88fce8c14ed..7c57d3d096c 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiControllerImp.java @@ -14,7 +14,6 @@ public class StoreApiControllerImp implements StoreApiControllerImpInterface { @Override public void deleteOrder(String orderId) throws Exception { //Do your magic!!! - } @Override diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiController.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiController.java index 06b4ef13b65..596ce528fff 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiController.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiController.java @@ -17,6 +17,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; @@ -24,11 +25,13 @@ public class UserApiController extends Controller { private final UserApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private UserApiController(UserApiControllerImpInterface imp) { + private UserApiController(Configuration configuration, UserApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -38,7 +41,9 @@ public class UserApiController extends Controller { User body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), User.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -52,8 +57,10 @@ public class UserApiController extends Controller { List body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); - for (User curItem : body) { - curItem.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + for (User curItem : body) { + SwaggerUtils.validate(curItem); + } } } else { throw new IllegalArgumentException("'body' parameter is required"); @@ -68,8 +75,10 @@ public class UserApiController extends Controller { List body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); - for (User curItem : body) { - curItem.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + for (User curItem : body) { + SwaggerUtils.validate(curItem); + } } } else { throw new IllegalArgumentException("'body' parameter is required"); @@ -87,7 +96,9 @@ public class UserApiController extends Controller { public Result getUserByName(String username) throws Exception { User obj = imp.getUserByName(username); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -125,7 +136,9 @@ public class UserApiController extends Controller { User body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), User.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiControllerImp.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiControllerImp.java index 82b9003b0fc..0ea7a808b9a 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiControllerImp.java @@ -14,25 +14,21 @@ public class UserApiControllerImp implements UserApiControllerImpInterface { @Override public void createUser(User body) throws Exception { //Do your magic!!! - } @Override public void createUsersWithArrayInput(List body) throws Exception { //Do your magic!!! - } @Override public void createUsersWithListInput(List body) throws Exception { //Do your magic!!! - } @Override public void deleteUser(String username) throws Exception { //Do your magic!!! - } @Override @@ -50,13 +46,11 @@ public class UserApiControllerImp implements UserApiControllerImpInterface { @Override public void logoutUser() throws Exception { //Do your magic!!! - } @Override public void updateUser(String username, User body) throws Exception { //Do your magic!!! - } } diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/swagger/SwaggerUtils.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/swagger/SwaggerUtils.java index b00dd30e7e5..4c5ee51c67f 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/swagger/SwaggerUtils.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/swagger/SwaggerUtils.java @@ -9,9 +9,30 @@ import java.lang.annotation.Target; import java.text.SimpleDateFormat; import java.util.*; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + public class SwaggerUtils { + public static void validate(T obj) { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + Set> constraintViolations = validator.validate(obj); + if (constraintViolations.size() > 0) { + StringBuilder errors = new StringBuilder(); + for (ConstraintViolation contraintes : constraintViolations) { + errors.append(String.format("%s.%s %s\n", + contraintes.getRootBeanClass().getSimpleName(), + contraintes.getPropertyPath(), + contraintes.getMessage())); + } + throw new RuntimeException("Bean validation : " + errors); + } + } + public static List parametersToList(String collectionFormat, String[] values){ List params = new ArrayList<>(); diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/conf/application.conf b/samples/server/petstore/java-play-framework-no-wrap-calls/conf/application.conf index a361b74d38e..46ce4312dd3 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/conf/application.conf +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/conf/application.conf @@ -17,6 +17,15 @@ play.filters.headers.contentSecurityPolicy=null +# When using bean validation with the swagger api, the validator will check that every constraint is respected +# This is very useful when testing but could add a lot of overhead if you return a lot of data. Benchmark have +# shown that the time it takes to validate is exponential. +# If this is a concern in your application, or if you don't want to validate the output coming from your API for +# respecting its contract, set the "output" property below to "false". Since there is not a lot of data as input for +# an endpoint, I highly suggest you let the "input" property set to true. +useInputBeanValidation=true +useOutputBeanValidation=true + play.http.errorHandler="swagger.ErrorHandler" ## Akka diff --git a/samples/server/petstore/java-play-framework/app/apimodels/Category.java b/samples/server/petstore/java-play-framework/app/apimodels/Category.java index fb9207f4b5d..9f0206575f5 100644 --- a/samples/server/petstore/java-play-framework/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework/app/apimodels/Category.java @@ -92,21 +92,5 @@ public class Category { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework/app/apimodels/ModelApiResponse.java index 05911012313..07493e84825 100644 --- a/samples/server/petstore/java-play-framework/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework/app/apimodels/ModelApiResponse.java @@ -114,21 +114,5 @@ public class ModelApiResponse { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework/app/apimodels/Order.java b/samples/server/petstore/java-play-framework/app/apimodels/Order.java index 987ef07d460..cdc21f722c9 100644 --- a/samples/server/petstore/java-play-framework/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework/app/apimodels/Order.java @@ -215,21 +215,5 @@ public class Order { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework/app/apimodels/Pet.java index 430bbe805ce..5e5ff376294 100644 --- a/samples/server/petstore/java-play-framework/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework/app/apimodels/Pet.java @@ -234,21 +234,5 @@ public class Pet { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework/app/apimodels/Tag.java index 709fef2cf11..15a8774252a 100644 --- a/samples/server/petstore/java-play-framework/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework/app/apimodels/Tag.java @@ -92,21 +92,5 @@ public class Tag { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework/app/apimodels/User.java b/samples/server/petstore/java-play-framework/app/apimodels/User.java index ba41fb76f80..689de768893 100644 --- a/samples/server/petstore/java-play-framework/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework/app/apimodels/User.java @@ -224,21 +224,5 @@ public class User { } return o.toString().replace("\n", "\n "); } - - public void validate() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(this); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } } diff --git a/samples/server/petstore/java-play-framework/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework/app/controllers/PetApiController.java index 2ecdbcbdc0b..cab362abda5 100644 --- a/samples/server/petstore/java-play-framework/app/controllers/PetApiController.java +++ b/samples/server/petstore/java-play-framework/app/controllers/PetApiController.java @@ -18,6 +18,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -26,11 +27,13 @@ public class PetApiController extends Controller { private final PetApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private PetApiController(PetApiControllerImpInterface imp) { + private PetApiController(Configuration configuration, PetApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -40,7 +43,9 @@ public class PetApiController extends Controller { Pet body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Pet.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -74,8 +79,10 @@ public class PetApiController extends Controller { status.add(curParam); } List obj = imp.findPetsByStatus(status); - for (Pet curItem : obj) { - curItem.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + for (Pet curItem : obj) { + SwaggerUtils.validate(curItem); + } } JsonNode result = mapper.valueToTree(obj); return ok(result); @@ -94,8 +101,10 @@ public class PetApiController extends Controller { tags.add(curParam); } List obj = imp.findPetsByTags(tags); - for (Pet curItem : obj) { - curItem.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + for (Pet curItem : obj) { + SwaggerUtils.validate(curItem); + } } JsonNode result = mapper.valueToTree(obj); return ok(result); @@ -104,7 +113,9 @@ public class PetApiController extends Controller { @ApiAction public Result getPetById(Long petId) throws Exception { Pet obj = imp.getPetById(petId); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -115,7 +126,9 @@ public class PetApiController extends Controller { Pet body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Pet.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -154,7 +167,9 @@ public class PetApiController extends Controller { } Http.MultipartFormData.FilePart file = request().body().asMultipartFormData().getFile("file"); ModelApiResponse obj = imp.uploadFile(petId, additionalMetadata, file); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } diff --git a/samples/server/petstore/java-play-framework/app/controllers/PetApiControllerImp.java b/samples/server/petstore/java-play-framework/app/controllers/PetApiControllerImp.java index c5ef552623e..c025993f7c1 100644 --- a/samples/server/petstore/java-play-framework/app/controllers/PetApiControllerImp.java +++ b/samples/server/petstore/java-play-framework/app/controllers/PetApiControllerImp.java @@ -15,13 +15,11 @@ public class PetApiControllerImp implements PetApiControllerImpInterface { @Override public void addPet(Pet body) throws Exception { //Do your magic!!! - } @Override public void deletePet(Long petId, String apiKey) throws Exception { //Do your magic!!! - } @Override @@ -45,13 +43,11 @@ public class PetApiControllerImp implements PetApiControllerImpInterface { @Override public void updatePet(Pet body) throws Exception { //Do your magic!!! - } @Override public void updatePetWithForm(Long petId, String name, String status) throws Exception { //Do your magic!!! - } @Override diff --git a/samples/server/petstore/java-play-framework/app/controllers/StoreApiController.java b/samples/server/petstore/java-play-framework/app/controllers/StoreApiController.java index 8254d1f992e..c94c5aa111a 100644 --- a/samples/server/petstore/java-play-framework/app/controllers/StoreApiController.java +++ b/samples/server/petstore/java-play-framework/app/controllers/StoreApiController.java @@ -17,6 +17,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -25,11 +26,13 @@ public class StoreApiController extends Controller { private final StoreApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private StoreApiController(StoreApiControllerImpInterface imp) { + private StoreApiController(Configuration configuration, StoreApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -49,7 +52,9 @@ public class StoreApiController extends Controller { @ApiAction public Result getOrderById( @Min(1) @Max(5)Long orderId) throws Exception { Order obj = imp.getOrderById(orderId); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -60,12 +65,16 @@ public class StoreApiController extends Controller { Order body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Order.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } Order obj = imp.placeOrder(body); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } diff --git a/samples/server/petstore/java-play-framework/app/controllers/StoreApiControllerImp.java b/samples/server/petstore/java-play-framework/app/controllers/StoreApiControllerImp.java index 88fce8c14ed..7c57d3d096c 100644 --- a/samples/server/petstore/java-play-framework/app/controllers/StoreApiControllerImp.java +++ b/samples/server/petstore/java-play-framework/app/controllers/StoreApiControllerImp.java @@ -14,7 +14,6 @@ public class StoreApiControllerImp implements StoreApiControllerImpInterface { @Override public void deleteOrder(String orderId) throws Exception { //Do your magic!!! - } @Override diff --git a/samples/server/petstore/java-play-framework/app/controllers/UserApiController.java b/samples/server/petstore/java-play-framework/app/controllers/UserApiController.java index b0676d8e3d5..245d076858a 100644 --- a/samples/server/petstore/java-play-framework/app/controllers/UserApiController.java +++ b/samples/server/petstore/java-play-framework/app/controllers/UserApiController.java @@ -17,6 +17,7 @@ import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import play.Configuration; import swagger.SwaggerUtils.ApiAction; @@ -25,11 +26,13 @@ public class UserApiController extends Controller { private final UserApiControllerImpInterface imp; private final ObjectMapper mapper; + private final Configuration configuration; @Inject - private UserApiController(UserApiControllerImpInterface imp) { + private UserApiController(Configuration configuration, UserApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); + this.configuration = configuration; } @@ -39,7 +42,9 @@ public class UserApiController extends Controller { User body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), User.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } @@ -53,8 +58,10 @@ public class UserApiController extends Controller { List body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); - for (User curItem : body) { - curItem.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + for (User curItem : body) { + SwaggerUtils.validate(curItem); + } } } else { throw new IllegalArgumentException("'body' parameter is required"); @@ -69,8 +76,10 @@ public class UserApiController extends Controller { List body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); - for (User curItem : body) { - curItem.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + for (User curItem : body) { + SwaggerUtils.validate(curItem); + } } } else { throw new IllegalArgumentException("'body' parameter is required"); @@ -88,7 +97,9 @@ public class UserApiController extends Controller { @ApiAction public Result getUserByName(String username) throws Exception { User obj = imp.getUserByName(username); - obj.validate(); + if (configuration.getBoolean("useOutputBeanValidation")) { + SwaggerUtils.validate(obj); + } JsonNode result = mapper.valueToTree(obj); return ok(result); } @@ -126,7 +137,9 @@ public class UserApiController extends Controller { User body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), User.class); - body.validate(); + if (configuration.getBoolean("useInputBeanValidation")) { + SwaggerUtils.validate(body); + } } else { throw new IllegalArgumentException("'body' parameter is required"); } diff --git a/samples/server/petstore/java-play-framework/app/controllers/UserApiControllerImp.java b/samples/server/petstore/java-play-framework/app/controllers/UserApiControllerImp.java index 82b9003b0fc..0ea7a808b9a 100644 --- a/samples/server/petstore/java-play-framework/app/controllers/UserApiControllerImp.java +++ b/samples/server/petstore/java-play-framework/app/controllers/UserApiControllerImp.java @@ -14,25 +14,21 @@ public class UserApiControllerImp implements UserApiControllerImpInterface { @Override public void createUser(User body) throws Exception { //Do your magic!!! - } @Override public void createUsersWithArrayInput(List body) throws Exception { //Do your magic!!! - } @Override public void createUsersWithListInput(List body) throws Exception { //Do your magic!!! - } @Override public void deleteUser(String username) throws Exception { //Do your magic!!! - } @Override @@ -50,13 +46,11 @@ public class UserApiControllerImp implements UserApiControllerImpInterface { @Override public void logoutUser() throws Exception { //Do your magic!!! - } @Override public void updateUser(String username, User body) throws Exception { //Do your magic!!! - } } diff --git a/samples/server/petstore/java-play-framework/app/swagger/SwaggerUtils.java b/samples/server/petstore/java-play-framework/app/swagger/SwaggerUtils.java index c7d8bd3de9e..d4900e02167 100644 --- a/samples/server/petstore/java-play-framework/app/swagger/SwaggerUtils.java +++ b/samples/server/petstore/java-play-framework/app/swagger/SwaggerUtils.java @@ -9,6 +9,11 @@ import java.lang.annotation.Target; import java.text.SimpleDateFormat; import java.util.*; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + public class SwaggerUtils { @With(ApiCall.class) @@ -17,6 +22,22 @@ public class SwaggerUtils { public @interface ApiAction { } + public static void validate(T obj) { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + Set> constraintViolations = validator.validate(obj); + if (constraintViolations.size() > 0) { + StringBuilder errors = new StringBuilder(); + for (ConstraintViolation contraintes : constraintViolations) { + errors.append(String.format("%s.%s %s\n", + contraintes.getRootBeanClass().getSimpleName(), + contraintes.getPropertyPath(), + contraintes.getMessage())); + } + throw new RuntimeException("Bean validation : " + errors); + } + } + public static List parametersToList(String collectionFormat, String[] values){ List params = new ArrayList<>(); diff --git a/samples/server/petstore/java-play-framework/conf/application.conf b/samples/server/petstore/java-play-framework/conf/application.conf index a361b74d38e..46ce4312dd3 100644 --- a/samples/server/petstore/java-play-framework/conf/application.conf +++ b/samples/server/petstore/java-play-framework/conf/application.conf @@ -17,6 +17,15 @@ play.filters.headers.contentSecurityPolicy=null +# When using bean validation with the swagger api, the validator will check that every constraint is respected +# This is very useful when testing but could add a lot of overhead if you return a lot of data. Benchmark have +# shown that the time it takes to validate is exponential. +# If this is a concern in your application, or if you don't want to validate the output coming from your API for +# respecting its contract, set the "output" property below to "false". Since there is not a lot of data as input for +# an endpoint, I highly suggest you let the "input" property set to true. +useInputBeanValidation=true +useOutputBeanValidation=true + play.http.errorHandler="swagger.ErrorHandler" ## Akka diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/pom.xml b/samples/server/petstore/jaxrs-cxf-annotated-base-path/pom.xml index edaf8d0eeb7..0136d8f0a76 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/pom.xml +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/pom.xml @@ -4,6 +4,7 @@ swagger-cxf-annotated-basepath war swagger-cxf-annotated-basepath + This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. 1.0.0 src/main/java diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/PetApi.java index f6551d8cc37..c576178bcc0 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/PetApi.java @@ -21,10 +21,22 @@ import io.swagger.jaxrs.PATCH; import javax.validation.constraints.*; import javax.validation.Valid; +/** + * 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. + * + */ @Path("/v2") @Api(value = "/", description = "") public interface PetApi { + /** + * Add a new pet to the store + * + * + * + */ @POST @Path("/pet") @Consumes({ "application/json", "application/xml" }) @@ -34,6 +46,12 @@ public interface PetApi { @ApiResponse(code = 405, message = "Invalid input") }) public void addPet(@Valid Pet body); + /** + * Deletes a pet + * + * + * + */ @DELETE @Path("/pet/{petId}") @Produces({ "application/xml", "application/json" }) @@ -42,6 +60,12 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid pet value") }) public void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey); + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + */ @GET @Path("/pet/findByStatus") @Produces({ "application/xml", "application/json" }) @@ -51,6 +75,12 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid status value") }) public List findPetsByStatus(@QueryParam("status") @NotNull List status); + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + */ @GET @Path("/pet/findByTags") @Produces({ "application/xml", "application/json" }) @@ -60,6 +90,12 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid tag value") }) public List findPetsByTags(@QueryParam("tags") @NotNull List tags); + /** + * Find pet by ID + * + * Returns a single pet + * + */ @GET @Path("/pet/{petId}") @Produces({ "application/xml", "application/json" }) @@ -70,6 +106,12 @@ public interface PetApi { @ApiResponse(code = 404, message = "Pet not found") }) public Pet getPetById(@PathParam("petId") Long petId); + /** + * Update an existing pet + * + * + * + */ @PUT @Path("/pet") @Consumes({ "application/json", "application/xml" }) @@ -81,6 +123,12 @@ public interface PetApi { @ApiResponse(code = 405, message = "Validation exception") }) public void updatePet(@Valid Pet body); + /** + * Updates a pet in the store with form data + * + * + * + */ @POST @Path("/pet/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) @@ -90,6 +138,12 @@ public interface PetApi { @ApiResponse(code = 405, message = "Invalid input") }) public void updatePetWithForm(@PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status); + /** + * uploads an image + * + * + * + */ @POST @Path("/pet/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/StoreApi.java index 0b00a353bc1..5e18529e1b5 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/StoreApi.java @@ -20,10 +20,22 @@ import io.swagger.jaxrs.PATCH; import javax.validation.constraints.*; import javax.validation.Valid; +/** + * 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. + * + */ @Path("/v2") @Api(value = "/", description = "") public interface StoreApi { + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + */ @DELETE @Path("/store/order/{orderId}") @Produces({ "application/xml", "application/json" }) @@ -33,6 +45,12 @@ public interface StoreApi { @ApiResponse(code = 404, message = "Order not found") }) public void deleteOrder(@PathParam("orderId") String orderId); + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + */ @GET @Path("/store/inventory") @Produces({ "application/json" }) @@ -41,6 +59,12 @@ public interface StoreApi { @ApiResponse(code = 200, message = "successful operation", response = Map.class, responseContainer = "Map") }) public Map getInventory(); + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + */ @GET @Path("/store/order/{orderId}") @Produces({ "application/xml", "application/json" }) @@ -51,6 +75,12 @@ public interface StoreApi { @ApiResponse(code = 404, message = "Order not found") }) public Order getOrderById(@PathParam("orderId") @Min(1) @Max(5) Long orderId); + /** + * Place an order for a pet + * + * + * + */ @POST @Path("/store/order") @Produces({ "application/xml", "application/json" }) diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/UserApi.java index 36a62cf2a0a..a5fd5adf01c 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/UserApi.java @@ -20,10 +20,22 @@ import io.swagger.jaxrs.PATCH; import javax.validation.constraints.*; import javax.validation.Valid; +/** + * 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. + * + */ @Path("/v2") @Api(value = "/", description = "") public interface UserApi { + /** + * Create user + * + * This can only be done by the logged in user. + * + */ @POST @Path("/user") @Produces({ "application/xml", "application/json" }) @@ -32,6 +44,12 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation") }) public void createUser(@Valid User body); + /** + * Creates list of users with given input array + * + * + * + */ @POST @Path("/user/createWithArray") @Produces({ "application/xml", "application/json" }) @@ -40,6 +58,12 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation") }) public void createUsersWithArrayInput(@Valid List body); + /** + * Creates list of users with given input array + * + * + * + */ @POST @Path("/user/createWithList") @Produces({ "application/xml", "application/json" }) @@ -48,6 +72,12 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation") }) public void createUsersWithListInput(@Valid List body); + /** + * Delete user + * + * This can only be done by the logged in user. + * + */ @DELETE @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) @@ -57,6 +87,12 @@ public interface UserApi { @ApiResponse(code = 404, message = "User not found") }) public void deleteUser(@PathParam("username") String username); + /** + * Get user by user name + * + * + * + */ @GET @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) @@ -67,6 +103,12 @@ public interface UserApi { @ApiResponse(code = 404, message = "User not found") }) public User getUserByName(@PathParam("username") String username); + /** + * Logs user into the system + * + * + * + */ @GET @Path("/user/login") @Produces({ "application/xml", "application/json" }) @@ -76,6 +118,12 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid username/password supplied") }) public String loginUser(@QueryParam("username") @NotNull String username, @QueryParam("password") @NotNull String password); + /** + * Logs out current logged in user session + * + * + * + */ @GET @Path("/user/logout") @Produces({ "application/xml", "application/json" }) @@ -84,6 +132,12 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation") }) public void logoutUser(); + /** + * Updated user + * + * This can only be done by the logged in user. + * + */ @PUT @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Category.java index c6076fb8df8..9a1956aae8c 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Category.java @@ -11,7 +11,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * A category for a pet + **/ @ApiModel(description="A category for a pet") public class Category { @@ -24,6 +28,7 @@ public class Category { * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -41,6 +46,7 @@ public class Category { * Get name * @return name **/ + @JsonProperty("name") public String getName() { return name; } diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/ModelApiResponse.java index 4877f3ace31..51ffbeff6da 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -11,7 +11,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * Describes the result of uploading an image resource + **/ @ApiModel(description="Describes the result of uploading an image resource") public class ModelApiResponse { @@ -26,6 +30,7 @@ public class ModelApiResponse { * Get code * @return code **/ + @JsonProperty("code") public Integer getCode() { return code; } @@ -43,6 +48,7 @@ public class ModelApiResponse { * Get type * @return type **/ + @JsonProperty("type") public String getType() { return type; } @@ -60,6 +66,7 @@ public class ModelApiResponse { * Get message * @return message **/ + @JsonProperty("message") public String getMessage() { return message; } diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Order.java index 5b4a67f50c1..dac33686761 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Order.java @@ -12,7 +12,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * An order for a pets from the pet store + **/ @ApiModel(description="An order for a pets from the pet store") public class Order { @@ -58,6 +62,9 @@ public enum StatusEnum { } @ApiModelProperty(value = "Order Status") + /** + * Order Status + **/ private StatusEnum status = null; @ApiModelProperty(value = "") private Boolean complete = false; @@ -66,6 +73,7 @@ public enum StatusEnum { * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -83,6 +91,7 @@ public enum StatusEnum { * Get petId * @return petId **/ + @JsonProperty("petId") public Long getPetId() { return petId; } @@ -100,6 +109,7 @@ public enum StatusEnum { * Get quantity * @return quantity **/ + @JsonProperty("quantity") public Integer getQuantity() { return quantity; } @@ -117,6 +127,7 @@ public enum StatusEnum { * Get shipDate * @return shipDate **/ + @JsonProperty("shipDate") public Date getShipDate() { return shipDate; } @@ -134,8 +145,12 @@ public enum StatusEnum { * Order Status * @return status **/ - public StatusEnum getStatus() { - return status; + @JsonProperty("status") + public String getStatus() { + if (status == null) { + return null; + } + return status.value(); } public void setStatus(StatusEnum status) { @@ -151,6 +166,7 @@ public enum StatusEnum { * Get complete * @return complete **/ + @JsonProperty("complete") public Boolean isComplete() { return complete; } diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Pet.java index 15f9322a95a..3c8ab5da478 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Pet.java @@ -15,7 +15,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * A pet for sale in the pet store + **/ @ApiModel(description="A pet for sale in the pet store") public class Pet { @@ -63,12 +67,16 @@ public enum StatusEnum { } @ApiModelProperty(value = "pet status in the store") + /** + * pet status in the store + **/ private StatusEnum status = null; /** * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -86,6 +94,7 @@ public enum StatusEnum { * Get category * @return category **/ + @JsonProperty("category") public Category getCategory() { return category; } @@ -103,6 +112,7 @@ public enum StatusEnum { * Get name * @return name **/ + @JsonProperty("name") @NotNull public String getName() { return name; @@ -121,6 +131,7 @@ public enum StatusEnum { * Get photoUrls * @return photoUrls **/ + @JsonProperty("photoUrls") @NotNull public List getPhotoUrls() { return photoUrls; @@ -144,6 +155,7 @@ public enum StatusEnum { * Get tags * @return tags **/ + @JsonProperty("tags") public List getTags() { return tags; } @@ -166,8 +178,12 @@ public enum StatusEnum { * pet status in the store * @return status **/ - public StatusEnum getStatus() { - return status; + @JsonProperty("status") + public String getStatus() { + if (status == null) { + return null; + } + return status.value(); } public void setStatus(StatusEnum status) { diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Tag.java index a0bfd24470f..24fd1d55d2a 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Tag.java @@ -11,7 +11,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * A tag for a pet + **/ @ApiModel(description="A tag for a pet") public class Tag { @@ -24,6 +28,7 @@ public class Tag { * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -41,6 +46,7 @@ public class Tag { * Get name * @return name **/ + @JsonProperty("name") public String getName() { return name; } diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/User.java index 74b908a3aa3..858e8e14268 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/User.java @@ -11,7 +11,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * A User who is purchasing from the pet store + **/ @ApiModel(description="A User who is purchasing from the pet store") public class User { @@ -30,12 +34,16 @@ public class User { @ApiModelProperty(value = "") private String phone = null; @ApiModelProperty(value = "User Status") + /** + * User Status + **/ private Integer userStatus = null; /** * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -53,6 +61,7 @@ public class User { * Get username * @return username **/ + @JsonProperty("username") public String getUsername() { return username; } @@ -70,6 +79,7 @@ public class User { * Get firstName * @return firstName **/ + @JsonProperty("firstName") public String getFirstName() { return firstName; } @@ -87,6 +97,7 @@ public class User { * Get lastName * @return lastName **/ + @JsonProperty("lastName") public String getLastName() { return lastName; } @@ -104,6 +115,7 @@ public class User { * Get email * @return email **/ + @JsonProperty("email") public String getEmail() { return email; } @@ -121,6 +133,7 @@ public class User { * Get password * @return password **/ + @JsonProperty("password") public String getPassword() { return password; } @@ -138,6 +151,7 @@ public class User { * Get phone * @return phone **/ + @JsonProperty("phone") public String getPhone() { return phone; } @@ -155,6 +169,7 @@ public class User { * User Status * @return userStatus **/ + @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index d9b9345d339..0f19eb3098d 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -18,49 +18,103 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; +/** + * 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. + * + */ public class PetApiServiceImpl implements PetApi { + /** + * Add a new pet to the store + * + * + * + */ public void addPet(Pet body) { // TODO: Implement... } + /** + * Deletes a pet + * + * + * + */ public void deletePet(Long petId, String apiKey) { // TODO: Implement... } + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + */ public List findPetsByStatus(List status) { // TODO: Implement... return null; } + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + */ public List findPetsByTags(List tags) { // TODO: Implement... return null; } + /** + * Find pet by ID + * + * Returns a single pet + * + */ public Pet getPetById(Long petId) { // TODO: Implement... return null; } + /** + * Update an existing pet + * + * + * + */ public void updatePet(Pet body) { // TODO: Implement... } + /** + * Updates a pet in the store with form data + * + * + * + */ public void updatePetWithForm(Long petId, String name, String status) { // TODO: Implement... } + /** + * uploads an image + * + * + * + */ public ModelApiResponse uploadFile(Long petId, String additionalMetadata, Attachment fileDetail) { // TODO: Implement... diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index 3f791097b6b..9d3f93f8c3d 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -17,25 +17,55 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; +/** + * 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. + * + */ public class StoreApiServiceImpl implements StoreApi { + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + */ public void deleteOrder(String orderId) { // TODO: Implement... } + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + */ public Map getInventory() { // TODO: Implement... return null; } + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + */ public Order getOrderById(Long orderId) { // TODO: Implement... return null; } + /** + * Place an order for a pet + * + * + * + */ public Order placeOrder(Order body) { // TODO: Implement... diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index 861273cfb7b..c569dbf5c15 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -17,49 +17,103 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; +/** + * 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. + * + */ public class UserApiServiceImpl implements UserApi { + /** + * Create user + * + * This can only be done by the logged in user. + * + */ public void createUser(User body) { // TODO: Implement... } + /** + * Creates list of users with given input array + * + * + * + */ public void createUsersWithArrayInput(List body) { // TODO: Implement... } + /** + * Creates list of users with given input array + * + * + * + */ public void createUsersWithListInput(List body) { // TODO: Implement... } + /** + * Delete user + * + * This can only be done by the logged in user. + * + */ public void deleteUser(String username) { // TODO: Implement... } + /** + * Get user by user name + * + * + * + */ public User getUserByName(String username) { // TODO: Implement... return null; } + /** + * Logs user into the system + * + * + * + */ public String loginUser(String username, String password) { // TODO: Implement... return null; } + /** + * Logs out current logged in user session + * + * + * + */ public void logoutUser() { // TODO: Implement... } + /** + * Updated user + * + * This can only be done by the logged in user. + * + */ public void updateUser(String username, User body) { // TODO: Implement... diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/pom.xml b/samples/server/petstore/jaxrs-cxf-non-spring-app/pom.xml index df55fcf5667..1c116b94ad1 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/pom.xml +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/pom.xml @@ -4,6 +4,7 @@ swagger-cxf-server-non-spring war swagger-cxf-server-non-spring + This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. 1.0.0 src/main/java diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/PetApi.java index 93a82ed4f6c..f8b8a10d288 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/PetApi.java @@ -21,10 +21,22 @@ import io.swagger.jaxrs.PATCH; import javax.validation.constraints.*; import javax.validation.Valid; +/** + * 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. + * + */ @Path("/") @Api(value = "/", description = "") public interface PetApi { + /** + * Add a new pet to the store + * + * + * + */ @POST @Path("/pet") @Consumes({ "application/json", "application/xml" }) @@ -34,6 +46,12 @@ public interface PetApi { @ApiResponse(code = 405, message = "Invalid input") }) public void addPet(@Valid Pet body); + /** + * Deletes a pet + * + * + * + */ @DELETE @Path("/pet/{petId}") @Produces({ "application/xml", "application/json" }) @@ -42,6 +60,12 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid pet value") }) public void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey); + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + */ @GET @Path("/pet/findByStatus") @Produces({ "application/xml", "application/json" }) @@ -51,6 +75,12 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid status value") }) public List findPetsByStatus(@QueryParam("status") @NotNull List status); + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + */ @GET @Path("/pet/findByTags") @Produces({ "application/xml", "application/json" }) @@ -60,6 +90,12 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid tag value") }) public List findPetsByTags(@QueryParam("tags") @NotNull List tags); + /** + * Find pet by ID + * + * Returns a single pet + * + */ @GET @Path("/pet/{petId}") @Produces({ "application/xml", "application/json" }) @@ -70,6 +106,12 @@ public interface PetApi { @ApiResponse(code = 404, message = "Pet not found") }) public Pet getPetById(@PathParam("petId") Long petId); + /** + * Update an existing pet + * + * + * + */ @PUT @Path("/pet") @Consumes({ "application/json", "application/xml" }) @@ -81,6 +123,12 @@ public interface PetApi { @ApiResponse(code = 405, message = "Validation exception") }) public void updatePet(@Valid Pet body); + /** + * Updates a pet in the store with form data + * + * + * + */ @POST @Path("/pet/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) @@ -90,6 +138,12 @@ public interface PetApi { @ApiResponse(code = 405, message = "Invalid input") }) public void updatePetWithForm(@PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status); + /** + * uploads an image + * + * + * + */ @POST @Path("/pet/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/StoreApi.java index 8ddeb8f3dea..72508ea286a 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/StoreApi.java @@ -20,10 +20,22 @@ import io.swagger.jaxrs.PATCH; import javax.validation.constraints.*; import javax.validation.Valid; +/** + * 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. + * + */ @Path("/") @Api(value = "/", description = "") public interface StoreApi { + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + */ @DELETE @Path("/store/order/{orderId}") @Produces({ "application/xml", "application/json" }) @@ -33,6 +45,12 @@ public interface StoreApi { @ApiResponse(code = 404, message = "Order not found") }) public void deleteOrder(@PathParam("orderId") String orderId); + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + */ @GET @Path("/store/inventory") @Produces({ "application/json" }) @@ -41,6 +59,12 @@ public interface StoreApi { @ApiResponse(code = 200, message = "successful operation", response = Map.class, responseContainer = "Map") }) public Map getInventory(); + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + */ @GET @Path("/store/order/{orderId}") @Produces({ "application/xml", "application/json" }) @@ -51,6 +75,12 @@ public interface StoreApi { @ApiResponse(code = 404, message = "Order not found") }) public Order getOrderById(@PathParam("orderId") @Min(1) @Max(5) Long orderId); + /** + * Place an order for a pet + * + * + * + */ @POST @Path("/store/order") @Produces({ "application/xml", "application/json" }) diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/UserApi.java index 5588dddf74f..7aba6911b46 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/UserApi.java @@ -20,10 +20,22 @@ import io.swagger.jaxrs.PATCH; import javax.validation.constraints.*; import javax.validation.Valid; +/** + * 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. + * + */ @Path("/") @Api(value = "/", description = "") public interface UserApi { + /** + * Create user + * + * This can only be done by the logged in user. + * + */ @POST @Path("/user") @Produces({ "application/xml", "application/json" }) @@ -32,6 +44,12 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation") }) public void createUser(@Valid User body); + /** + * Creates list of users with given input array + * + * + * + */ @POST @Path("/user/createWithArray") @Produces({ "application/xml", "application/json" }) @@ -40,6 +58,12 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation") }) public void createUsersWithArrayInput(@Valid List body); + /** + * Creates list of users with given input array + * + * + * + */ @POST @Path("/user/createWithList") @Produces({ "application/xml", "application/json" }) @@ -48,6 +72,12 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation") }) public void createUsersWithListInput(@Valid List body); + /** + * Delete user + * + * This can only be done by the logged in user. + * + */ @DELETE @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) @@ -57,6 +87,12 @@ public interface UserApi { @ApiResponse(code = 404, message = "User not found") }) public void deleteUser(@PathParam("username") String username); + /** + * Get user by user name + * + * + * + */ @GET @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) @@ -67,6 +103,12 @@ public interface UserApi { @ApiResponse(code = 404, message = "User not found") }) public User getUserByName(@PathParam("username") String username); + /** + * Logs user into the system + * + * + * + */ @GET @Path("/user/login") @Produces({ "application/xml", "application/json" }) @@ -76,6 +118,12 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid username/password supplied") }) public String loginUser(@QueryParam("username") @NotNull String username, @QueryParam("password") @NotNull String password); + /** + * Logs out current logged in user session + * + * + * + */ @GET @Path("/user/logout") @Produces({ "application/xml", "application/json" }) @@ -84,6 +132,12 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation") }) public void logoutUser(); + /** + * Updated user + * + * This can only be done by the logged in user. + * + */ @PUT @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Category.java index c6076fb8df8..9a1956aae8c 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Category.java @@ -11,7 +11,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * A category for a pet + **/ @ApiModel(description="A category for a pet") public class Category { @@ -24,6 +28,7 @@ public class Category { * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -41,6 +46,7 @@ public class Category { * Get name * @return name **/ + @JsonProperty("name") public String getName() { return name; } diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/ModelApiResponse.java index 4877f3ace31..51ffbeff6da 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -11,7 +11,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * Describes the result of uploading an image resource + **/ @ApiModel(description="Describes the result of uploading an image resource") public class ModelApiResponse { @@ -26,6 +30,7 @@ public class ModelApiResponse { * Get code * @return code **/ + @JsonProperty("code") public Integer getCode() { return code; } @@ -43,6 +48,7 @@ public class ModelApiResponse { * Get type * @return type **/ + @JsonProperty("type") public String getType() { return type; } @@ -60,6 +66,7 @@ public class ModelApiResponse { * Get message * @return message **/ + @JsonProperty("message") public String getMessage() { return message; } diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Order.java index 5b4a67f50c1..dac33686761 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Order.java @@ -12,7 +12,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * An order for a pets from the pet store + **/ @ApiModel(description="An order for a pets from the pet store") public class Order { @@ -58,6 +62,9 @@ public enum StatusEnum { } @ApiModelProperty(value = "Order Status") + /** + * Order Status + **/ private StatusEnum status = null; @ApiModelProperty(value = "") private Boolean complete = false; @@ -66,6 +73,7 @@ public enum StatusEnum { * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -83,6 +91,7 @@ public enum StatusEnum { * Get petId * @return petId **/ + @JsonProperty("petId") public Long getPetId() { return petId; } @@ -100,6 +109,7 @@ public enum StatusEnum { * Get quantity * @return quantity **/ + @JsonProperty("quantity") public Integer getQuantity() { return quantity; } @@ -117,6 +127,7 @@ public enum StatusEnum { * Get shipDate * @return shipDate **/ + @JsonProperty("shipDate") public Date getShipDate() { return shipDate; } @@ -134,8 +145,12 @@ public enum StatusEnum { * Order Status * @return status **/ - public StatusEnum getStatus() { - return status; + @JsonProperty("status") + public String getStatus() { + if (status == null) { + return null; + } + return status.value(); } public void setStatus(StatusEnum status) { @@ -151,6 +166,7 @@ public enum StatusEnum { * Get complete * @return complete **/ + @JsonProperty("complete") public Boolean isComplete() { return complete; } diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Pet.java index 15f9322a95a..3c8ab5da478 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Pet.java @@ -15,7 +15,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * A pet for sale in the pet store + **/ @ApiModel(description="A pet for sale in the pet store") public class Pet { @@ -63,12 +67,16 @@ public enum StatusEnum { } @ApiModelProperty(value = "pet status in the store") + /** + * pet status in the store + **/ private StatusEnum status = null; /** * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -86,6 +94,7 @@ public enum StatusEnum { * Get category * @return category **/ + @JsonProperty("category") public Category getCategory() { return category; } @@ -103,6 +112,7 @@ public enum StatusEnum { * Get name * @return name **/ + @JsonProperty("name") @NotNull public String getName() { return name; @@ -121,6 +131,7 @@ public enum StatusEnum { * Get photoUrls * @return photoUrls **/ + @JsonProperty("photoUrls") @NotNull public List getPhotoUrls() { return photoUrls; @@ -144,6 +155,7 @@ public enum StatusEnum { * Get tags * @return tags **/ + @JsonProperty("tags") public List getTags() { return tags; } @@ -166,8 +178,12 @@ public enum StatusEnum { * pet status in the store * @return status **/ - public StatusEnum getStatus() { - return status; + @JsonProperty("status") + public String getStatus() { + if (status == null) { + return null; + } + return status.value(); } public void setStatus(StatusEnum status) { diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Tag.java index a0bfd24470f..24fd1d55d2a 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Tag.java @@ -11,7 +11,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * A tag for a pet + **/ @ApiModel(description="A tag for a pet") public class Tag { @@ -24,6 +28,7 @@ public class Tag { * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -41,6 +46,7 @@ public class Tag { * Get name * @return name **/ + @JsonProperty("name") public String getName() { return name; } diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/User.java index 74b908a3aa3..858e8e14268 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/User.java @@ -11,7 +11,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * A User who is purchasing from the pet store + **/ @ApiModel(description="A User who is purchasing from the pet store") public class User { @@ -30,12 +34,16 @@ public class User { @ApiModelProperty(value = "") private String phone = null; @ApiModelProperty(value = "User Status") + /** + * User Status + **/ private Integer userStatus = null; /** * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -53,6 +61,7 @@ public class User { * Get username * @return username **/ + @JsonProperty("username") public String getUsername() { return username; } @@ -70,6 +79,7 @@ public class User { * Get firstName * @return firstName **/ + @JsonProperty("firstName") public String getFirstName() { return firstName; } @@ -87,6 +97,7 @@ public class User { * Get lastName * @return lastName **/ + @JsonProperty("lastName") public String getLastName() { return lastName; } @@ -104,6 +115,7 @@ public class User { * Get email * @return email **/ + @JsonProperty("email") public String getEmail() { return email; } @@ -121,6 +133,7 @@ public class User { * Get password * @return password **/ + @JsonProperty("password") public String getPassword() { return password; } @@ -138,6 +151,7 @@ public class User { * Get phone * @return phone **/ + @JsonProperty("phone") public String getPhone() { return phone; } @@ -155,6 +169,7 @@ public class User { * User Status * @return userStatus **/ + @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index d9b9345d339..0f19eb3098d 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -18,49 +18,103 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; +/** + * 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. + * + */ public class PetApiServiceImpl implements PetApi { + /** + * Add a new pet to the store + * + * + * + */ public void addPet(Pet body) { // TODO: Implement... } + /** + * Deletes a pet + * + * + * + */ public void deletePet(Long petId, String apiKey) { // TODO: Implement... } + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + */ public List findPetsByStatus(List status) { // TODO: Implement... return null; } + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + */ public List findPetsByTags(List tags) { // TODO: Implement... return null; } + /** + * Find pet by ID + * + * Returns a single pet + * + */ public Pet getPetById(Long petId) { // TODO: Implement... return null; } + /** + * Update an existing pet + * + * + * + */ public void updatePet(Pet body) { // TODO: Implement... } + /** + * Updates a pet in the store with form data + * + * + * + */ public void updatePetWithForm(Long petId, String name, String status) { // TODO: Implement... } + /** + * uploads an image + * + * + * + */ public ModelApiResponse uploadFile(Long petId, String additionalMetadata, Attachment fileDetail) { // TODO: Implement... diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index 3f791097b6b..9d3f93f8c3d 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -17,25 +17,55 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; +/** + * 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. + * + */ public class StoreApiServiceImpl implements StoreApi { + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + */ public void deleteOrder(String orderId) { // TODO: Implement... } + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + */ public Map getInventory() { // TODO: Implement... return null; } + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + */ public Order getOrderById(Long orderId) { // TODO: Implement... return null; } + /** + * Place an order for a pet + * + * + * + */ public Order placeOrder(Order body) { // TODO: Implement... diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index 861273cfb7b..c569dbf5c15 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -17,49 +17,103 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; +/** + * 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. + * + */ public class UserApiServiceImpl implements UserApi { + /** + * Create user + * + * This can only be done by the logged in user. + * + */ public void createUser(User body) { // TODO: Implement... } + /** + * Creates list of users with given input array + * + * + * + */ public void createUsersWithArrayInput(List body) { // TODO: Implement... } + /** + * Creates list of users with given input array + * + * + * + */ public void createUsersWithListInput(List body) { // TODO: Implement... } + /** + * Delete user + * + * This can only be done by the logged in user. + * + */ public void deleteUser(String username) { // TODO: Implement... } + /** + * Get user by user name + * + * + * + */ public User getUserByName(String username) { // TODO: Implement... return null; } + /** + * Logs user into the system + * + * + * + */ public String loginUser(String username, String password) { // TODO: Implement... return null; } + /** + * Logs out current logged in user session + * + * + * + */ public void logoutUser() { // TODO: Implement... } + /** + * Updated user + * + * This can only be done by the logged in user. + * + */ public void updateUser(String username, User body) { // TODO: Implement... diff --git a/samples/server/petstore/jaxrs-cxf/pom.xml b/samples/server/petstore/jaxrs-cxf/pom.xml index 3d7d56c8519..1ab75579100 100644 --- a/samples/server/petstore/jaxrs-cxf/pom.xml +++ b/samples/server/petstore/jaxrs-cxf/pom.xml @@ -4,6 +4,7 @@ swagger-cxf-server war swagger-cxf-server + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ 1.0.0 src/main/java @@ -32,7 +33,7 @@ 8079 stopit - 8080 + 80 60000 diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/AnotherFakeApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/AnotherFakeApi.java index 3accd4f023e..c05c51bee51 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/AnotherFakeApi.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/AnotherFakeApi.java @@ -19,10 +19,22 @@ import io.swagger.jaxrs.PATCH; import javax.validation.constraints.*; import javax.validation.Valid; +/** + * 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: \" \\ + * + */ @Path("/") @Api(value = "/", description = "") public interface AnotherFakeApi { + /** + * To test special tags + * + * To test special tags + * + */ @PATCH @Path("/another-fake/dummy") @Consumes({ "application/json" }) diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/FakeApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/FakeApi.java index 1e201b5f14d..96c3a2b16e0 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/FakeApi.java @@ -23,6 +23,12 @@ import io.swagger.jaxrs.PATCH; import javax.validation.constraints.*; import javax.validation.Valid; +/** + * 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: \" \\ + * + */ @Path("/") @Api(value = "/", description = "") public interface FakeApi { @@ -55,6 +61,12 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output string", response = String.class) }) public String fakeOuterStringSerialize(@Valid String body); + /** + * To test \"client\" model + * + * To test \"client\" model + * + */ @PATCH @Path("/fake") @Consumes({ "application/json" }) @@ -64,6 +76,12 @@ public interface FakeApi { @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) public Client testClientModel(@Valid Client body); + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + */ @POST @Path("/fake") @Consumes({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) @@ -74,6 +92,12 @@ public interface FakeApi { @ApiResponse(code = 404, message = "User not found") }) public void testEndpointParameters(@Multipart(value = "number") BigDecimal number, @Multipart(value = "double") Double _double, @Multipart(value = "pattern_without_delimiter") String patternWithoutDelimiter, @Multipart(value = "byte") byte[] _byte, @Multipart(value = "integer", required = false) Integer integer, @Multipart(value = "int32", required = false) Integer int32, @Multipart(value = "int64", required = false) Long int64, @Multipart(value = "float", required = false) Float _float, @Multipart(value = "string", required = false) String string, @Multipart(value = "binary", required = false) byte[] binary, @Multipart(value = "date", required = false) LocalDate date, @Multipart(value = "dateTime", required = false) Date dateTime, @Multipart(value = "password", required = false) String password, @Multipart(value = "callback", required = false) String paramCallback); + /** + * To test enum parameters + * + * To test enum parameters + * + */ @GET @Path("/fake") @Consumes({ "*/*" }) @@ -84,6 +108,26 @@ public interface FakeApi { @ApiResponse(code = 404, message = "Not found") }) public void testEnumParameters(@Multipart(value = "enum_form_string_array", required = false) List enumFormStringArray, @Multipart(value = "enum_form_string", required = false) String enumFormString, @HeaderParam("enum_header_string_array") List enumHeaderStringArray, @HeaderParam("enum_header_string") String enumHeaderString, @QueryParam("enum_query_string_array") List enumQueryStringArray, @QueryParam("enum_query_string") @DefaultValue("-efg") String enumQueryString, @QueryParam("enum_query_integer") Integer enumQueryInteger, @Multipart(value = "enum_query_double", required = false) Double enumQueryDouble); + /** + * test inline additionalProperties + * + * + * + */ + @POST + @Path("/fake/inline-additionalProperties") + @Consumes({ "application/json" }) + @ApiOperation(value = "test inline additionalProperties", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation") }) + public void testInlineAdditionalProperties(@Valid Object param); + + /** + * test json serialization of form data + * + * + * + */ @GET @Path("/fake/jsonFormData") @Consumes({ "application/json" }) diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/FakeClassnameTags123Api.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/FakeClassnameTags123Api.java index 021e7eeb91f..63de6839dc1 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/FakeClassnameTags123Api.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/FakeClassnameTags123Api.java @@ -19,10 +19,20 @@ import io.swagger.jaxrs.PATCH; import javax.validation.constraints.*; import javax.validation.Valid; +/** + * 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: \" \\ + * + */ @Path("/") @Api(value = "/", description = "") public interface FakeClassnameTags123Api { + /** + * To test class name in snake case + * + */ @PATCH @Path("/fake_classname_test") @Consumes({ "application/json" }) diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java index 93a82ed4f6c..20fab16db0c 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java @@ -21,10 +21,22 @@ import io.swagger.jaxrs.PATCH; import javax.validation.constraints.*; import javax.validation.Valid; +/** + * 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: \" \\ + * + */ @Path("/") @Api(value = "/", description = "") public interface PetApi { + /** + * Add a new pet to the store + * + * + * + */ @POST @Path("/pet") @Consumes({ "application/json", "application/xml" }) @@ -34,6 +46,12 @@ public interface PetApi { @ApiResponse(code = 405, message = "Invalid input") }) public void addPet(@Valid Pet body); + /** + * Deletes a pet + * + * + * + */ @DELETE @Path("/pet/{petId}") @Produces({ "application/xml", "application/json" }) @@ -42,6 +60,12 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid pet value") }) public void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey); + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + */ @GET @Path("/pet/findByStatus") @Produces({ "application/xml", "application/json" }) @@ -51,6 +75,12 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid status value") }) public List findPetsByStatus(@QueryParam("status") @NotNull List status); + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + */ @GET @Path("/pet/findByTags") @Produces({ "application/xml", "application/json" }) @@ -60,6 +90,12 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid tag value") }) public List findPetsByTags(@QueryParam("tags") @NotNull List tags); + /** + * Find pet by ID + * + * Returns a single pet + * + */ @GET @Path("/pet/{petId}") @Produces({ "application/xml", "application/json" }) @@ -70,6 +106,12 @@ public interface PetApi { @ApiResponse(code = 404, message = "Pet not found") }) public Pet getPetById(@PathParam("petId") Long petId); + /** + * Update an existing pet + * + * + * + */ @PUT @Path("/pet") @Consumes({ "application/json", "application/xml" }) @@ -81,6 +123,12 @@ public interface PetApi { @ApiResponse(code = 405, message = "Validation exception") }) public void updatePet(@Valid Pet body); + /** + * Updates a pet in the store with form data + * + * + * + */ @POST @Path("/pet/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) @@ -90,6 +138,12 @@ public interface PetApi { @ApiResponse(code = 405, message = "Invalid input") }) public void updatePetWithForm(@PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status); + /** + * uploads an image + * + * + * + */ @POST @Path("/pet/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java index 2698ca445e6..065420cf357 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java @@ -20,10 +20,22 @@ import io.swagger.jaxrs.PATCH; import javax.validation.constraints.*; import javax.validation.Valid; +/** + * 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: \" \\ + * + */ @Path("/") @Api(value = "/", description = "") public interface StoreApi { + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + */ @DELETE @Path("/store/order/{order_id}") @Produces({ "application/xml", "application/json" }) @@ -33,6 +45,12 @@ public interface StoreApi { @ApiResponse(code = 404, message = "Order not found") }) public void deleteOrder(@PathParam("order_id") String orderId); + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + */ @GET @Path("/store/inventory") @Produces({ "application/json" }) @@ -41,6 +59,12 @@ public interface StoreApi { @ApiResponse(code = 200, message = "successful operation", response = Map.class, responseContainer = "Map") }) public Map getInventory(); + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + */ @GET @Path("/store/order/{order_id}") @Produces({ "application/xml", "application/json" }) @@ -51,6 +75,12 @@ public interface StoreApi { @ApiResponse(code = 404, message = "Order not found") }) public Order getOrderById(@PathParam("order_id") @Min(1) @Max(5) Long orderId); + /** + * Place an order for a pet + * + * + * + */ @POST @Path("/store/order") @Produces({ "application/xml", "application/json" }) diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java index 5588dddf74f..3e0d6350623 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java @@ -20,10 +20,22 @@ import io.swagger.jaxrs.PATCH; import javax.validation.constraints.*; import javax.validation.Valid; +/** + * 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: \" \\ + * + */ @Path("/") @Api(value = "/", description = "") public interface UserApi { + /** + * Create user + * + * This can only be done by the logged in user. + * + */ @POST @Path("/user") @Produces({ "application/xml", "application/json" }) @@ -32,6 +44,12 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation") }) public void createUser(@Valid User body); + /** + * Creates list of users with given input array + * + * + * + */ @POST @Path("/user/createWithArray") @Produces({ "application/xml", "application/json" }) @@ -40,6 +58,12 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation") }) public void createUsersWithArrayInput(@Valid List body); + /** + * Creates list of users with given input array + * + * + * + */ @POST @Path("/user/createWithList") @Produces({ "application/xml", "application/json" }) @@ -48,6 +72,12 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation") }) public void createUsersWithListInput(@Valid List body); + /** + * Delete user + * + * This can only be done by the logged in user. + * + */ @DELETE @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) @@ -57,6 +87,12 @@ public interface UserApi { @ApiResponse(code = 404, message = "User not found") }) public void deleteUser(@PathParam("username") String username); + /** + * Get user by user name + * + * + * + */ @GET @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) @@ -67,6 +103,12 @@ public interface UserApi { @ApiResponse(code = 404, message = "User not found") }) public User getUserByName(@PathParam("username") String username); + /** + * Logs user into the system + * + * + * + */ @GET @Path("/user/login") @Produces({ "application/xml", "application/json" }) @@ -76,6 +118,12 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid username/password supplied") }) public String loginUser(@QueryParam("username") @NotNull String username, @QueryParam("password") @NotNull String password); + /** + * Logs out current logged in user session + * + * + * + */ @GET @Path("/user/logout") @Produces({ "application/xml", "application/json" }) @@ -84,6 +132,12 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation") }) public void logoutUser(); + /** + * Updated user + * + * This can only be done by the logged in user. + * + */ @PUT @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java index 2a684fce3bd..0fd4f04aeea 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -13,6 +13,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class AdditionalPropertiesClass { @@ -25,6 +26,7 @@ public class AdditionalPropertiesClass { * Get mapProperty * @return mapProperty **/ + @JsonProperty("map_property") public Map getMapProperty() { return mapProperty; } @@ -47,6 +49,7 @@ public class AdditionalPropertiesClass { * Get mapOfMapProperty * @return mapOfMapProperty **/ + @JsonProperty("map_of_map_property") public Map> getMapOfMapProperty() { return mapOfMapProperty; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Animal.java index 7b8b9faa45e..29ad41d9e98 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Animal.java @@ -12,6 +12,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class Animal { @@ -24,6 +25,7 @@ public class Animal { * Get className * @return className **/ + @JsonProperty("className") @NotNull public String getClassName() { return className; @@ -42,6 +44,7 @@ public class Animal { * Get color * @return color **/ + @JsonProperty("color") public String getColor() { return color; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AnimalFarm.java index b9ceb010054..e3ea311206f 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AnimalFarm.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AnimalFarm.java @@ -13,6 +13,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class AnimalFarm extends ArrayList { diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java index cf72f92cd9e..da2ba2eba34 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -13,6 +13,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class ArrayOfArrayOfNumberOnly { @@ -23,6 +24,7 @@ public class ArrayOfArrayOfNumberOnly { * Get arrayArrayNumber * @return arrayArrayNumber **/ + @JsonProperty("ArrayArrayNumber") public List> getArrayArrayNumber() { return arrayArrayNumber; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java index 6c1b6335d96..30ad053c214 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -13,6 +13,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class ArrayOfNumberOnly { @@ -23,6 +24,7 @@ public class ArrayOfNumberOnly { * Get arrayNumber * @return arrayNumber **/ + @JsonProperty("ArrayNumber") public List getArrayNumber() { return arrayNumber; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayTest.java index 36523b49963..c76d50e816f 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayTest.java @@ -13,6 +13,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class ArrayTest { @@ -27,6 +28,7 @@ public class ArrayTest { * Get arrayOfString * @return arrayOfString **/ + @JsonProperty("array_of_string") public List getArrayOfString() { return arrayOfString; } @@ -49,6 +51,7 @@ public class ArrayTest { * Get arrayArrayOfInteger * @return arrayArrayOfInteger **/ + @JsonProperty("array_array_of_integer") public List> getArrayArrayOfInteger() { return arrayArrayOfInteger; } @@ -71,6 +74,7 @@ public class ArrayTest { * Get arrayArrayOfModel * @return arrayArrayOfModel **/ + @JsonProperty("array_array_of_model") public List> getArrayArrayOfModel() { return arrayArrayOfModel; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Capitalization.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Capitalization.java index 8d25cc55cb3..89278c7c298 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Capitalization.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Capitalization.java @@ -10,6 +10,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class Capitalization { @@ -24,12 +25,16 @@ public class Capitalization { @ApiModelProperty(value = "") private String scAETHFlowPoints = null; @ApiModelProperty(value = "Name of the pet ") + /** + * Name of the pet + **/ private String ATT_NAME = null; /** * Get smallCamel * @return smallCamel **/ + @JsonProperty("smallCamel") public String getSmallCamel() { return smallCamel; } @@ -47,6 +52,7 @@ public class Capitalization { * Get capitalCamel * @return capitalCamel **/ + @JsonProperty("CapitalCamel") public String getCapitalCamel() { return capitalCamel; } @@ -64,6 +70,7 @@ public class Capitalization { * Get smallSnake * @return smallSnake **/ + @JsonProperty("small_Snake") public String getSmallSnake() { return smallSnake; } @@ -81,6 +88,7 @@ public class Capitalization { * Get capitalSnake * @return capitalSnake **/ + @JsonProperty("Capital_Snake") public String getCapitalSnake() { return capitalSnake; } @@ -98,6 +106,7 @@ public class Capitalization { * Get scAETHFlowPoints * @return scAETHFlowPoints **/ + @JsonProperty("SCA_ETH_Flow_Points") public String getScAETHFlowPoints() { return scAETHFlowPoints; } @@ -115,6 +124,7 @@ public class Capitalization { * Name of the pet * @return ATT_NAME **/ + @JsonProperty("ATT_NAME") public String getATTNAME() { return ATT_NAME; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Cat.java index 490db608125..64f6869a3f8 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Cat.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Cat.java @@ -11,6 +11,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class Cat extends Animal { @@ -21,6 +22,7 @@ public class Cat extends Animal { * Get declawed * @return declawed **/ + @JsonProperty("declawed") public Boolean isDeclawed() { return declawed; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java index 6abf3c9c6cb..d16c0c2d3d4 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java @@ -10,6 +10,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class Category { @@ -22,6 +23,7 @@ public class Category { * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -39,6 +41,7 @@ public class Category { * Get name * @return name **/ + @JsonProperty("name") public String getName() { return name; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ClassModel.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ClassModel.java index 9f4a079d27a..fcdc0f57054 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ClassModel.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ClassModel.java @@ -11,7 +11,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * Model for testing model with \"_class\" property + **/ @ApiModel(description="Model for testing model with \"_class\" property") public class ClassModel { @@ -22,6 +26,7 @@ public class ClassModel { * Get propertyClass * @return propertyClass **/ + @JsonProperty("_class") public String getPropertyClass() { return propertyClass; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Client.java index c3eff86cc82..ee4bb6ffcf0 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Client.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Client.java @@ -10,6 +10,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class Client { @@ -20,6 +21,7 @@ public class Client { * Get client * @return client **/ + @JsonProperty("client") public String getClient() { return client; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Dog.java index 80aaf8dcfdd..3cdf1f4adcb 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Dog.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Dog.java @@ -11,6 +11,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class Dog extends Animal { @@ -21,6 +22,7 @@ public class Dog extends Animal { * Get breed * @return breed **/ + @JsonProperty("breed") public String getBreed() { return breed; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumArrays.java index 1a76571a267..68193c7ada4 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumArrays.java @@ -12,6 +12,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class EnumArrays { @@ -90,8 +91,12 @@ public enum ArrayEnumEnum { * Get justSymbol * @return justSymbol **/ - public JustSymbolEnum getJustSymbol() { - return justSymbol; + @JsonProperty("just_symbol") + public String getJustSymbol() { + if (justSymbol == null) { + return null; + } + return justSymbol.value(); } public void setJustSymbol(JustSymbolEnum justSymbol) { @@ -107,6 +112,7 @@ public enum ArrayEnumEnum { * Get arrayEnum * @return arrayEnum **/ + @JsonProperty("array_enum") public List getArrayEnum() { return arrayEnum; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumTest.java index 44199a514af..e4db3ed4395 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumTest.java @@ -11,6 +11,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class EnumTest { @@ -126,8 +127,12 @@ public enum EnumNumberEnum { * Get enumString * @return enumString **/ - public EnumStringEnum getEnumString() { - return enumString; + @JsonProperty("enum_string") + public String getEnumString() { + if (enumString == null) { + return null; + } + return enumString.value(); } public void setEnumString(EnumStringEnum enumString) { @@ -143,8 +148,12 @@ public enum EnumNumberEnum { * Get enumInteger * @return enumInteger **/ - public EnumIntegerEnum getEnumInteger() { - return enumInteger; + @JsonProperty("enum_integer") + public Integer getEnumInteger() { + if (enumInteger == null) { + return null; + } + return enumInteger.value(); } public void setEnumInteger(EnumIntegerEnum enumInteger) { @@ -160,8 +169,12 @@ public enum EnumNumberEnum { * Get enumNumber * @return enumNumber **/ - public EnumNumberEnum getEnumNumber() { - return enumNumber; + @JsonProperty("enum_number") + public Double getEnumNumber() { + if (enumNumber == null) { + return null; + } + return enumNumber.value(); } public void setEnumNumber(EnumNumberEnum enumNumber) { @@ -177,6 +190,7 @@ public enum EnumNumberEnum { * Get outerEnum * @return outerEnum **/ + @JsonProperty("outerEnum") public OuterEnum getOuterEnum() { return outerEnum; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/FormatTest.java index bbb02c85253..1e90851cede 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/FormatTest.java @@ -14,6 +14,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class FormatTest { @@ -50,6 +51,7 @@ public class FormatTest { * maximum: 100 * @return integer **/ + @JsonProperty("integer") @Min(10) @Max(100) public Integer getInteger() { return integer; } @@ -69,6 +71,7 @@ public class FormatTest { * maximum: 200 * @return int32 **/ + @JsonProperty("int32") @Min(20) @Max(200) public Integer getInt32() { return int32; } @@ -86,6 +89,7 @@ public class FormatTest { * Get int64 * @return int64 **/ + @JsonProperty("int64") public Long getInt64() { return int64; } @@ -105,6 +109,7 @@ public class FormatTest { * maximum: 543.2 * @return number **/ + @JsonProperty("number") @NotNull @DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { return number; @@ -125,6 +130,7 @@ public class FormatTest { * maximum: 987.6 * @return _float **/ + @JsonProperty("float") @DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -144,6 +150,7 @@ public class FormatTest { * maximum: 123.4 * @return _double **/ + @JsonProperty("double") @DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -161,6 +168,7 @@ public class FormatTest { * Get string * @return string **/ + @JsonProperty("string") @Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -178,6 +186,7 @@ public class FormatTest { * Get _byte * @return _byte **/ + @JsonProperty("byte") @NotNull @Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") public byte[] getByte() { return _byte; @@ -196,6 +205,7 @@ public class FormatTest { * Get binary * @return binary **/ + @JsonProperty("binary") public byte[] getBinary() { return binary; } @@ -213,6 +223,7 @@ public class FormatTest { * Get date * @return date **/ + @JsonProperty("date") @NotNull public LocalDate getDate() { return date; @@ -231,6 +242,7 @@ public class FormatTest { * Get dateTime * @return dateTime **/ + @JsonProperty("dateTime") public Date getDateTime() { return dateTime; } @@ -248,6 +260,7 @@ public class FormatTest { * Get uuid * @return uuid **/ + @JsonProperty("uuid") public UUID getUuid() { return uuid; } @@ -265,6 +278,7 @@ public class FormatTest { * Get password * @return password **/ + @JsonProperty("password") @NotNull @Size(min=10,max=64) public String getPassword() { return password; diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/HasOnlyReadOnly.java index 975088e5928..079686f4d3f 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -10,6 +10,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class HasOnlyReadOnly { @@ -22,6 +23,7 @@ public class HasOnlyReadOnly { * Get bar * @return bar **/ + @JsonProperty("bar") public String getBar() { return bar; } @@ -31,6 +33,7 @@ public class HasOnlyReadOnly { * Get foo * @return foo **/ + @JsonProperty("foo") public String getFoo() { return foo; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MapTest.java index 896bfc54829..cf29fcfb87d 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MapTest.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MapTest.java @@ -13,6 +13,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class MapTest { @@ -58,6 +59,7 @@ public enum InnerEnum { * Get mapMapOfString * @return mapMapOfString **/ + @JsonProperty("map_map_of_string") public Map> getMapMapOfString() { return mapMapOfString; } @@ -80,6 +82,7 @@ public enum InnerEnum { * Get mapOfEnumString * @return mapOfEnumString **/ + @JsonProperty("map_of_enum_string") public Map getMapOfEnumString() { return mapOfEnumString; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java index 51f18692f46..fa87343a7e6 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -16,6 +16,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class MixedPropertiesAndAdditionalPropertiesClass { @@ -30,6 +31,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { * Get uuid * @return uuid **/ + @JsonProperty("uuid") public UUID getUuid() { return uuid; } @@ -47,6 +49,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { * Get dateTime * @return dateTime **/ + @JsonProperty("dateTime") public Date getDateTime() { return dateTime; } @@ -64,6 +67,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { * Get map * @return map **/ + @JsonProperty("map") public Map getMap() { return map; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Model200Response.java index 1f2a89db5d3..4a5621e30be 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Model200Response.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Model200Response.java @@ -11,7 +11,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * Model for testing model name starting with number + **/ @ApiModel(description="Model for testing model name starting with number") public class Model200Response { @@ -24,6 +28,7 @@ public class Model200Response { * Get name * @return name **/ + @JsonProperty("name") public Integer getName() { return name; } @@ -41,6 +46,7 @@ public class Model200Response { * Get propertyClass * @return propertyClass **/ + @JsonProperty("class") public String getPropertyClass() { return propertyClass; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java index 536fecd5949..1b313aaa3a0 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -10,6 +10,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class ModelApiResponse { @@ -24,6 +25,7 @@ public class ModelApiResponse { * Get code * @return code **/ + @JsonProperty("code") public Integer getCode() { return code; } @@ -41,6 +43,7 @@ public class ModelApiResponse { * Get type * @return type **/ + @JsonProperty("type") public String getType() { return type; } @@ -58,6 +61,7 @@ public class ModelApiResponse { * Get message * @return message **/ + @JsonProperty("message") public String getMessage() { return message; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelReturn.java index 3a56f9c8683..0c514b23b5c 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelReturn.java @@ -11,7 +11,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * Model for testing reserved words + **/ @ApiModel(description="Model for testing reserved words") public class ModelReturn { @@ -22,6 +26,7 @@ public class ModelReturn { * Get _return * @return _return **/ + @JsonProperty("return") public Integer getReturn() { return _return; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Name.java index d5edcadd585..8743ac35dbb 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Name.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Name.java @@ -11,7 +11,11 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; +/** + * Model for testing model name same as property name + **/ @ApiModel(description="Model for testing model name same as property name") public class Name { @@ -28,6 +32,7 @@ public class Name { * Get name * @return name **/ + @JsonProperty("name") @NotNull public Integer getName() { return name; @@ -46,6 +51,7 @@ public class Name { * Get snakeCase * @return snakeCase **/ + @JsonProperty("snake_case") public Integer getSnakeCase() { return snakeCase; } @@ -55,6 +61,7 @@ public class Name { * Get property * @return property **/ + @JsonProperty("property") public String getProperty() { return property; } @@ -72,6 +79,7 @@ public class Name { * Get _123Number * @return _123Number **/ + @JsonProperty("123Number") public Integer get123Number() { return _123Number; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/NumberOnly.java index 60e46381901..b6755c7a9a2 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/NumberOnly.java @@ -11,6 +11,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class NumberOnly { @@ -21,6 +22,7 @@ public class NumberOnly { * Get justNumber * @return justNumber **/ + @JsonProperty("JustNumber") public BigDecimal getJustNumber() { return justNumber; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java index c479b33bc35..4b5fbdf9640 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java @@ -11,6 +11,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class Order { @@ -56,6 +57,9 @@ public enum StatusEnum { } @ApiModelProperty(value = "Order Status") + /** + * Order Status + **/ private StatusEnum status = null; @ApiModelProperty(value = "") private Boolean complete = false; @@ -64,6 +68,7 @@ public enum StatusEnum { * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -81,6 +86,7 @@ public enum StatusEnum { * Get petId * @return petId **/ + @JsonProperty("petId") public Long getPetId() { return petId; } @@ -98,6 +104,7 @@ public enum StatusEnum { * Get quantity * @return quantity **/ + @JsonProperty("quantity") public Integer getQuantity() { return quantity; } @@ -115,6 +122,7 @@ public enum StatusEnum { * Get shipDate * @return shipDate **/ + @JsonProperty("shipDate") public Date getShipDate() { return shipDate; } @@ -132,8 +140,12 @@ public enum StatusEnum { * Order Status * @return status **/ - public StatusEnum getStatus() { - return status; + @JsonProperty("status") + public String getStatus() { + if (status == null) { + return null; + } + return status.value(); } public void setStatus(StatusEnum status) { @@ -149,6 +161,7 @@ public enum StatusEnum { * Get complete * @return complete **/ + @JsonProperty("complete") public Boolean isComplete() { return complete; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/OuterComposite.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/OuterComposite.java index 264121fb46d..82c7d8fa9d9 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/OuterComposite.java @@ -11,6 +11,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class OuterComposite { @@ -25,6 +26,7 @@ public class OuterComposite { * Get myNumber * @return myNumber **/ + @JsonProperty("my_number") public BigDecimal getMyNumber() { return myNumber; } @@ -42,6 +44,7 @@ public class OuterComposite { * Get myString * @return myString **/ + @JsonProperty("my_string") public String getMyString() { return myString; } @@ -59,6 +62,7 @@ public class OuterComposite { * Get myBoolean * @return myBoolean **/ + @JsonProperty("my_boolean") public Boolean getMyBoolean() { return myBoolean; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java index 4d6215faf10..8cb32bc3e9c 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java @@ -14,6 +14,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class Pet { @@ -61,12 +62,16 @@ public enum StatusEnum { } @ApiModelProperty(value = "pet status in the store") + /** + * pet status in the store + **/ private StatusEnum status = null; /** * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -84,6 +89,7 @@ public enum StatusEnum { * Get category * @return category **/ + @JsonProperty("category") public Category getCategory() { return category; } @@ -101,6 +107,7 @@ public enum StatusEnum { * Get name * @return name **/ + @JsonProperty("name") @NotNull public String getName() { return name; @@ -119,6 +126,7 @@ public enum StatusEnum { * Get photoUrls * @return photoUrls **/ + @JsonProperty("photoUrls") @NotNull public List getPhotoUrls() { return photoUrls; @@ -142,6 +150,7 @@ public enum StatusEnum { * Get tags * @return tags **/ + @JsonProperty("tags") public List getTags() { return tags; } @@ -164,8 +173,12 @@ public enum StatusEnum { * pet status in the store * @return status **/ - public StatusEnum getStatus() { - return status; + @JsonProperty("status") + public String getStatus() { + if (status == null) { + return null; + } + return status.value(); } public void setStatus(StatusEnum status) { diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ReadOnlyFirst.java index f6868a7d344..d6c2527bc13 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -10,6 +10,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class ReadOnlyFirst { @@ -22,6 +23,7 @@ public class ReadOnlyFirst { * Get bar * @return bar **/ + @JsonProperty("bar") public String getBar() { return bar; } @@ -31,6 +33,7 @@ public class ReadOnlyFirst { * Get baz * @return baz **/ + @JsonProperty("baz") public String getBaz() { return baz; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/SpecialModelName.java index ebf181b8db6..af734ec937d 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/SpecialModelName.java @@ -10,6 +10,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class SpecialModelName { @@ -20,6 +21,7 @@ public class SpecialModelName { * Get specialPropertyName * @return specialPropertyName **/ + @JsonProperty("$special[property.name]") public Long getSpecialPropertyName() { return specialPropertyName; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java index 40cf3188aa7..77d43ac52eb 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java @@ -10,6 +10,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class Tag { @@ -22,6 +23,7 @@ public class Tag { * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -39,6 +41,7 @@ public class Tag { * Get name * @return name **/ + @JsonProperty("name") public String getName() { return name; } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java index dd95f042ad1..44509b594be 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java @@ -10,6 +10,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonProperty; public class User { @@ -28,12 +29,16 @@ public class User { @ApiModelProperty(value = "") private String phone = null; @ApiModelProperty(value = "User Status") + /** + * User Status + **/ private Integer userStatus = null; /** * Get id * @return id **/ + @JsonProperty("id") public Long getId() { return id; } @@ -51,6 +56,7 @@ public class User { * Get username * @return username **/ + @JsonProperty("username") public String getUsername() { return username; } @@ -68,6 +74,7 @@ public class User { * Get firstName * @return firstName **/ + @JsonProperty("firstName") public String getFirstName() { return firstName; } @@ -85,6 +92,7 @@ public class User { * Get lastName * @return lastName **/ + @JsonProperty("lastName") public String getLastName() { return lastName; } @@ -102,6 +110,7 @@ public class User { * Get email * @return email **/ + @JsonProperty("email") public String getEmail() { return email; } @@ -119,6 +128,7 @@ public class User { * Get password * @return password **/ + @JsonProperty("password") public String getPassword() { return password; } @@ -136,6 +146,7 @@ public class User { * Get phone * @return phone **/ + @JsonProperty("phone") public String getPhone() { return phone; } @@ -153,6 +164,7 @@ public class User { * User Status * @return userStatus **/ + @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } diff --git a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/AnotherFakeApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/AnotherFakeApiServiceImpl.java index 5de97453193..a162ec64ee7 100644 --- a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/AnotherFakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/AnotherFakeApiServiceImpl.java @@ -16,7 +16,19 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; +/** + * 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: \" \\ + * + */ public class AnotherFakeApiServiceImpl implements AnotherFakeApi { + /** + * To test special tags + * + * To test special tags + * + */ public Client testSpecialTags(Client body) { // TODO: Implement... diff --git a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java index b170bddee2d..9f0c36bd52d 100644 --- a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java @@ -20,6 +20,12 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; +/** + * 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: \" \\ + * + */ public class FakeApiServiceImpl implements FakeApi { public Boolean fakeOuterBooleanSerialize(Boolean body) { // TODO: Implement... @@ -45,24 +51,60 @@ public class FakeApiServiceImpl implements FakeApi { return null; } + /** + * To test \"client\" model + * + * To test \"client\" model + * + */ public Client testClientModel(Client body) { // TODO: Implement... return null; } + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + */ public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, Date dateTime, String password, String paramCallback) { // TODO: Implement... } + /** + * To test enum parameters + * + * To test enum parameters + * + */ public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) { // TODO: Implement... } + /** + * test inline additionalProperties + * + * + * + */ + public void testInlineAdditionalProperties(Object param) { + // TODO: Implement... + + + } + + /** + * test json serialization of form data + * + * + * + */ public void testJsonFormData(String param, String param2) { // TODO: Implement... diff --git a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/FakeClassnameTags123ApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/FakeClassnameTags123ApiServiceImpl.java index 539edc610d9..ad3f555af97 100644 --- a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/FakeClassnameTags123ApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/FakeClassnameTags123ApiServiceImpl.java @@ -16,7 +16,17 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; +/** + * 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: \" \\ + * + */ public class FakeClassnameTags123ApiServiceImpl implements FakeClassnameTags123Api { + /** + * To test class name in snake case + * + */ public Client testClassname(Client body) { // TODO: Implement... diff --git a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index d9b9345d339..439daacb1b2 100644 --- a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -18,49 +18,103 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; +/** + * 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: \" \\ + * + */ public class PetApiServiceImpl implements PetApi { + /** + * Add a new pet to the store + * + * + * + */ public void addPet(Pet body) { // TODO: Implement... } + /** + * Deletes a pet + * + * + * + */ public void deletePet(Long petId, String apiKey) { // TODO: Implement... } + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + */ public List findPetsByStatus(List status) { // TODO: Implement... return null; } + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + */ public List findPetsByTags(List tags) { // TODO: Implement... return null; } + /** + * Find pet by ID + * + * Returns a single pet + * + */ public Pet getPetById(Long petId) { // TODO: Implement... return null; } + /** + * Update an existing pet + * + * + * + */ public void updatePet(Pet body) { // TODO: Implement... } + /** + * Updates a pet in the store with form data + * + * + * + */ public void updatePetWithForm(Long petId, String name, String status) { // TODO: Implement... } + /** + * uploads an image + * + * + * + */ public ModelApiResponse uploadFile(Long petId, String additionalMetadata, Attachment fileDetail) { // TODO: Implement... diff --git a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index 3f791097b6b..546d096399b 100644 --- a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -17,25 +17,55 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; +/** + * 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: \" \\ + * + */ public class StoreApiServiceImpl implements StoreApi { + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + */ public void deleteOrder(String orderId) { // TODO: Implement... } + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + */ public Map getInventory() { // TODO: Implement... return null; } + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + */ public Order getOrderById(Long orderId) { // TODO: Implement... return null; } + /** + * Place an order for a pet + * + * + * + */ public Order placeOrder(Order body) { // TODO: Implement... diff --git a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index 861273cfb7b..363a42dad0e 100644 --- a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -17,49 +17,103 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; +/** + * 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: \" \\ + * + */ public class UserApiServiceImpl implements UserApi { + /** + * Create user + * + * This can only be done by the logged in user. + * + */ public void createUser(User body) { // TODO: Implement... } + /** + * Creates list of users with given input array + * + * + * + */ public void createUsersWithArrayInput(List body) { // TODO: Implement... } + /** + * Creates list of users with given input array + * + * + * + */ public void createUsersWithListInput(List body) { // TODO: Implement... } + /** + * Delete user + * + * This can only be done by the logged in user. + * + */ public void deleteUser(String username) { // TODO: Implement... } + /** + * Get user by user name + * + * + * + */ public User getUserByName(String username) { // TODO: Implement... return null; } + /** + * Logs user into the system + * + * + * + */ public String loginUser(String username, String password) { // TODO: Implement... return null; } + /** + * Logs out current logged in user session + * + * + * + */ public void logoutUser() { // TODO: Implement... } + /** + * Updated user + * + * This can only be done by the logged in user. + * + */ public void updateUser(String username, User body) { // TODO: Implement... diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java index 820bb4a2f18..6aa5fc2b980 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -10,6 +10,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class AdditionalPropertiesClass implements Serializable { @@ -26,6 +27,7 @@ public class AdditionalPropertiesClass implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("map_property") public Map getMapProperty() { return mapProperty; } @@ -42,6 +44,7 @@ public class AdditionalPropertiesClass implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("map_of_map_property") public Map> getMapOfMapProperty() { return mapOfMapProperty; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Animal.java index f7aef656d44..bb54e9cad22 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Animal.java @@ -9,6 +9,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Animal implements Serializable { @@ -25,6 +26,7 @@ public class Animal implements Serializable { @ApiModelProperty(required = true, value = "") + @JsonProperty("className") @NotNull public String getClassName() { return className; @@ -42,6 +44,7 @@ public class Animal implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("color") public String getColor() { return color; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/AnimalFarm.java index ca03cafd3ef..f14a33d343e 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/AnimalFarm.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/AnimalFarm.java @@ -10,6 +10,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class AnimalFarm extends ArrayList implements Serializable { diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java index 558c55d50e1..0be06450317 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -10,6 +10,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class ArrayOfArrayOfNumberOnly implements Serializable { @@ -25,6 +26,7 @@ public class ArrayOfArrayOfNumberOnly implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("ArrayArrayNumber") public List> getArrayArrayNumber() { return arrayArrayNumber; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java index 780c9bf0df8..c131d2c633a 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -10,6 +10,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class ArrayOfNumberOnly implements Serializable { @@ -25,6 +26,7 @@ public class ArrayOfNumberOnly implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("ArrayNumber") public List getArrayNumber() { return arrayNumber; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ArrayTest.java index f6ef76af0d6..1720cde126c 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ArrayTest.java @@ -10,6 +10,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class ArrayTest implements Serializable { @@ -27,6 +28,7 @@ public class ArrayTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("array_of_string") public List getArrayOfString() { return arrayOfString; } @@ -43,6 +45,7 @@ public class ArrayTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("array_array_of_integer") public List> getArrayArrayOfInteger() { return arrayArrayOfInteger; } @@ -59,6 +62,7 @@ public class ArrayTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("array_array_of_model") public List> getArrayArrayOfModel() { return arrayArrayOfModel; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Capitalization.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Capitalization.java index 385c622b0ba..00402e4788a 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Capitalization.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Capitalization.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Capitalization implements Serializable { @@ -27,6 +28,7 @@ public class Capitalization implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("smallCamel") public String getSmallCamel() { return smallCamel; } @@ -43,6 +45,7 @@ public class Capitalization implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("CapitalCamel") public String getCapitalCamel() { return capitalCamel; } @@ -59,6 +62,7 @@ public class Capitalization implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("small_Snake") public String getSmallSnake() { return smallSnake; } @@ -75,6 +79,7 @@ public class Capitalization implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("Capital_Snake") public String getCapitalSnake() { return capitalSnake; } @@ -91,6 +96,7 @@ public class Capitalization implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("SCA_ETH_Flow_Points") public String getScAETHFlowPoints() { return scAETHFlowPoints; } @@ -108,6 +114,7 @@ public class Capitalization implements Serializable { @ApiModelProperty(value = "Name of the pet ") + @JsonProperty("ATT_NAME") public String getATTNAME() { return ATT_NAME; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Cat.java index f334fcd1914..086c6462d8e 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Cat.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Cat.java @@ -8,6 +8,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Cat extends Animal implements Serializable { @@ -23,6 +24,7 @@ public class Cat extends Animal implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("declawed") public Boolean isDeclawed() { return declawed; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Category.java index 5cee21d0404..1e5c20bf730 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Category.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Category implements Serializable { @@ -23,6 +24,7 @@ public class Category implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -39,6 +41,7 @@ public class Category implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("name") public String getName() { return name; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ClassModel.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ClassModel.java index faa4cf796cb..c05c7b4a9b6 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ClassModel.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ClassModel.java @@ -11,6 +11,7 @@ import javax.validation.Valid; **/ import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "Model for testing model with \"_class\" property") public class ClassModel implements Serializable { @@ -26,6 +27,7 @@ public class ClassModel implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("_class") public String getPropertyClass() { return propertyClass; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Client.java index 55a8b4e31c0..61c2aef0512 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Client.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Client.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Client implements Serializable { @@ -22,6 +23,7 @@ public class Client implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("client") public String getClient() { return client; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Dog.java index e55012815c2..8c1d2c3f85b 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Dog.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Dog.java @@ -8,6 +8,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Dog extends Animal implements Serializable { @@ -23,6 +24,7 @@ public class Dog extends Animal implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("breed") public String getBreed() { return breed; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/EnumArrays.java index afb80283457..595f687217d 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/EnumArrays.java @@ -9,6 +9,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class EnumArrays implements Serializable { @@ -87,6 +88,7 @@ public enum ArrayEnumEnum { @ApiModelProperty(value = "") + @JsonProperty("just_symbol") public JustSymbolEnum getJustSymbol() { return justSymbol; } @@ -103,6 +105,7 @@ public enum ArrayEnumEnum { @ApiModelProperty(value = "") + @JsonProperty("array_enum") public List getArrayEnum() { return arrayEnum; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/EnumTest.java index 277fcf88e8d..d704287dd95 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/EnumTest.java @@ -8,6 +8,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class EnumTest implements Serializable { @@ -119,6 +120,7 @@ public enum EnumNumberEnum { @ApiModelProperty(value = "") + @JsonProperty("enum_string") public EnumStringEnum getEnumString() { return enumString; } @@ -135,6 +137,7 @@ public enum EnumNumberEnum { @ApiModelProperty(value = "") + @JsonProperty("enum_integer") public EnumIntegerEnum getEnumInteger() { return enumInteger; } @@ -151,6 +154,7 @@ public enum EnumNumberEnum { @ApiModelProperty(value = "") + @JsonProperty("enum_number") public EnumNumberEnum getEnumNumber() { return enumNumber; } @@ -167,6 +171,7 @@ public enum EnumNumberEnum { @ApiModelProperty(value = "") + @JsonProperty("outerEnum") public OuterEnum getOuterEnum() { return outerEnum; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/FormatTest.java index 64d0e10f9a1..bb3072fe1e9 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/FormatTest.java @@ -11,6 +11,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class FormatTest implements Serializable { @@ -40,6 +41,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("integer") @Min(10) @Max(100) public Integer getInteger() { return integer; } @@ -58,6 +60,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("int32") @Min(20) @Max(200) public Integer getInt32() { return int32; } @@ -74,6 +77,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("int64") public Long getInt64() { return int64; } @@ -92,6 +96,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(required = true, value = "") + @JsonProperty("number") @NotNull @DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { return number; @@ -111,6 +116,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("float") @DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -129,6 +135,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("double") @DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -145,6 +152,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("string") @Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -161,6 +169,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(required = true, value = "") + @JsonProperty("byte") @NotNull @Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") public byte[] getByte() { return _byte; @@ -178,6 +187,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("binary") public byte[] getBinary() { return binary; } @@ -194,6 +204,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(required = true, value = "") + @JsonProperty("date") @NotNull public LocalDate getDate() { return date; @@ -211,6 +222,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("dateTime") public Date getDateTime() { return dateTime; } @@ -227,6 +239,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("uuid") public UUID getUuid() { return uuid; } @@ -243,6 +256,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(required = true, value = "") + @JsonProperty("password") @NotNull @Size(min=10,max=64) public String getPassword() { return password; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/HasOnlyReadOnly.java index bef66ba21ee..ef9c2728846 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class HasOnlyReadOnly implements Serializable { @@ -23,6 +24,7 @@ public class HasOnlyReadOnly implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("bar") public String getBar() { return bar; } @@ -39,6 +41,7 @@ public class HasOnlyReadOnly implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("foo") public String getFoo() { return foo; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/MapTest.java index ff256f599d4..54abae05490 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/MapTest.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/MapTest.java @@ -10,6 +10,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class MapTest implements Serializable { @@ -57,6 +58,7 @@ public enum InnerEnum { @ApiModelProperty(value = "") + @JsonProperty("map_map_of_string") public Map> getMapMapOfString() { return mapMapOfString; } @@ -73,6 +75,7 @@ public enum InnerEnum { @ApiModelProperty(value = "") + @JsonProperty("map_of_enum_string") public Map getMapOfEnumString() { return mapOfEnumString; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java index d72ca2af084..673adda125e 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -13,6 +13,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class MixedPropertiesAndAdditionalPropertiesClass implements Serializable { @@ -30,6 +31,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass implements Serializabl @ApiModelProperty(value = "") + @JsonProperty("uuid") public UUID getUuid() { return uuid; } @@ -46,6 +48,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass implements Serializabl @ApiModelProperty(value = "") + @JsonProperty("dateTime") public Date getDateTime() { return dateTime; } @@ -62,6 +65,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass implements Serializabl @ApiModelProperty(value = "") + @JsonProperty("map") public Map getMap() { return map; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Model200Response.java index aedda176fb2..eeb8e7547cf 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Model200Response.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Model200Response.java @@ -11,6 +11,7 @@ import javax.validation.Valid; **/ import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "Model for testing model name starting with number") public class Model200Response implements Serializable { @@ -27,6 +28,7 @@ public class Model200Response implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("name") public Integer getName() { return name; } @@ -43,6 +45,7 @@ public class Model200Response implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("class") public String getPropertyClass() { return propertyClass; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ModelApiResponse.java index da860040d95..e97b1fdfd8b 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class ModelApiResponse implements Serializable { @@ -24,6 +25,7 @@ public class ModelApiResponse implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("code") public Integer getCode() { return code; } @@ -40,6 +42,7 @@ public class ModelApiResponse implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("type") public String getType() { return type; } @@ -56,6 +59,7 @@ public class ModelApiResponse implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("message") public String getMessage() { return message; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ModelReturn.java index 1e17a101c64..72a677f7ab0 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ModelReturn.java @@ -11,6 +11,7 @@ import javax.validation.Valid; **/ import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "Model for testing reserved words") public class ModelReturn implements Serializable { @@ -26,6 +27,7 @@ public class ModelReturn implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("return") public Integer getReturn() { return _return; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Name.java index 1c189b6e01d..5460ff8a9b9 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Name.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Name.java @@ -11,6 +11,7 @@ import javax.validation.Valid; **/ import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "Model for testing model name same as property name") public class Name implements Serializable { @@ -29,6 +30,7 @@ public class Name implements Serializable { @ApiModelProperty(required = true, value = "") + @JsonProperty("name") @NotNull public Integer getName() { return name; @@ -46,6 +48,7 @@ public class Name implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("snake_case") public Integer getSnakeCase() { return snakeCase; } @@ -62,6 +65,7 @@ public class Name implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("property") public String getProperty() { return property; } @@ -78,6 +82,7 @@ public class Name implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("123Number") public Integer get123Number() { return _123Number; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/NumberOnly.java index edff615a50d..5f02fd0649a 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/NumberOnly.java @@ -8,6 +8,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class NumberOnly implements Serializable { @@ -23,6 +24,7 @@ public class NumberOnly implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("JustNumber") public BigDecimal getJustNumber() { return justNumber; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Order.java index d7042477807..f7665f15a54 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Order.java @@ -8,6 +8,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Order implements Serializable { @@ -59,6 +60,7 @@ public enum StatusEnum { @ApiModelProperty(value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -75,6 +77,7 @@ public enum StatusEnum { @ApiModelProperty(value = "") + @JsonProperty("petId") public Long getPetId() { return petId; } @@ -91,6 +94,7 @@ public enum StatusEnum { @ApiModelProperty(value = "") + @JsonProperty("quantity") public Integer getQuantity() { return quantity; } @@ -107,6 +111,7 @@ public enum StatusEnum { @ApiModelProperty(value = "") + @JsonProperty("shipDate") public Date getShipDate() { return shipDate; } @@ -124,6 +129,7 @@ public enum StatusEnum { @ApiModelProperty(value = "Order Status") + @JsonProperty("status") public StatusEnum getStatus() { return status; } @@ -140,6 +146,7 @@ public enum StatusEnum { @ApiModelProperty(value = "") + @JsonProperty("complete") public Boolean isComplete() { return complete; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/OuterComposite.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/OuterComposite.java index c038e105892..bfe8211b654 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/OuterComposite.java @@ -8,6 +8,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class OuterComposite implements Serializable { @@ -25,6 +26,7 @@ public class OuterComposite implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("my_number") public BigDecimal getMyNumber() { return myNumber; } @@ -41,6 +43,7 @@ public class OuterComposite implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("my_string") public String getMyString() { return myString; } @@ -57,6 +60,7 @@ public class OuterComposite implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("my_boolean") public Boolean getMyBoolean() { return myBoolean; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Pet.java index 5bad5ba12d6..fc8a6796b79 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Pet.java @@ -11,6 +11,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Pet implements Serializable { @@ -62,6 +63,7 @@ public enum StatusEnum { @ApiModelProperty(value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -78,6 +80,7 @@ public enum StatusEnum { @ApiModelProperty(value = "") + @JsonProperty("category") public Category getCategory() { return category; } @@ -94,6 +97,7 @@ public enum StatusEnum { @ApiModelProperty(example = "doggie", required = true, value = "") + @JsonProperty("name") @NotNull public String getName() { return name; @@ -111,6 +115,7 @@ public enum StatusEnum { @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") @NotNull public List getPhotoUrls() { return photoUrls; @@ -128,6 +133,7 @@ public enum StatusEnum { @ApiModelProperty(value = "") + @JsonProperty("tags") public List getTags() { return tags; } @@ -145,6 +151,7 @@ public enum StatusEnum { @ApiModelProperty(value = "pet status in the store") + @JsonProperty("status") public StatusEnum getStatus() { return status; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ReadOnlyFirst.java index 0617b6904ea..bd4ee7e1cb1 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class ReadOnlyFirst implements Serializable { @@ -23,6 +24,7 @@ public class ReadOnlyFirst implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("bar") public String getBar() { return bar; } @@ -39,6 +41,7 @@ public class ReadOnlyFirst implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("baz") public String getBaz() { return baz; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/SpecialModelName.java index 9afe1f14834..b8144314b82 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/SpecialModelName.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class SpecialModelName implements Serializable { @@ -22,6 +23,7 @@ public class SpecialModelName implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("$special[property.name]") public Long getSpecialPropertyName() { return specialPropertyName; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Tag.java index 35c70dd8bbd..10a7ffc7c57 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/Tag.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Tag implements Serializable { @@ -23,6 +24,7 @@ public class Tag implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -39,6 +41,7 @@ public class Tag implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("name") public String getName() { return name; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/User.java index ad92725cb41..a86f0eae070 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/io/swagger/model/User.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class User implements Serializable { @@ -29,6 +30,7 @@ public class User implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -45,6 +47,7 @@ public class User implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("username") public String getUsername() { return username; } @@ -61,6 +64,7 @@ public class User implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("firstName") public String getFirstName() { return firstName; } @@ -77,6 +81,7 @@ public class User implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("lastName") public String getLastName() { return lastName; } @@ -93,6 +98,7 @@ public class User implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("email") public String getEmail() { return email; } @@ -109,6 +115,7 @@ public class User implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("password") public String getPassword() { return password; } @@ -125,6 +132,7 @@ public class User implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("phone") public String getPhone() { return phone; } @@ -142,6 +150,7 @@ public class User implements Serializable { @ApiModelProperty(value = "User Status") + @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java index 820bb4a2f18..6aa5fc2b980 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -10,6 +10,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class AdditionalPropertiesClass implements Serializable { @@ -26,6 +27,7 @@ public class AdditionalPropertiesClass implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("map_property") public Map getMapProperty() { return mapProperty; } @@ -42,6 +44,7 @@ public class AdditionalPropertiesClass implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("map_of_map_property") public Map> getMapOfMapProperty() { return mapOfMapProperty; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Animal.java index f7aef656d44..bb54e9cad22 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Animal.java @@ -9,6 +9,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Animal implements Serializable { @@ -25,6 +26,7 @@ public class Animal implements Serializable { @ApiModelProperty(required = true, value = "") + @JsonProperty("className") @NotNull public String getClassName() { return className; @@ -42,6 +44,7 @@ public class Animal implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("color") public String getColor() { return color; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/AnimalFarm.java index ca03cafd3ef..f14a33d343e 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/AnimalFarm.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/AnimalFarm.java @@ -10,6 +10,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class AnimalFarm extends ArrayList implements Serializable { diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java index 558c55d50e1..0be06450317 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -10,6 +10,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class ArrayOfArrayOfNumberOnly implements Serializable { @@ -25,6 +26,7 @@ public class ArrayOfArrayOfNumberOnly implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("ArrayArrayNumber") public List> getArrayArrayNumber() { return arrayArrayNumber; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java index 780c9bf0df8..c131d2c633a 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -10,6 +10,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class ArrayOfNumberOnly implements Serializable { @@ -25,6 +26,7 @@ public class ArrayOfNumberOnly implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("ArrayNumber") public List getArrayNumber() { return arrayNumber; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayTest.java index f6ef76af0d6..1720cde126c 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayTest.java @@ -10,6 +10,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class ArrayTest implements Serializable { @@ -27,6 +28,7 @@ public class ArrayTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("array_of_string") public List getArrayOfString() { return arrayOfString; } @@ -43,6 +45,7 @@ public class ArrayTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("array_array_of_integer") public List> getArrayArrayOfInteger() { return arrayArrayOfInteger; } @@ -59,6 +62,7 @@ public class ArrayTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("array_array_of_model") public List> getArrayArrayOfModel() { return arrayArrayOfModel; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Capitalization.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Capitalization.java index 385c622b0ba..00402e4788a 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Capitalization.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Capitalization.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Capitalization implements Serializable { @@ -27,6 +28,7 @@ public class Capitalization implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("smallCamel") public String getSmallCamel() { return smallCamel; } @@ -43,6 +45,7 @@ public class Capitalization implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("CapitalCamel") public String getCapitalCamel() { return capitalCamel; } @@ -59,6 +62,7 @@ public class Capitalization implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("small_Snake") public String getSmallSnake() { return smallSnake; } @@ -75,6 +79,7 @@ public class Capitalization implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("Capital_Snake") public String getCapitalSnake() { return capitalSnake; } @@ -91,6 +96,7 @@ public class Capitalization implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("SCA_ETH_Flow_Points") public String getScAETHFlowPoints() { return scAETHFlowPoints; } @@ -108,6 +114,7 @@ public class Capitalization implements Serializable { @ApiModelProperty(value = "Name of the pet ") + @JsonProperty("ATT_NAME") public String getATTNAME() { return ATT_NAME; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Cat.java index f334fcd1914..086c6462d8e 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Cat.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Cat.java @@ -8,6 +8,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Cat extends Animal implements Serializable { @@ -23,6 +24,7 @@ public class Cat extends Animal implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("declawed") public Boolean isDeclawed() { return declawed; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Category.java index 5cee21d0404..1e5c20bf730 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Category.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Category implements Serializable { @@ -23,6 +24,7 @@ public class Category implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -39,6 +41,7 @@ public class Category implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("name") public String getName() { return name; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ClassModel.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ClassModel.java index faa4cf796cb..c05c7b4a9b6 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ClassModel.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ClassModel.java @@ -11,6 +11,7 @@ import javax.validation.Valid; **/ import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "Model for testing model with \"_class\" property") public class ClassModel implements Serializable { @@ -26,6 +27,7 @@ public class ClassModel implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("_class") public String getPropertyClass() { return propertyClass; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Client.java index 55a8b4e31c0..61c2aef0512 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Client.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Client.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Client implements Serializable { @@ -22,6 +23,7 @@ public class Client implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("client") public String getClient() { return client; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Dog.java index e55012815c2..8c1d2c3f85b 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Dog.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Dog.java @@ -8,6 +8,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Dog extends Animal implements Serializable { @@ -23,6 +24,7 @@ public class Dog extends Animal implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("breed") public String getBreed() { return breed; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/EnumArrays.java index afb80283457..595f687217d 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/EnumArrays.java @@ -9,6 +9,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class EnumArrays implements Serializable { @@ -87,6 +88,7 @@ public enum ArrayEnumEnum { @ApiModelProperty(value = "") + @JsonProperty("just_symbol") public JustSymbolEnum getJustSymbol() { return justSymbol; } @@ -103,6 +105,7 @@ public enum ArrayEnumEnum { @ApiModelProperty(value = "") + @JsonProperty("array_enum") public List getArrayEnum() { return arrayEnum; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/EnumTest.java index 277fcf88e8d..d704287dd95 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/EnumTest.java @@ -8,6 +8,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class EnumTest implements Serializable { @@ -119,6 +120,7 @@ public enum EnumNumberEnum { @ApiModelProperty(value = "") + @JsonProperty("enum_string") public EnumStringEnum getEnumString() { return enumString; } @@ -135,6 +137,7 @@ public enum EnumNumberEnum { @ApiModelProperty(value = "") + @JsonProperty("enum_integer") public EnumIntegerEnum getEnumInteger() { return enumInteger; } @@ -151,6 +154,7 @@ public enum EnumNumberEnum { @ApiModelProperty(value = "") + @JsonProperty("enum_number") public EnumNumberEnum getEnumNumber() { return enumNumber; } @@ -167,6 +171,7 @@ public enum EnumNumberEnum { @ApiModelProperty(value = "") + @JsonProperty("outerEnum") public OuterEnum getOuterEnum() { return outerEnum; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/FormatTest.java index 64d0e10f9a1..bb3072fe1e9 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/FormatTest.java @@ -11,6 +11,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class FormatTest implements Serializable { @@ -40,6 +41,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("integer") @Min(10) @Max(100) public Integer getInteger() { return integer; } @@ -58,6 +60,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("int32") @Min(20) @Max(200) public Integer getInt32() { return int32; } @@ -74,6 +77,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("int64") public Long getInt64() { return int64; } @@ -92,6 +96,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(required = true, value = "") + @JsonProperty("number") @NotNull @DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { return number; @@ -111,6 +116,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("float") @DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -129,6 +135,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("double") @DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -145,6 +152,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("string") @Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -161,6 +169,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(required = true, value = "") + @JsonProperty("byte") @NotNull @Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") public byte[] getByte() { return _byte; @@ -178,6 +187,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("binary") public byte[] getBinary() { return binary; } @@ -194,6 +204,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(required = true, value = "") + @JsonProperty("date") @NotNull public LocalDate getDate() { return date; @@ -211,6 +222,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("dateTime") public Date getDateTime() { return dateTime; } @@ -227,6 +239,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("uuid") public UUID getUuid() { return uuid; } @@ -243,6 +256,7 @@ public class FormatTest implements Serializable { @ApiModelProperty(required = true, value = "") + @JsonProperty("password") @NotNull @Size(min=10,max=64) public String getPassword() { return password; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/HasOnlyReadOnly.java index bef66ba21ee..ef9c2728846 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class HasOnlyReadOnly implements Serializable { @@ -23,6 +24,7 @@ public class HasOnlyReadOnly implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("bar") public String getBar() { return bar; } @@ -39,6 +41,7 @@ public class HasOnlyReadOnly implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("foo") public String getFoo() { return foo; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/MapTest.java index ff256f599d4..54abae05490 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/MapTest.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/MapTest.java @@ -10,6 +10,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class MapTest implements Serializable { @@ -57,6 +58,7 @@ public enum InnerEnum { @ApiModelProperty(value = "") + @JsonProperty("map_map_of_string") public Map> getMapMapOfString() { return mapMapOfString; } @@ -73,6 +75,7 @@ public enum InnerEnum { @ApiModelProperty(value = "") + @JsonProperty("map_of_enum_string") public Map getMapOfEnumString() { return mapOfEnumString; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java index d72ca2af084..673adda125e 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -13,6 +13,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class MixedPropertiesAndAdditionalPropertiesClass implements Serializable { @@ -30,6 +31,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass implements Serializabl @ApiModelProperty(value = "") + @JsonProperty("uuid") public UUID getUuid() { return uuid; } @@ -46,6 +48,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass implements Serializabl @ApiModelProperty(value = "") + @JsonProperty("dateTime") public Date getDateTime() { return dateTime; } @@ -62,6 +65,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass implements Serializabl @ApiModelProperty(value = "") + @JsonProperty("map") public Map getMap() { return map; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Model200Response.java index aedda176fb2..eeb8e7547cf 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Model200Response.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Model200Response.java @@ -11,6 +11,7 @@ import javax.validation.Valid; **/ import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "Model for testing model name starting with number") public class Model200Response implements Serializable { @@ -27,6 +28,7 @@ public class Model200Response implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("name") public Integer getName() { return name; } @@ -43,6 +45,7 @@ public class Model200Response implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("class") public String getPropertyClass() { return propertyClass; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelApiResponse.java index da860040d95..e97b1fdfd8b 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class ModelApiResponse implements Serializable { @@ -24,6 +25,7 @@ public class ModelApiResponse implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("code") public Integer getCode() { return code; } @@ -40,6 +42,7 @@ public class ModelApiResponse implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("type") public String getType() { return type; } @@ -56,6 +59,7 @@ public class ModelApiResponse implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("message") public String getMessage() { return message; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelReturn.java index 1e17a101c64..72a677f7ab0 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelReturn.java @@ -11,6 +11,7 @@ import javax.validation.Valid; **/ import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "Model for testing reserved words") public class ModelReturn implements Serializable { @@ -26,6 +27,7 @@ public class ModelReturn implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("return") public Integer getReturn() { return _return; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Name.java index 1c189b6e01d..5460ff8a9b9 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Name.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Name.java @@ -11,6 +11,7 @@ import javax.validation.Valid; **/ import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "Model for testing model name same as property name") public class Name implements Serializable { @@ -29,6 +30,7 @@ public class Name implements Serializable { @ApiModelProperty(required = true, value = "") + @JsonProperty("name") @NotNull public Integer getName() { return name; @@ -46,6 +48,7 @@ public class Name implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("snake_case") public Integer getSnakeCase() { return snakeCase; } @@ -62,6 +65,7 @@ public class Name implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("property") public String getProperty() { return property; } @@ -78,6 +82,7 @@ public class Name implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("123Number") public Integer get123Number() { return _123Number; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/NumberOnly.java index edff615a50d..5f02fd0649a 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/NumberOnly.java @@ -8,6 +8,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class NumberOnly implements Serializable { @@ -23,6 +24,7 @@ public class NumberOnly implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("JustNumber") public BigDecimal getJustNumber() { return justNumber; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Order.java index d7042477807..f7665f15a54 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Order.java @@ -8,6 +8,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Order implements Serializable { @@ -59,6 +60,7 @@ public enum StatusEnum { @ApiModelProperty(value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -75,6 +77,7 @@ public enum StatusEnum { @ApiModelProperty(value = "") + @JsonProperty("petId") public Long getPetId() { return petId; } @@ -91,6 +94,7 @@ public enum StatusEnum { @ApiModelProperty(value = "") + @JsonProperty("quantity") public Integer getQuantity() { return quantity; } @@ -107,6 +111,7 @@ public enum StatusEnum { @ApiModelProperty(value = "") + @JsonProperty("shipDate") public Date getShipDate() { return shipDate; } @@ -124,6 +129,7 @@ public enum StatusEnum { @ApiModelProperty(value = "Order Status") + @JsonProperty("status") public StatusEnum getStatus() { return status; } @@ -140,6 +146,7 @@ public enum StatusEnum { @ApiModelProperty(value = "") + @JsonProperty("complete") public Boolean isComplete() { return complete; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/OuterComposite.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/OuterComposite.java index c038e105892..bfe8211b654 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/OuterComposite.java @@ -8,6 +8,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class OuterComposite implements Serializable { @@ -25,6 +26,7 @@ public class OuterComposite implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("my_number") public BigDecimal getMyNumber() { return myNumber; } @@ -41,6 +43,7 @@ public class OuterComposite implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("my_string") public String getMyString() { return myString; } @@ -57,6 +60,7 @@ public class OuterComposite implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("my_boolean") public Boolean getMyBoolean() { return myBoolean; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Pet.java index 5bad5ba12d6..fc8a6796b79 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Pet.java @@ -11,6 +11,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Pet implements Serializable { @@ -62,6 +63,7 @@ public enum StatusEnum { @ApiModelProperty(value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -78,6 +80,7 @@ public enum StatusEnum { @ApiModelProperty(value = "") + @JsonProperty("category") public Category getCategory() { return category; } @@ -94,6 +97,7 @@ public enum StatusEnum { @ApiModelProperty(example = "doggie", required = true, value = "") + @JsonProperty("name") @NotNull public String getName() { return name; @@ -111,6 +115,7 @@ public enum StatusEnum { @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") @NotNull public List getPhotoUrls() { return photoUrls; @@ -128,6 +133,7 @@ public enum StatusEnum { @ApiModelProperty(value = "") + @JsonProperty("tags") public List getTags() { return tags; } @@ -145,6 +151,7 @@ public enum StatusEnum { @ApiModelProperty(value = "pet status in the store") + @JsonProperty("status") public StatusEnum getStatus() { return status; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ReadOnlyFirst.java index 0617b6904ea..bd4ee7e1cb1 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class ReadOnlyFirst implements Serializable { @@ -23,6 +24,7 @@ public class ReadOnlyFirst implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("bar") public String getBar() { return bar; } @@ -39,6 +41,7 @@ public class ReadOnlyFirst implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("baz") public String getBaz() { return baz; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/SpecialModelName.java index 9afe1f14834..b8144314b82 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/SpecialModelName.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class SpecialModelName implements Serializable { @@ -22,6 +23,7 @@ public class SpecialModelName implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("$special[property.name]") public Long getSpecialPropertyName() { return specialPropertyName; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Tag.java index 35c70dd8bbd..10a7ffc7c57 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Tag.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class Tag implements Serializable { @@ -23,6 +24,7 @@ public class Tag implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -39,6 +41,7 @@ public class Tag implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("name") public String getName() { return name; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/User.java index ad92725cb41..a86f0eae070 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/User.java @@ -7,6 +7,7 @@ import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; public class User implements Serializable { @@ -29,6 +30,7 @@ public class User implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -45,6 +47,7 @@ public class User implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("username") public String getUsername() { return username; } @@ -61,6 +64,7 @@ public class User implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("firstName") public String getFirstName() { return firstName; } @@ -77,6 +81,7 @@ public class User implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("lastName") public String getLastName() { return lastName; } @@ -93,6 +98,7 @@ public class User implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("email") public String getEmail() { return email; } @@ -109,6 +115,7 @@ public class User implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("password") public String getPassword() { return password; } @@ -125,6 +132,7 @@ public class User implements Serializable { @ApiModelProperty(value = "") + @JsonProperty("phone") public String getPhone() { return phone; } @@ -142,6 +150,7 @@ public class User implements Serializable { @ApiModelProperty(value = "User Status") + @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } diff --git a/samples/server/petstore/nancyfx-async/.swagger-codegen-ignore b/samples/server/petstore/nancyfx-async/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/nancyfx-async/.swagger-codegen/VERSION b/samples/server/petstore/nancyfx-async/.swagger-codegen/VERSION new file mode 100644 index 00000000000..f9f7450d135 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/IO.Swagger.sln b/samples/server/petstore/nancyfx-async/IO.Swagger.sln new file mode 100644 index 00000000000..1e40deb1a14 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/IO.Swagger.sln @@ -0,0 +1,25 @@ +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", "{768B8DC6-54EE-4D40-9B20-7857E1D742A4}" +EndProject +Global +GlobalSection(SolutionConfigurationPlatforms) = preSolution +Debug|Any CPU = Debug|Any CPU +Release|Any CPU = Release|Any CPU +EndGlobalSection +GlobalSection(ProjectConfigurationPlatforms) = postSolution +{768B8DC6-54EE-4D40-9B20-7857E1D742A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{768B8DC6-54EE-4D40-9B20-7857E1D742A4}.Debug|Any CPU.Build.0 = Debug|Any CPU +{768B8DC6-54EE-4D40-9B20-7857E1D742A4}.Release|Any CPU.ActiveCfg = Release|Any CPU +{768B8DC6-54EE-4D40-9B20-7857E1D742A4}.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 +{19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.Build.0 = Release|Any CPU +EndGlobalSection +GlobalSection(SolutionProperties) = preSolution +HideSolutionNode = FALSE +EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/IO.Swagger.csproj b/samples/server/petstore/nancyfx-async/src/IO.Swagger/IO.Swagger.csproj new file mode 100644 index 00000000000..e1577197b6f --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/IO.Swagger.csproj @@ -0,0 +1,66 @@ + + + + Debug + AnyCPU + {768B8DC6-54EE-4D40-9B20-7857E1D742A4} + Library + Properties + IO.Swagger.v2 + IO.Swagger + v4.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + bin\Debug\IO.Swagger.XML + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + bin\Release\IO.Swagger.XML + + + + ..\..\packages\Nancy.1.4.3\lib\net40\Nancy.dll + True + + + ..\..\packages\NodaTime.1.3.1\lib\net35-Client\NodaTime.dll + True + + + ..\..\packages\Sharpility.1.2.2\lib\net45\Sharpility.dll + True + + + ..\..\packages\System.Collections.Immutable.1.1.37\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll + True + + + + + + + + + + + + + + + + + + diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/IO.Swagger.nuspec b/samples/server/petstore/nancyfx-async/src/IO.Swagger/IO.Swagger.nuspec new file mode 100644 index 00000000000..889fe96ab03 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/IO.Swagger.nuspec @@ -0,0 +1,14 @@ + + + + IO.Swagger + IO.Swagger + 1.0.0 + swagger-codegen + swagger-codegen + false + NancyFx IO.Swagger API + http://swagger.io/terms/ + http://www.apache.org/licenses/LICENSE-2.0.html + + \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/ApiResponse.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/ApiResponse.cs new file mode 100644 index 00000000000..ebaa3c8d4f1 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/ApiResponse.cs @@ -0,0 +1,185 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Sharpility.Extensions; +using NodaTime; + +namespace IO.Swagger.v2.Models +{ + ///

+ /// Describes the result of uploading an image resource + /// + public sealed class ApiResponse: IEquatable + { + /// + /// Code + /// + public int? Code { get; private set; } + + /// + /// Type + /// + public string Type { get; private set; } + + /// + /// Message + /// + public string Message { get; private set; } + + + /// + /// Empty constructor required by some serializers. + /// Use ApiResponse.Builder() for instance creation instead. + /// + [Obsolete] + public ApiResponse() + { + } + + private ApiResponse(int? Code, string Type, string Message) + { + + this.Code = Code; + + this.Type = Type; + + this.Message = Message; + + } + + /// + /// Returns builder of ApiResponse. + /// + /// ApiResponseBuilder + public static ApiResponseBuilder Builder() + { + return new ApiResponseBuilder(); + } + + /// + /// Returns ApiResponseBuilder with properties set. + /// Use it to change properties. + /// + /// ApiResponseBuilder + public ApiResponseBuilder With() + { + return Builder() + .Code(Code) + .Type(Type) + .Message(Message); + } + + public override string ToString() + { + return this.PropertiesToString(); + } + + public override bool Equals(object obj) + { + return this.EqualsByProperties(obj); + } + + public bool Equals(ApiResponse other) + { + return Equals((object) other); + } + + public override int GetHashCode() + { + return this.PropertiesHash(); + } + + /// + /// Implementation of == operator for (ApiResponse. + /// + /// Compared (ApiResponse + /// Compared (ApiResponse + /// true if compared items are equals, false otherwise + public static bool operator == (ApiResponse left, ApiResponse right) + { + return Equals(left, right); + } + + /// + /// Implementation of != operator for (ApiResponse. + /// + /// Compared (ApiResponse + /// Compared (ApiResponse + /// true if compared items are not equals, false otherwise + public static bool operator != (ApiResponse left, ApiResponse right) + { + return !Equals(left, right); + } + + /// + /// Builder of ApiResponse. + /// + public sealed class ApiResponseBuilder + { + private int? _Code; + private string _Type; + private string _Message; + + internal ApiResponseBuilder() + { + SetupDefaults(); + } + + private void SetupDefaults() + { + } + + /// + /// Sets value for ApiResponse.Code property. + /// + /// Code + public ApiResponseBuilder Code(int? value) + { + _Code = value; + return this; + } + + /// + /// Sets value for ApiResponse.Type property. + /// + /// Type + public ApiResponseBuilder Type(string value) + { + _Type = value; + return this; + } + + /// + /// Sets value for ApiResponse.Message property. + /// + /// Message + public ApiResponseBuilder Message(string value) + { + _Message = value; + return this; + } + + + /// + /// Builds instance of ApiResponse. + /// + /// ApiResponse + public ApiResponse Build() + { + Validate(); + return new ApiResponse( + Code: _Code, + Type: _Type, + Message: _Message + ); + } + + private void Validate() + { + } + } + + + } +} \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Category.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Category.cs new file mode 100644 index 00000000000..bf811614b37 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Category.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Sharpility.Extensions; +using NodaTime; + +namespace IO.Swagger.v2.Models +{ + /// + /// A category for a pet + /// + public sealed class Category: IEquatable + { + /// + /// Id + /// + public long? Id { get; private set; } + + /// + /// Name + /// + public string Name { get; private set; } + + + /// + /// Empty constructor required by some serializers. + /// Use Category.Builder() for instance creation instead. + /// + [Obsolete] + public Category() + { + } + + private Category(long? Id, string Name) + { + + this.Id = Id; + + this.Name = Name; + + } + + /// + /// Returns builder of Category. + /// + /// CategoryBuilder + public static CategoryBuilder Builder() + { + return new CategoryBuilder(); + } + + /// + /// Returns CategoryBuilder with properties set. + /// Use it to change properties. + /// + /// CategoryBuilder + public CategoryBuilder With() + { + return Builder() + .Id(Id) + .Name(Name); + } + + public override string ToString() + { + return this.PropertiesToString(); + } + + public override bool Equals(object obj) + { + return this.EqualsByProperties(obj); + } + + public bool Equals(Category other) + { + return Equals((object) other); + } + + public override int GetHashCode() + { + return this.PropertiesHash(); + } + + /// + /// Implementation of == operator for (Category. + /// + /// Compared (Category + /// Compared (Category + /// true if compared items are equals, false otherwise + public static bool operator == (Category left, Category right) + { + return Equals(left, right); + } + + /// + /// Implementation of != operator for (Category. + /// + /// Compared (Category + /// Compared (Category + /// true if compared items are not equals, false otherwise + public static bool operator != (Category left, Category right) + { + return !Equals(left, right); + } + + /// + /// Builder of Category. + /// + public sealed class CategoryBuilder + { + private long? _Id; + private string _Name; + + internal CategoryBuilder() + { + SetupDefaults(); + } + + private void SetupDefaults() + { + } + + /// + /// Sets value for Category.Id property. + /// + /// Id + public CategoryBuilder Id(long? value) + { + _Id = value; + return this; + } + + /// + /// Sets value for Category.Name property. + /// + /// Name + public CategoryBuilder Name(string value) + { + _Name = value; + return this; + } + + + /// + /// Builds instance of Category. + /// + /// Category + public Category Build() + { + Validate(); + return new Category( + Id: _Id, + Name: _Name + ); + } + + private void Validate() + { + } + } + + + } +} \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Order.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Order.cs new file mode 100644 index 00000000000..0495a36f138 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Order.cs @@ -0,0 +1,247 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Sharpility.Extensions; +using NodaTime; + +namespace IO.Swagger.v2.Models +{ + /// + /// An order for a pets from the pet store + /// + public sealed class Order: IEquatable + { + /// + /// Id + /// + public long? Id { get; private set; } + + /// + /// PetId + /// + public long? PetId { get; private set; } + + /// + /// Quantity + /// + public int? Quantity { get; private set; } + + /// + /// ShipDate + /// + public ZonedDateTime? ShipDate { get; private set; } + + /// + /// Order Status + /// + public StatusEnum? Status { get; private set; } + + /// + /// Complete + /// + public bool? Complete { get; private set; } + + + /// + /// Empty constructor required by some serializers. + /// Use Order.Builder() for instance creation instead. + /// + [Obsolete] + public Order() + { + } + + private Order(long? Id, long? PetId, int? Quantity, ZonedDateTime? ShipDate, StatusEnum? Status, bool? Complete) + { + + this.Id = Id; + + this.PetId = PetId; + + this.Quantity = Quantity; + + this.ShipDate = ShipDate; + + this.Status = Status; + + this.Complete = Complete; + + } + + /// + /// Returns builder of Order. + /// + /// OrderBuilder + public static OrderBuilder Builder() + { + return new OrderBuilder(); + } + + /// + /// Returns OrderBuilder with properties set. + /// Use it to change properties. + /// + /// OrderBuilder + public OrderBuilder With() + { + return Builder() + .Id(Id) + .PetId(PetId) + .Quantity(Quantity) + .ShipDate(ShipDate) + .Status(Status) + .Complete(Complete); + } + + public override string ToString() + { + return this.PropertiesToString(); + } + + public override bool Equals(object obj) + { + return this.EqualsByProperties(obj); + } + + public bool Equals(Order other) + { + return Equals((object) other); + } + + public override int GetHashCode() + { + return this.PropertiesHash(); + } + + /// + /// Implementation of == operator for (Order. + /// + /// Compared (Order + /// Compared (Order + /// true if compared items are equals, false otherwise + public static bool operator == (Order left, Order right) + { + return Equals(left, right); + } + + /// + /// Implementation of != operator for (Order. + /// + /// Compared (Order + /// Compared (Order + /// true if compared items are not equals, false otherwise + public static bool operator != (Order left, Order right) + { + return !Equals(left, right); + } + + /// + /// Builder of Order. + /// + public sealed class OrderBuilder + { + private long? _Id; + private long? _PetId; + private int? _Quantity; + private ZonedDateTime? _ShipDate; + private StatusEnum? _Status; + private bool? _Complete; + + internal OrderBuilder() + { + SetupDefaults(); + } + + private void SetupDefaults() + { + _Complete = false; + } + + /// + /// Sets value for Order.Id property. + /// + /// Id + public OrderBuilder Id(long? value) + { + _Id = value; + return this; + } + + /// + /// Sets value for Order.PetId property. + /// + /// PetId + public OrderBuilder PetId(long? value) + { + _PetId = value; + return this; + } + + /// + /// Sets value for Order.Quantity property. + /// + /// Quantity + public OrderBuilder Quantity(int? value) + { + _Quantity = value; + return this; + } + + /// + /// Sets value for Order.ShipDate property. + /// + /// ShipDate + public OrderBuilder ShipDate(ZonedDateTime? value) + { + _ShipDate = value; + return this; + } + + /// + /// Sets value for Order.Status property. + /// + /// Order Status + public OrderBuilder Status(StatusEnum? value) + { + _Status = value; + return this; + } + + /// + /// Sets value for Order.Complete property. + /// + /// Complete + public OrderBuilder Complete(bool? value) + { + _Complete = value; + return this; + } + + + /// + /// Builds instance of Order. + /// + /// Order + public Order Build() + { + Validate(); + return new Order( + Id: _Id, + PetId: _PetId, + Quantity: _Quantity, + ShipDate: _ShipDate, + Status: _Status, + Complete: _Complete + ); + } + + private void Validate() + { + } + } + + + public enum StatusEnum { Placed, Approved, Delivered }; + } +} \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Pet.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Pet.cs new file mode 100644 index 00000000000..f945a0fdd78 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Pet.cs @@ -0,0 +1,254 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Sharpility.Extensions; +using NodaTime; + +namespace IO.Swagger.v2.Models +{ + /// + /// A pet for sale in the pet store + /// + public sealed class Pet: IEquatable + { + /// + /// Id + /// + public long? Id { get; private set; } + + /// + /// Category + /// + public Category Category { get; private set; } + + /// + /// Name + /// + public string Name { get; private set; } + + /// + /// PhotoUrls + /// + public List PhotoUrls { get; private set; } + + /// + /// Tags + /// + public List Tags { get; private set; } + + /// + /// pet status in the store + /// + public StatusEnum? Status { get; private set; } + + + /// + /// Empty constructor required by some serializers. + /// Use Pet.Builder() for instance creation instead. + /// + [Obsolete] + public Pet() + { + } + + private Pet(long? Id, Category Category, string Name, List PhotoUrls, List Tags, StatusEnum? Status) + { + + this.Id = Id; + + this.Category = Category; + + this.Name = Name; + + this.PhotoUrls = PhotoUrls; + + this.Tags = Tags; + + this.Status = Status; + + } + + /// + /// Returns builder of Pet. + /// + /// PetBuilder + public static PetBuilder Builder() + { + return new PetBuilder(); + } + + /// + /// Returns PetBuilder with properties set. + /// Use it to change properties. + /// + /// PetBuilder + public PetBuilder With() + { + return Builder() + .Id(Id) + .Category(Category) + .Name(Name) + .PhotoUrls(PhotoUrls) + .Tags(Tags) + .Status(Status); + } + + public override string ToString() + { + return this.PropertiesToString(); + } + + public override bool Equals(object obj) + { + return this.EqualsByProperties(obj); + } + + public bool Equals(Pet other) + { + return Equals((object) other); + } + + public override int GetHashCode() + { + return this.PropertiesHash(); + } + + /// + /// Implementation of == operator for (Pet. + /// + /// Compared (Pet + /// Compared (Pet + /// true if compared items are equals, false otherwise + public static bool operator == (Pet left, Pet right) + { + return Equals(left, right); + } + + /// + /// Implementation of != operator for (Pet. + /// + /// Compared (Pet + /// Compared (Pet + /// true if compared items are not equals, false otherwise + public static bool operator != (Pet left, Pet right) + { + return !Equals(left, right); + } + + /// + /// Builder of Pet. + /// + public sealed class PetBuilder + { + private long? _Id; + private Category _Category; + private string _Name; + private List _PhotoUrls; + private List _Tags; + private StatusEnum? _Status; + + internal PetBuilder() + { + SetupDefaults(); + } + + private void SetupDefaults() + { + } + + /// + /// Sets value for Pet.Id property. + /// + /// Id + public PetBuilder Id(long? value) + { + _Id = value; + return this; + } + + /// + /// Sets value for Pet.Category property. + /// + /// Category + public PetBuilder Category(Category value) + { + _Category = value; + return this; + } + + /// + /// Sets value for Pet.Name property. + /// + /// Name + public PetBuilder Name(string value) + { + _Name = value; + return this; + } + + /// + /// Sets value for Pet.PhotoUrls property. + /// + /// PhotoUrls + public PetBuilder PhotoUrls(List value) + { + _PhotoUrls = value; + return this; + } + + /// + /// Sets value for Pet.Tags property. + /// + /// Tags + public PetBuilder Tags(List value) + { + _Tags = value; + return this; + } + + /// + /// Sets value for Pet.Status property. + /// + /// pet status in the store + public PetBuilder Status(StatusEnum? value) + { + _Status = value; + return this; + } + + + /// + /// Builds instance of Pet. + /// + /// Pet + public Pet Build() + { + Validate(); + return new Pet( + Id: _Id, + Category: _Category, + Name: _Name, + PhotoUrls: _PhotoUrls, + Tags: _Tags, + Status: _Status + ); + } + + private void Validate() + { + if (_Name == null) + { + throw new ArgumentException("Name is a required property for Pet and cannot be null"); + } + if (_PhotoUrls == null) + { + throw new ArgumentException("PhotoUrls is a required property for Pet and cannot be null"); + } + } + } + + + public enum StatusEnum { Available, Pending, Sold }; + } +} \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Tag.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Tag.cs new file mode 100644 index 00000000000..02d1e40f1ec --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Tag.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Sharpility.Extensions; +using NodaTime; + +namespace IO.Swagger.v2.Models +{ + /// + /// A tag for a pet + /// + public sealed class Tag: IEquatable + { + /// + /// Id + /// + public long? Id { get; private set; } + + /// + /// Name + /// + public string Name { get; private set; } + + + /// + /// Empty constructor required by some serializers. + /// Use Tag.Builder() for instance creation instead. + /// + [Obsolete] + public Tag() + { + } + + private Tag(long? Id, string Name) + { + + this.Id = Id; + + this.Name = Name; + + } + + /// + /// Returns builder of Tag. + /// + /// TagBuilder + public static TagBuilder Builder() + { + return new TagBuilder(); + } + + /// + /// Returns TagBuilder with properties set. + /// Use it to change properties. + /// + /// TagBuilder + public TagBuilder With() + { + return Builder() + .Id(Id) + .Name(Name); + } + + public override string ToString() + { + return this.PropertiesToString(); + } + + public override bool Equals(object obj) + { + return this.EqualsByProperties(obj); + } + + public bool Equals(Tag other) + { + return Equals((object) other); + } + + public override int GetHashCode() + { + return this.PropertiesHash(); + } + + /// + /// Implementation of == operator for (Tag. + /// + /// Compared (Tag + /// Compared (Tag + /// true if compared items are equals, false otherwise + public static bool operator == (Tag left, Tag right) + { + return Equals(left, right); + } + + /// + /// Implementation of != operator for (Tag. + /// + /// Compared (Tag + /// Compared (Tag + /// true if compared items are not equals, false otherwise + public static bool operator != (Tag left, Tag right) + { + return !Equals(left, right); + } + + /// + /// Builder of Tag. + /// + public sealed class TagBuilder + { + private long? _Id; + private string _Name; + + internal TagBuilder() + { + SetupDefaults(); + } + + private void SetupDefaults() + { + } + + /// + /// Sets value for Tag.Id property. + /// + /// Id + public TagBuilder Id(long? value) + { + _Id = value; + return this; + } + + /// + /// Sets value for Tag.Name property. + /// + /// Name + public TagBuilder Name(string value) + { + _Name = value; + return this; + } + + + /// + /// Builds instance of Tag. + /// + /// Tag + public Tag Build() + { + Validate(); + return new Tag( + Id: _Id, + Name: _Name + ); + } + + private void Validate() + { + } + } + + + } +} \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/User.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/User.cs new file mode 100644 index 00000000000..99f401750df --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/User.cs @@ -0,0 +1,285 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Sharpility.Extensions; +using NodaTime; + +namespace IO.Swagger.v2.Models +{ + /// + /// A User who is purchasing from the pet store + /// + public sealed class User: IEquatable + { + /// + /// Id + /// + public long? Id { get; private set; } + + /// + /// Username + /// + public string Username { get; private set; } + + /// + /// FirstName + /// + public string FirstName { get; private set; } + + /// + /// LastName + /// + public string LastName { get; private set; } + + /// + /// Email + /// + public string Email { get; private set; } + + /// + /// Password + /// + public string Password { get; private set; } + + /// + /// Phone + /// + public string Phone { get; private set; } + + /// + /// User Status + /// + public int? UserStatus { get; private set; } + + + /// + /// Empty constructor required by some serializers. + /// Use User.Builder() for instance creation instead. + /// + [Obsolete] + public User() + { + } + + private User(long? Id, string Username, string FirstName, string LastName, string Email, string Password, string Phone, int? 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; + + } + + /// + /// Returns builder of User. + /// + /// UserBuilder + public static UserBuilder Builder() + { + return new UserBuilder(); + } + + /// + /// Returns UserBuilder with properties set. + /// Use it to change properties. + /// + /// UserBuilder + public UserBuilder With() + { + return Builder() + .Id(Id) + .Username(Username) + .FirstName(FirstName) + .LastName(LastName) + .Email(Email) + .Password(Password) + .Phone(Phone) + .UserStatus(UserStatus); + } + + public override string ToString() + { + return this.PropertiesToString(); + } + + public override bool Equals(object obj) + { + return this.EqualsByProperties(obj); + } + + public bool Equals(User other) + { + return Equals((object) other); + } + + public override int GetHashCode() + { + return this.PropertiesHash(); + } + + /// + /// Implementation of == operator for (User. + /// + /// Compared (User + /// Compared (User + /// true if compared items are equals, false otherwise + public static bool operator == (User left, User right) + { + return Equals(left, right); + } + + /// + /// Implementation of != operator for (User. + /// + /// Compared (User + /// Compared (User + /// true if compared items are not equals, false otherwise + public static bool operator != (User left, User right) + { + return !Equals(left, right); + } + + /// + /// Builder of User. + /// + public sealed class UserBuilder + { + private long? _Id; + private string _Username; + private string _FirstName; + private string _LastName; + private string _Email; + private string _Password; + private string _Phone; + private int? _UserStatus; + + internal UserBuilder() + { + SetupDefaults(); + } + + private void SetupDefaults() + { + } + + /// + /// Sets value for User.Id property. + /// + /// Id + public UserBuilder Id(long? value) + { + _Id = value; + return this; + } + + /// + /// Sets value for User.Username property. + /// + /// Username + public UserBuilder Username(string value) + { + _Username = value; + return this; + } + + /// + /// Sets value for User.FirstName property. + /// + /// FirstName + public UserBuilder FirstName(string value) + { + _FirstName = value; + return this; + } + + /// + /// Sets value for User.LastName property. + /// + /// LastName + public UserBuilder LastName(string value) + { + _LastName = value; + return this; + } + + /// + /// Sets value for User.Email property. + /// + /// Email + public UserBuilder Email(string value) + { + _Email = value; + return this; + } + + /// + /// Sets value for User.Password property. + /// + /// Password + public UserBuilder Password(string value) + { + _Password = value; + return this; + } + + /// + /// Sets value for User.Phone property. + /// + /// Phone + public UserBuilder Phone(string value) + { + _Phone = value; + return this; + } + + /// + /// Sets value for User.UserStatus property. + /// + /// User Status + public UserBuilder UserStatus(int? value) + { + _UserStatus = value; + return this; + } + + + /// + /// Builds instance of User. + /// + /// User + public User Build() + { + Validate(); + return new User( + Id: _Id, + Username: _Username, + FirstName: _FirstName, + LastName: _LastName, + Email: _Email, + Password: _Password, + Phone: _Phone, + UserStatus: _UserStatus + ); + } + + private void Validate() + { + } + } + + + } +} \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs new file mode 100644 index 00000000000..0d4cf8616c7 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs @@ -0,0 +1,247 @@ +using System; +using Nancy; +using Nancy.ModelBinding; +using System.Collections.Generic; +using Sharpility.Base; +using IO.Swagger.v2.Models; +using IO.Swagger.v2.Utils; +using NodaTime; +using System.Threading.Tasks; + +namespace IO.Swagger.v2.Modules +{ + /// + /// Status values that need to be considered for filter + /// + public enum FindPetsByStatusStatusEnum + { + available, + pending, + sold + }; + + + /// + /// Module processing requests of Pet domain. + /// + public sealed class PetModule : NancyModule + { + /// + /// Sets up HTTP methods mappings. + /// + /// Service handling requests + public PetModule(PetService service) : base("/v2") + { + Post["/pet", true] = async (parameters, ct) => + { + var body = this.Bind(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'AddPet'"); + + await service.AddPet(Context, body); + return new Response { ContentType = "application/xml"}; + }; + + Delete["/pet/{petId}", true] = async (parameters, ct) => + { + var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); + var apiKey = Parameters.ValueOf(parameters, Context.Request, "apiKey", ParameterType.Header); + Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'DeletePet'"); + + await service.DeletePet(Context, petId, apiKey); + return new Response { ContentType = "application/xml"}; + }; + + Get["/pet/findByStatus", true] = async (parameters, ct) => + { + var status = Parameters.ValueOf(parameters, Context.Request, "status", ParameterType.Query); + Preconditions.IsNotNull(status, "Required parameter: 'status' is missing at 'FindPetsByStatus'"); + + return await service.FindPetsByStatus(Context, status).ToArray(); + }; + + Get["/pet/findByTags", true] = async (parameters, ct) => + { + var tags = Parameters.ValueOf>(parameters, Context.Request, "tags", ParameterType.Query); + Preconditions.IsNotNull(tags, "Required parameter: 'tags' is missing at 'FindPetsByTags'"); + + return await service.FindPetsByTags(Context, tags).ToArray(); + }; + + Get["/pet/{petId}", true] = async (parameters, ct) => + { + var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); + Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'GetPetById'"); + + return await service.GetPetById(Context, petId); + }; + + Put["/pet", true] = async (parameters, ct) => + { + var body = this.Bind(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'UpdatePet'"); + + await service.UpdatePet(Context, body); + return new Response { ContentType = "application/xml"}; + }; + + Post["/pet/{petId}", true] = async (parameters, ct) => + { + var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); + var name = Parameters.ValueOf(parameters, Context.Request, "name", ParameterType.Undefined); + var status = Parameters.ValueOf(parameters, Context.Request, "status", ParameterType.Undefined); + Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'UpdatePetWithForm'"); + + await service.UpdatePetWithForm(Context, petId, name, status); + return new Response { ContentType = "application/xml"}; + }; + + Post["/pet/{petId}/uploadImage", true] = async (parameters, ct) => + { + var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); + var additionalMetadata = Parameters.ValueOf(parameters, Context.Request, "additionalMetadata", ParameterType.Undefined); + var file = Parameters.ValueOf(parameters, Context.Request, "file", ParameterType.Undefined); + Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'UploadFile'"); + + return await service.UploadFile(Context, petId, additionalMetadata, file); + }; + } + } + + /// + /// Service handling Pet requests. + /// + public interface PetService + { + /// + /// + /// + /// Context of request + /// Pet object that needs to be added to the store + /// + Task AddPet(NancyContext context, Pet body); + + /// + /// + /// + /// Context of request + /// Pet id to delete + /// (optional) + /// + Task DeletePet(NancyContext context, long? petId, string apiKey); + + /// + /// Multiple status values can be provided with comma separated strings + /// + /// Context of request + /// Status values that need to be considered for filter + /// List<Pet> + Task> FindPetsByStatus(NancyContext context, FindPetsByStatusStatusEnum? status); + + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Context of request + /// Tags to filter by + /// List<Pet> + Task> FindPetsByTags(NancyContext context, List tags); + + /// + /// Returns a single pet + /// + /// Context of request + /// ID of pet to return + /// Pet + Task GetPetById(NancyContext context, long? petId); + + /// + /// + /// + /// Context of request + /// Pet object that needs to be added to the store + /// + Task UpdatePet(NancyContext context, Pet body); + + /// + /// + /// + /// Context of request + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// + Task UpdatePetWithForm(NancyContext context, long? petId, string name, string status); + + /// + /// + /// + /// Context of request + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// ApiResponse + Task UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file); + } + + /// + /// Abstraction of PetService. + /// + public abstract class AbstractPetService: PetService + { + public virtual Task AddPet(NancyContext context, Pet body) + { + return AddPet(body); + } + + public virtual Task DeletePet(NancyContext context, long? petId, string apiKey) + { + return DeletePet(petId, apiKey); + } + + public virtual Task> FindPetsByStatus(NancyContext context, FindPetsByStatusStatusEnum? status) + { + return FindPetsByStatus(status); + } + + public virtual Task> FindPetsByTags(NancyContext context, List tags) + { + return FindPetsByTags(tags); + } + + public virtual Task GetPetById(NancyContext context, long? petId) + { + return GetPetById(petId); + } + + public virtual Task UpdatePet(NancyContext context, Pet body) + { + return UpdatePet(body); + } + + public virtual Task UpdatePetWithForm(NancyContext context, long? petId, string name, string status) + { + return UpdatePetWithForm(petId, name, status); + } + + public virtual Task UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file) + { + return UploadFile(petId, additionalMetadata, file); + } + + protected abstract Task AddPet(Pet body); + + protected abstract Task DeletePet(long? petId, string apiKey); + + protected abstract Task> FindPetsByStatus(FindPetsByStatusStatusEnum? status); + + protected abstract Task> FindPetsByTags(List tags); + + protected abstract Task GetPetById(long? petId); + + protected abstract Task UpdatePet(Pet body); + + protected abstract Task UpdatePetWithForm(long? petId, string name, string status); + + protected abstract Task UploadFile(long? petId, string additionalMetadata, System.IO.Stream file); + } + +} diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/StoreModule.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/StoreModule.cs new file mode 100644 index 00000000000..30c46234256 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/StoreModule.cs @@ -0,0 +1,129 @@ +using System; +using Nancy; +using Nancy.ModelBinding; +using System.Collections.Generic; +using Sharpility.Base; +using IO.Swagger.v2.Models; +using IO.Swagger.v2.Utils; +using NodaTime; +using System.Threading.Tasks; + +namespace IO.Swagger.v2.Modules +{ + + /// + /// Module processing requests of Store domain. + /// + public sealed class StoreModule : NancyModule + { + /// + /// Sets up HTTP methods mappings. + /// + /// Service handling requests + public StoreModule(StoreService service) : base("/v2") + { + Delete["/store/order/{orderId}", true] = async (parameters, ct) => + { + var orderId = Parameters.ValueOf(parameters, Context.Request, "orderId", ParameterType.Path); + Preconditions.IsNotNull(orderId, "Required parameter: 'orderId' is missing at 'DeleteOrder'"); + + await service.DeleteOrder(Context, orderId); + return new Response { ContentType = "application/xml"}; + }; + + Get["/store/inventory", true] = async (parameters, ct) => + { + + return await service.GetInventory(Context); + }; + + Get["/store/order/{orderId}", true] = async (parameters, ct) => + { + var orderId = Parameters.ValueOf(parameters, Context.Request, "orderId", ParameterType.Path); + Preconditions.IsNotNull(orderId, "Required parameter: 'orderId' is missing at 'GetOrderById'"); + + return await service.GetOrderById(Context, orderId); + }; + + Post["/store/order", true] = async (parameters, ct) => + { + var body = this.Bind(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'PlaceOrder'"); + + return await service.PlaceOrder(Context, body); + }; + } + } + + /// + /// Service handling Store requests. + /// + public interface StoreService + { + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Context of request + /// ID of the order that needs to be deleted + /// + Task DeleteOrder(NancyContext context, string orderId); + + /// + /// Returns a map of status codes to quantities + /// + /// Context of request + /// Dictionary<string, int?> + Task> GetInventory(NancyContext context); + + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Context of request + /// ID of pet that needs to be fetched + /// Order + Task GetOrderById(NancyContext context, long? orderId); + + /// + /// + /// + /// Context of request + /// order placed for purchasing the pet + /// Order + Task PlaceOrder(NancyContext context, Order body); + } + + /// + /// Abstraction of StoreService. + /// + public abstract class AbstractStoreService: StoreService + { + public virtual Task DeleteOrder(NancyContext context, string orderId) + { + return DeleteOrder(orderId); + } + + public virtual Task> GetInventory(NancyContext context) + { + return GetInventory(); + } + + public virtual Task GetOrderById(NancyContext context, long? orderId) + { + return GetOrderById(orderId); + } + + public virtual Task PlaceOrder(NancyContext context, Order body) + { + return PlaceOrder(body); + } + + protected abstract Task DeleteOrder(string orderId); + + protected abstract Task> GetInventory(); + + protected abstract Task GetOrderById(long? orderId); + + protected abstract Task PlaceOrder(Order body); + } + +} diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/UserModule.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/UserModule.cs new file mode 100644 index 00000000000..4faf9e38dbd --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/UserModule.cs @@ -0,0 +1,234 @@ +using System; +using Nancy; +using Nancy.ModelBinding; +using System.Collections.Generic; +using Sharpility.Base; +using IO.Swagger.v2.Models; +using IO.Swagger.v2.Utils; +using NodaTime; +using System.Threading.Tasks; + +namespace IO.Swagger.v2.Modules +{ + + /// + /// Module processing requests of User domain. + /// + public sealed class UserModule : NancyModule + { + /// + /// Sets up HTTP methods mappings. + /// + /// Service handling requests + public UserModule(UserService service) : base("/v2") + { + Post["/user", true] = async (parameters, ct) => + { + var body = this.Bind(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUser'"); + + await service.CreateUser(Context, body); + return new Response { ContentType = "application/xml"}; + }; + + Post["/user/createWithArray", true] = async (parameters, ct) => + { + var body = this.Bind>(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUsersWithArrayInput'"); + + await service.CreateUsersWithArrayInput(Context, body); + return new Response { ContentType = "application/xml"}; + }; + + Post["/user/createWithList", true] = async (parameters, ct) => + { + var body = this.Bind>(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUsersWithListInput'"); + + await service.CreateUsersWithListInput(Context, body); + return new Response { ContentType = "application/xml"}; + }; + + Delete["/user/{username}", true] = async (parameters, ct) => + { + var username = Parameters.ValueOf(parameters, Context.Request, "username", ParameterType.Path); + Preconditions.IsNotNull(username, "Required parameter: 'username' is missing at 'DeleteUser'"); + + await service.DeleteUser(Context, username); + return new Response { ContentType = "application/xml"}; + }; + + Get["/user/{username}", true] = async (parameters, ct) => + { + var username = Parameters.ValueOf(parameters, Context.Request, "username", ParameterType.Path); + Preconditions.IsNotNull(username, "Required parameter: 'username' is missing at 'GetUserByName'"); + + return await service.GetUserByName(Context, username); + }; + + Get["/user/login", true] = async (parameters, ct) => + { + var username = Parameters.ValueOf(parameters, Context.Request, "username", ParameterType.Query); + var password = Parameters.ValueOf(parameters, Context.Request, "password", ParameterType.Query); + Preconditions.IsNotNull(username, "Required parameter: 'username' is missing at 'LoginUser'"); + + Preconditions.IsNotNull(password, "Required parameter: 'password' is missing at 'LoginUser'"); + + return await service.LoginUser(Context, username, password); + }; + + Get["/user/logout", true] = async (parameters, ct) => + { + + await service.LogoutUser(Context); + return new Response { ContentType = "application/xml"}; + }; + + Put["/user/{username}", true] = async (parameters, ct) => + { + var username = Parameters.ValueOf(parameters, Context.Request, "username", ParameterType.Path); + var body = this.Bind(); + Preconditions.IsNotNull(username, "Required parameter: 'username' is missing at 'UpdateUser'"); + + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'UpdateUser'"); + + await service.UpdateUser(Context, username, body); + return new Response { ContentType = "application/xml"}; + }; + } + } + + /// + /// Service handling User requests. + /// + public interface UserService + { + /// + /// This can only be done by the logged in user. + /// + /// Context of request + /// Created user object + /// + Task CreateUser(NancyContext context, User body); + + /// + /// + /// + /// Context of request + /// List of user object + /// + Task CreateUsersWithArrayInput(NancyContext context, List body); + + /// + /// + /// + /// Context of request + /// List of user object + /// + Task CreateUsersWithListInput(NancyContext context, List body); + + /// + /// This can only be done by the logged in user. + /// + /// Context of request + /// The name that needs to be deleted + /// + Task DeleteUser(NancyContext context, string username); + + /// + /// + /// + /// Context of request + /// The name that needs to be fetched. Use user1 for testing. + /// User + Task GetUserByName(NancyContext context, string username); + + /// + /// + /// + /// Context of request + /// The user name for login + /// The password for login in clear text + /// string + Task LoginUser(NancyContext context, string username, string password); + + /// + /// + /// + /// Context of request + /// + Task LogoutUser(NancyContext context); + + /// + /// This can only be done by the logged in user. + /// + /// Context of request + /// name that need to be deleted + /// Updated user object + /// + Task UpdateUser(NancyContext context, string username, User body); + } + + /// + /// Abstraction of UserService. + /// + public abstract class AbstractUserService: UserService + { + public virtual Task CreateUser(NancyContext context, User body) + { + return CreateUser(body); + } + + public virtual Task CreateUsersWithArrayInput(NancyContext context, List body) + { + return CreateUsersWithArrayInput(body); + } + + public virtual Task CreateUsersWithListInput(NancyContext context, List body) + { + return CreateUsersWithListInput(body); + } + + public virtual Task DeleteUser(NancyContext context, string username) + { + return DeleteUser(username); + } + + public virtual Task GetUserByName(NancyContext context, string username) + { + return GetUserByName(username); + } + + public virtual Task LoginUser(NancyContext context, string username, string password) + { + return LoginUser(username, password); + } + + public virtual Task LogoutUser(NancyContext context) + { + return LogoutUser(); + } + + public virtual Task UpdateUser(NancyContext context, string username, User body) + { + return UpdateUser(username, body); + } + + protected abstract Task CreateUser(User body); + + protected abstract Task CreateUsersWithArrayInput(List body); + + protected abstract Task CreateUsersWithListInput(List body); + + protected abstract Task DeleteUser(string username); + + protected abstract Task GetUserByName(string username); + + protected abstract Task LoginUser(string username, string password); + + protected abstract Task LogoutUser(); + + protected abstract Task UpdateUser(string username, User body); + } + +} diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Utils/Parameters.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Utils/Parameters.cs new file mode 100644 index 00000000000..6175758fd9a --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Utils/Parameters.cs @@ -0,0 +1,443 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Nancy; +using NodaTime; +using NodaTime.Text; +using Sharpility.Base; +using Sharpility.Extensions; +using Sharpility.Util; + +namespace IO.Swagger.v2.Utils +{ + internal static class Parameters + { + private static readonly IDictionary> Parsers = CreateParsers(); + + internal static TValue ValueOf(dynamic parameters, Request request, string name, ParameterType parameterType) + { + var valueType = typeof(TValue); + var valueUnderlyingType = Nullable.GetUnderlyingType(valueType); + var isNullable = default(TValue) == null; + string value = RawValueOf(parameters, request, name, parameterType); + Preconditions.Evaluate(!string.IsNullOrEmpty(value) || isNullable, string.Format("Required parameter: '{0}' is missing", name)); + if (value == null && isNullable) + { + return default(TValue); + } + if (valueType.IsEnum || (valueUnderlyingType != null && valueUnderlyingType.IsEnum)) + { + return EnumValueOf(name, value); + } + return ValueOf(parameters, name, value, valueType, request, parameterType); + } + + private static string RawValueOf(dynamic parameters, Request request, string name, ParameterType parameterType) + { + try + { + switch (parameterType) + { + case ParameterType.Query: + string querValue = request.Query[name]; + return querValue; + case ParameterType.Path: + string pathValue = parameters[name]; + return pathValue; + case ParameterType.Header: + var headerValue = request.Headers[name]; + return headerValue != null ? string.Join(",", headerValue) : null; + } + } + catch (Exception e) + { + throw new InvalidOperationException(string.Format("Could not obtain value of '{0}' parameter", name), e); + } + throw new InvalidOperationException(string.Format("Parameter with type: {0} is not supported", parameterType)); + } + + private static TValue EnumValueOf(string name, string value) + { + var valueType = typeof(TValue); + var enumType = valueType.IsEnum ? valueType : Nullable.GetUnderlyingType(valueType); + Preconditions.IsNotNull(enumType, () => new InvalidOperationException( + string.Format("Could not parse parameter: '{0}' to enum. Type {1} is not enum", name, valueType))); + var values = Enum.GetValues(enumType); + foreach (var entry in values) + { + if (entry.ToString().EqualsIgnoreCases(value) + || ((int)entry).ToString().EqualsIgnoreCases(value)) + { + return (TValue)entry; + } + } + throw new ArgumentException(string.Format("Parameter: '{0}' value: '{1}' is not supported. Expected one of: {2}", + name, value, Strings.ToString(values))); + } + + private static TValue ValueOf(dynamic parameters, string name, string value, Type valueType, Request request, ParameterType parameterType) + { + var parser = Parsers.GetIfPresent(valueType); + if (parser != null) + { + return ParseValueUsing(name, value, valueType, parser); + } + if (parameterType == ParameterType.Path) + { + return DynamicValueOf(parameters, name); + } + if (parameterType == ParameterType.Query) + { + return DynamicValueOf(request.Query, name); + } + throw new InvalidOperationException(string.Format("Could not get value for {0} with type {1}", name, valueType)); + } + + private static TValue ParseValueUsing(string name, string value, Type valueType, Func parser) + { + var result = parser(Parameter.Of(name, value)); + try + { + return (TValue)result; + } + catch (InvalidCastException) + { + throw new InvalidOperationException( + string.Format("Could not parse parameter: '{0}' with value: '{1}'. " + + "Received: '{2}', expected: '{3}'.", + name, value, result.GetType(), valueType)); + } + } + + private static TValue DynamicValueOf(dynamic parameters, string name) + { + string value = parameters[name]; + try + { + TValue result = parameters[name]; + return result; + } + catch (InvalidCastException) + { + throw new InvalidOperationException(Strings.Format("Parameter: '{0}' value: '{1}' could not be parsed. " + + "Expected type: '{2}' is not supported", + name, value, typeof(TValue))); + } + catch (Exception e) + { + throw new InvalidOperationException(string.Format("Could not get '{0}' value of '{1}' type dynamicly", + name, typeof(TValue)), e); + } + } + + private static IDictionary> CreateParsers() + { + var parsers = ImmutableDictionary.CreateBuilder>(); + parsers.Put(typeof(string), value => value.Value); + parsers.Put(typeof(bool), SafeParse(bool.Parse)); + parsers.Put(typeof(bool?), SafeParse(bool.Parse)); + parsers.Put(typeof(byte), SafeParse(byte.Parse)); + parsers.Put(typeof(sbyte?), SafeParse(sbyte.Parse)); + parsers.Put(typeof(short), SafeParse(short.Parse)); + parsers.Put(typeof(short?), SafeParse(short.Parse)); + parsers.Put(typeof(ushort), SafeParse(ushort.Parse)); + parsers.Put(typeof(ushort?), SafeParse(ushort.Parse)); + parsers.Put(typeof(int), SafeParse(int.Parse)); + parsers.Put(typeof(int?), SafeParse(int.Parse)); + parsers.Put(typeof(uint), SafeParse(uint.Parse)); + parsers.Put(typeof(uint?), SafeParse(uint.Parse)); + parsers.Put(typeof(long), SafeParse(long.Parse)); + parsers.Put(typeof(long?), SafeParse(long.Parse)); + parsers.Put(typeof(ulong), SafeParse(ulong.Parse)); + parsers.Put(typeof(ulong?), SafeParse(ulong.Parse)); + parsers.Put(typeof(float), SafeParse(float.Parse)); + parsers.Put(typeof(float?), SafeParse(float.Parse)); + parsers.Put(typeof(double), SafeParse(double.Parse)); + parsers.Put(typeof(double?), SafeParse(double.Parse)); + parsers.Put(typeof(decimal), SafeParse(decimal.Parse)); + parsers.Put(typeof(decimal?), SafeParse(decimal.Parse)); + parsers.Put(typeof(DateTime), SafeParse(DateTime.Parse)); + parsers.Put(typeof(DateTime?), SafeParse(DateTime.Parse)); + parsers.Put(typeof(TimeSpan), SafeParse(TimeSpan.Parse)); + parsers.Put(typeof(TimeSpan?), SafeParse(TimeSpan.Parse)); + parsers.Put(typeof(ZonedDateTime), SafeParse(ParseZonedDateTime)); + parsers.Put(typeof(ZonedDateTime?), SafeParse(ParseZonedDateTime)); + parsers.Put(typeof(LocalTime), SafeParse(ParseLocalTime)); + parsers.Put(typeof(LocalTime?), SafeParse(ParseLocalTime)); + + parsers.Put(typeof(IEnumerable), ImmutableListParse(value => value)); + parsers.Put(typeof(ICollection), ImmutableListParse(value => value)); + parsers.Put(typeof(IList), ImmutableListParse(value => value)); + parsers.Put(typeof(List), ListParse(value => value)); + parsers.Put(typeof(ISet), ImmutableListParse(value => value)); + parsers.Put(typeof(HashSet), SetParse(value => value)); + + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(bool.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(bool.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(bool.Parse)); + parsers.Put(typeof(List), NullableListParse(bool.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(bool.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(bool.Parse)); + + parsers.Put(typeof(IEnumerable), ImmutableListParse(byte.Parse)); + parsers.Put(typeof(ICollection), ImmutableListParse(byte.Parse)); + parsers.Put(typeof(IList), ImmutableListParse(byte.Parse)); + parsers.Put(typeof(List), ListParse(byte.Parse)); + parsers.Put(typeof(ISet), ImmutableSetParse(byte.Parse)); + parsers.Put(typeof(HashSet), SetParse(byte.Parse)); + + parsers.Put(typeof(IEnumerable), ImmutableListParse(sbyte.Parse)); + parsers.Put(typeof(ICollection), ImmutableListParse(sbyte.Parse)); + parsers.Put(typeof(IList), ImmutableListParse(sbyte.Parse)); + parsers.Put(typeof(List), ListParse(sbyte.Parse)); + parsers.Put(typeof(ISet), ImmutableSetParse(sbyte.Parse)); + parsers.Put(typeof(HashSet), SetParse(sbyte.Parse)); + + parsers.Put(typeof(IEnumerable), ImmutableListParse(short.Parse)); + parsers.Put(typeof(ICollection), ImmutableListParse(short.Parse)); + parsers.Put(typeof(IList), ImmutableListParse(short.Parse)); + parsers.Put(typeof(List), ListParse(short.Parse)); + parsers.Put(typeof(ISet), ImmutableSetParse(short.Parse)); + parsers.Put(typeof(HashSet), SetParse(short.Parse)); + + parsers.Put(typeof(IEnumerable), ImmutableListParse(ushort.Parse)); + parsers.Put(typeof(ICollection), ImmutableListParse(ushort.Parse)); + parsers.Put(typeof(IList), ImmutableListParse(ushort.Parse)); + parsers.Put(typeof(List), ListParse(ushort.Parse)); + parsers.Put(typeof(ISet), ImmutableSetParse(ushort.Parse)); + parsers.Put(typeof(HashSet), SetParse(ushort.Parse)); + + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(int.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(int.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(int.Parse)); + parsers.Put(typeof(List), NullableListParse(int.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(int.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(int.Parse)); + + parsers.Put(typeof(IEnumerable), ImmutableListParse(uint.Parse)); + parsers.Put(typeof(ICollection), ImmutableListParse(uint.Parse)); + parsers.Put(typeof(IList), ImmutableListParse(uint.Parse)); + parsers.Put(typeof(List), ListParse(uint.Parse)); + parsers.Put(typeof(ISet), ImmutableSetParse(uint.Parse)); + parsers.Put(typeof(HashSet), SetParse(uint.Parse)); + + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(long.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(long.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(long.Parse)); + parsers.Put(typeof(List), NullableListParse(long.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(long.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(long.Parse)); + + parsers.Put(typeof(IEnumerable), ImmutableListParse(ulong.Parse)); + parsers.Put(typeof(ICollection), ImmutableListParse(ulong.Parse)); + parsers.Put(typeof(IList), ImmutableListParse(ulong.Parse)); + parsers.Put(typeof(List), ListParse(ulong.Parse)); + parsers.Put(typeof(ISet), ImmutableSetParse(ulong.Parse)); + parsers.Put(typeof(HashSet), SetParse(ulong.Parse)); + + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(float.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(float.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(float.Parse)); + parsers.Put(typeof(List), NullableListParse(float.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(float.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(float.Parse)); + + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(double.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(double.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(double.Parse)); + parsers.Put(typeof(List), NullableListParse(double.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(double.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(double.Parse)); + + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(decimal.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(decimal.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(decimal.Parse)); + parsers.Put(typeof(List), NullableListParse(decimal.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(decimal.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(decimal.Parse)); + + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(DateTime.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(DateTime.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(DateTime.Parse)); + parsers.Put(typeof(List), NullableListParse(DateTime.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(DateTime.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(DateTime.Parse)); + + parsers.Put(typeof(IEnumerable), ImmutableListParse(TimeSpan.Parse)); + parsers.Put(typeof(ICollection), ImmutableListParse(TimeSpan.Parse)); + parsers.Put(typeof(IList), ImmutableListParse(TimeSpan.Parse)); + parsers.Put(typeof(List), ListParse(TimeSpan.Parse)); + parsers.Put(typeof(ISet), ImmutableSetParse(TimeSpan.Parse)); + parsers.Put(typeof(HashSet), SetParse(TimeSpan.Parse)); + + return parsers.ToImmutableDictionary(); + } + + private static Func SafeParse(Func parse) + { + return parameter => + { + try + { + return parse(parameter.Value); + } + catch (OverflowException) + { + throw ParameterOutOfRange(parameter, typeof(T)); + } + catch (FormatException) + { + throw InvalidParameterFormat(parameter, typeof(T)); + } + catch (Exception e) + { + throw new InvalidOperationException(Strings.Format("Unable to parse parameter: '{0}' with value: '{1}' to {2}", + parameter.Name, parameter.Value, typeof(T)), e); + } + }; + } + + private static Func NullableListParse(Func itemParser) where T: struct + { + return ListParse(it => it.ToNullable(itemParser)); + } + + private static Func ListParse(Func itemParser) + { + return parameter => + { + if (string.IsNullOrEmpty(parameter.Value)) + { + return new List(); + } + return ParseCollection(parameter.Value, itemParser).ToList(); + }; + } + + private static Func NullableImmutableListParse(Func itemParser) where T: struct + { + return ImmutableListParse(it => it.ToNullable(itemParser)); + } + + private static Func ImmutableListParse(Func itemParser) + { + return parameter => + { + if (string.IsNullOrEmpty(parameter.Value)) + { + return Lists.EmptyList(); + } + return ParseCollection(parameter.Value, itemParser).ToImmutableList(); + }; + } + + private static Func NullableSetParse(Func itemParser) where T: struct + { + return SetParse(it => it.ToNullable(itemParser)); + } + + private static Func SetParse(Func itemParser) + { + return parameter => + { + if (string.IsNullOrEmpty(parameter.Value)) + { + return new HashSet(); + } + return ParseCollection(parameter.Value, itemParser).ToSet(); + }; + } + + private static Func NullableImmutableSetParse(Func itemParser) where T: struct + { + return ImmutableSetParse(it => it.ToNullable(itemParser)); + } + + private static Func ImmutableSetParse(Func itemParser) + { + return parameter => + { + if (string.IsNullOrEmpty(parameter.Value)) + { + return Sets.EmptySet(); + } + return ParseCollection(parameter.Value, itemParser).ToImmutableHashSet(); + }; + } + + private static ZonedDateTime ParseZonedDateTime(string value) + { + var dateTime = DateTime.Parse(value); + return new ZonedDateTime(Instant.FromDateTimeUtc(dateTime.ToUniversalTime()), DateTimeZone.Utc); + } + + private static LocalTime ParseLocalTime(string value) + { + return LocalTimePattern.ExtendedIsoPattern.Parse(value).Value; + } + + private static ArgumentException ParameterOutOfRange(Parameter parameter, Type type) + { + return new ArgumentException(Strings.Format("Query: '{0}' value: '{1}' is out of range for: '{2}'", + parameter.Name, parameter.Value, type)); + } + + private static ArgumentException InvalidParameterFormat(Parameter parameter, Type type) + { + return new ArgumentException(Strings.Format("Query '{0}' value: '{1}' format is invalid for: '{2}'", + parameter.Name, parameter.Value, type)); + } + + private static IEnumerable ParseCollection(string value, Func itemParser) + { + var results = value.Split(new[] { ',' }, StringSplitOptions.None) + .Where(it => it != null) + .Select(it => it.Trim()) + .Select(itemParser); + return results; + } + + public static T? ToNullable(this string s, Func itemParser) where T : struct + { + T? result = new T?(); + try + { + if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0) + { + result = itemParser(s); + } + } + catch (Exception e) + { + throw new InvalidOperationException(Strings.Format("Unable to parse value: '{0}' to nullable: '{1}'", s, typeof(T).ToString()), e); + } + return result; + } + + private class Parameter + { + internal string Name { get; private set; } + internal string Value { get; private set; } + + private Parameter(string name, string value) + { + Name = name; + Value = value; + } + + internal static Parameter Of(string name, string value) + { + return new Parameter(name, value); + } + } + } + + internal enum ParameterType + { + Undefined, + Query, + Path, + Header + } +} diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/packages.config b/samples/server/petstore/nancyfx-async/src/IO.Swagger/packages.config new file mode 100644 index 00000000000..e3401566e5d --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/packages.config @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/samples/server/petstore/nancyfx/IO.Swagger.sln b/samples/server/petstore/nancyfx/IO.Swagger.sln index 680fe56caa0..1e40deb1a14 100644 --- a/samples/server/petstore/nancyfx/IO.Swagger.sln +++ b/samples/server/petstore/nancyfx/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", "{19B8107D-38E2-4D32-B74F-C45470A9FCA3}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{768B8DC6-54EE-4D40-9B20-7857E1D742A4}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -10,10 +10,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{DFBD27E3-36EF-45CB-9D6D-EF500915B5CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{DFBD27E3-36EF-45CB-9D6D-EF500915B5CF}.Debug|Any CPU.Build.0 = Debug|Any CPU -{DFBD27E3-36EF-45CB-9D6D-EF500915B5CF}.Release|Any CPU.ActiveCfg = Release|Any CPU -{DFBD27E3-36EF-45CB-9D6D-EF500915B5CF}.Release|Any CPU.Build.0 = Release|Any CPU +{768B8DC6-54EE-4D40-9B20-7857E1D742A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{768B8DC6-54EE-4D40-9B20-7857E1D742A4}.Debug|Any CPU.Build.0 = Debug|Any CPU +{768B8DC6-54EE-4D40-9B20-7857E1D742A4}.Release|Any CPU.ActiveCfg = Release|Any CPU +{768B8DC6-54EE-4D40-9B20-7857E1D742A4}.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/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj index b7bb26dd9df..e1577197b6f 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj @@ -3,7 +3,7 @@ Debug AnyCPU - {19B8107D-38E2-4D32-B74F-C45470A9FCA3} + {768B8DC6-54EE-4D40-9B20-7857E1D742A4} Library Properties IO.Swagger.v2 diff --git a/samples/server/petstore/php-symfony/.swagger-codegen-ignore b/samples/server/petstore/php-symfony/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/php-symfony/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/php-symfony/.swagger-codegen/VERSION b/samples/server/petstore/php-symfony/.swagger-codegen/VERSION new file mode 100644 index 00000000000..f9f7450d135 --- /dev/null +++ b/samples/server/petstore/php-symfony/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/.php_cs b/samples/server/petstore/php-symfony/SymfonyBundle-php/.php_cs new file mode 100644 index 00000000000..6b8e23c818a --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/.php_cs @@ -0,0 +1,18 @@ +level(Symfony\CS\FixerInterface::PSR2_LEVEL) + ->setUsingCache(true) + ->fixers( + [ + 'ordered_use', + 'phpdoc_order', + 'short_array_syntax', + 'strict', + 'strict_param' + ] + ) + ->finder( + Symfony\CS\Finder\DefaultFinder::create() + ->in(__DIR__) + ); diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/.travis.yml b/samples/server/petstore/php-symfony/SymfonyBundle-php/.travis.yml new file mode 100644 index 00000000000..d77f3825f6f --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/.travis.yml @@ -0,0 +1,10 @@ +language: php +sudo: false +php: + - 5.4 + - 5.5 + - 5.6 + - 7.0 + - hhvm +before_install: "composer install" +script: "vendor/bin/phpunit" diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/ApiServer.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/ApiServer.php new file mode 100644 index 00000000000..d26918e624f --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/ApiServer.php @@ -0,0 +1,80 @@ +apis[$api])) { + throw new \InvalidArgumentException('API has already a handler: '.$api); + } + + $this->apis[$api] = $handler; + } + + /** + * Returns an API handler. + * + * @param string $api An API name of the handle + * @return mixed Returns a handler + * @throws \InvalidArgumentException When no such handler exists + */ + public function getApiHandler($api) + { + if (!isset($this->apis[$api])) { + throw new \InvalidArgumentException('No handler for '.$api.' implemented.'); + } + + return $this->apis[$api]; + } +} diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/PetApiInterface.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/PetApiInterface.php new file mode 100644 index 00000000000..587f6d813a3 --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/PetApiInterface.php @@ -0,0 +1,172 @@ +validator = $validator; + } + + public function setSerializer(SerializerInterface $serializer) + { + $this->serializer = $serializer; + } + + public function setApiServer($server) + { + $this->apiServer = $server; + } + + /** + * This will return a response with code 400. Usage example: + * return $this->createBadRequestResponse('Unable to access this page!'); + * + * @param string $message A message + * + * @return Response + */ + public function createBadRequestResponse($message = 'Bad Request.') + { + return new Response($message, 400); + } + + /** + * This will return an error response. Usage example: + * return $this->createErrorResponse(new UnauthorizedHttpException()); + * + * @param HttpException $exception An HTTP exception + * + * @return Response + */ + public function createErrorResponse(HttpException $exception) + { + $statusCode = $exception->getStatusCode(); + $headers = array_merge($exception->getHeaders(), ['Content-Type' => 'application/json']); + + $json = $this->exceptionToArray($exception); + $json['statusCode'] = $statusCode; + + return new Response(json_encode($json, 15, 512), $statusCode, $headers); + } + + /** + * Serializes data to a given type format. + * + * @param mixed $data The data to serialize. + * @param string $class The source data class. + * @param string $format The target serialization format. + * + * @return string A serialized data string. + */ + protected function serialize($data, $format) + { + return $this->serializer->serialize($data, $format); + } + + /** + * Deserializes data from a given type format. + * + * @param string $data The data to deserialize. + * @param string $class The target data class. + * @param string $format The source serialization format. + * + * @return mixed A deserialized data. + */ + protected function deserialize($data, $class, $format) + { + return $this->serializer->deserialize($data, $class, $format); + } + + protected function validate($data, $asserts = null) + { + $errors = $this->validator->validate($data, $asserts); + + if (count($errors) > 0) { + $errorsString = (string)$errors; + return $this->createBadRequestResponse($errorsString); + } + } + + /** + * Converts an exception to a serializable array. + * + * @param \Exception|null $exception + * + * @return array + */ + private function exceptionToArray(\Exception $exception = null) + { + if (null === $exception) { + return null; + } + + if (!$this->container->get('kernel')->isDebug()) { + return [ + 'message' => $exception->getMessage(), + ]; + } + + return [ + 'message' => $exception->getMessage(), + 'type' => get_class($exception), + 'previous' => $this->exceptionToArray($exception->getPrevious()), + ]; + } + + protected function getOutputFormat($accept, array $produced) + { + // Figure out what the client accepts + $accept = preg_split("/[\s,]+/", $accept); + + if (in_array('*/*', $accept) || in_array('application/*', $accept)) { + // Prefer JSON if the client has no preference + if (in_array('application/json', $produced)) { + return 'application/json'; + } + if (in_array('application/xml', $produced)) { + return 'application/xml'; + } + } + + if (in_array('application/json', $accept) && in_array('application/json', $produced)) { + return 'application/json'; + } + + if (in_array('application/xml', $accept) && in_array('application/xml', $produced)) { + return 'application/xml'; + } + + // If we reach this point, we don't have a common ground between server and client + return null; + } +} diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/PetController.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/PetController.php new file mode 100644 index 00000000000..9362b82b123 --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/PetController.php @@ -0,0 +1,799 @@ +headers->has('Content-Type')?$request->headers->get('Content-Type'):$consumes[0]; + if (!in_array($inputFormat, $consumes)) { + // We can't consume the content that the client is sending us + return new Response('', 415); + } + + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + // Authentication 'petstore_auth' required + // Oauth required + $securitypetstore_auth = $request->headers->get('authorization'); + + // Read out all input parameter values into variables + $body = $request->getContent(); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + + $body = $this->deserialize($body, 'Swagger\Server\Model\Pet', $inputFormat); + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\Type("Swagger\Server\Model\Pet"); + $response = $this->validate($body, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + // Set authentication method 'petstore_auth' + $handler->setpetstore_auth($securitypetstore_auth); + + // Make the call to the business logic + $responseCode = 204; + $responseHeaders = []; + $result = $handler->addPet($body, $responseCode, $responseHeaders); + + // Find default response message + $message = ''; + + // Find a more specific message, if available + switch ($responseCode) { + case 405: + $message = 'Invalid input'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Operation deletePet + * + * Deletes a pet + * + * @param Request $request The Symfony request to handle. + * @return Response The Symfony response. + */ + public function deletePetAction(Request $request, $petId) + { + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + // Authentication 'petstore_auth' required + // Oauth required + $securitypetstore_auth = $request->headers->get('authorization'); + + // Read out all input parameter values into variables + $apiKey = $request->headers->get('apiKey'); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + $petId = $this->deserialize($petId, 'int', 'string'); + $apiKey = $request->headers->get('apiKey'); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + $apiKey = $this->deserialize($apiKey, 'string', 'string'); + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\Type("int"); + $response = $this->validate($petId, $asserts); + if ($response instanceof Response) { + return $response; + } + $asserts = []; + $asserts[] = new Assert\Type("string"); + $response = $this->validate($apiKey, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + // Set authentication method 'petstore_auth' + $handler->setpetstore_auth($securitypetstore_auth); + + // Make the call to the business logic + $responseCode = 204; + $responseHeaders = []; + $result = $handler->deletePet($petId, $apiKey, $responseCode, $responseHeaders); + + // Find default response message + $message = ''; + + // Find a more specific message, if available + switch ($responseCode) { + case 400: + $message = 'Invalid pet value'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Operation findPetsByStatus + * + * Finds Pets by status + * + * @param Request $request The Symfony request to handle. + * @return Response The Symfony response. + */ + public function findPetsByStatusAction(Request $request) + { + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + // Authentication 'petstore_auth' required + // Oauth required + $securitypetstore_auth = $request->headers->get('authorization'); + + // Read out all input parameter values into variables + $status = $request->query->get('status'); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + $status = $this->deserialize($status, 'array', 'string'); + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\All([ + new Assert\Choice([ "available", "pending", "sold" ]) + ]); + $asserts[] = new Assert\All([ + new Assert\Type("string") + ]); + $response = $this->validate($status, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + // Set authentication method 'petstore_auth' + $handler->setpetstore_auth($securitypetstore_auth); + + // Make the call to the business logic + $responseCode = 200; + $responseHeaders = []; + $result = $handler->findPetsByStatus($status, $responseCode, $responseHeaders); + + // Find default response message + $message = 'successful operation'; + + // Find a more specific message, if available + switch ($responseCode) { + case 200: + $message = 'successful operation'; + break; + case 400: + $message = 'Invalid status value'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Operation findPetsByTags + * + * Finds Pets by tags + * + * @param Request $request The Symfony request to handle. + * @return Response The Symfony response. + */ + public function findPetsByTagsAction(Request $request) + { + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + // Authentication 'petstore_auth' required + // Oauth required + $securitypetstore_auth = $request->headers->get('authorization'); + + // Read out all input parameter values into variables + $tags = $request->query->get('tags'); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + $tags = $this->deserialize($tags, 'array', 'string'); + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\All([ + new Assert\Type("string") + ]); + $response = $this->validate($tags, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + // Set authentication method 'petstore_auth' + $handler->setpetstore_auth($securitypetstore_auth); + + // Make the call to the business logic + $responseCode = 200; + $responseHeaders = []; + $result = $handler->findPetsByTags($tags, $responseCode, $responseHeaders); + + // Find default response message + $message = 'successful operation'; + + // Find a more specific message, if available + switch ($responseCode) { + case 200: + $message = 'successful operation'; + break; + case 400: + $message = 'Invalid tag value'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Operation getPetById + * + * Find pet by ID + * + * @param Request $request The Symfony request to handle. + * @return Response The Symfony response. + */ + public function getPetByIdAction(Request $request, $petId) + { + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + // Authentication 'api_key' required + // Set key with prefix in header + $securityapi_key = $request->headers->get('api_key'); + + // Read out all input parameter values into variables + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + $petId = $this->deserialize($petId, 'int', 'string'); + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\Type("int"); + $response = $this->validate($petId, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + // Set authentication method 'api_key' + $handler->setapi_key($securityapi_key); + + // Make the call to the business logic + $responseCode = 200; + $responseHeaders = []; + $result = $handler->getPetById($petId, $responseCode, $responseHeaders); + + // Find default response message + $message = 'successful operation'; + + // Find a more specific message, if available + switch ($responseCode) { + case 200: + $message = 'successful operation'; + break; + case 400: + $message = 'Invalid ID supplied'; + break; + case 404: + $message = 'Pet not found'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Operation updatePet + * + * Update an existing pet + * + * @param Request $request The Symfony request to handle. + * @return Response The Symfony response. + */ + public function updatePetAction(Request $request) + { + // Make sure that the client is providing something that we can consume + $consumes = ['application/json', 'application/xml']; + $inputFormat = $request->headers->has('Content-Type')?$request->headers->get('Content-Type'):$consumes[0]; + if (!in_array($inputFormat, $consumes)) { + // We can't consume the content that the client is sending us + return new Response('', 415); + } + + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + // Authentication 'petstore_auth' required + // Oauth required + $securitypetstore_auth = $request->headers->get('authorization'); + + // Read out all input parameter values into variables + $body = $request->getContent(); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + + $body = $this->deserialize($body, 'Swagger\Server\Model\Pet', $inputFormat); + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\Type("Swagger\Server\Model\Pet"); + $response = $this->validate($body, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + // Set authentication method 'petstore_auth' + $handler->setpetstore_auth($securitypetstore_auth); + + // Make the call to the business logic + $responseCode = 204; + $responseHeaders = []; + $result = $handler->updatePet($body, $responseCode, $responseHeaders); + + // Find default response message + $message = ''; + + // Find a more specific message, if available + switch ($responseCode) { + case 400: + $message = 'Invalid ID supplied'; + break; + case 404: + $message = 'Pet not found'; + break; + case 405: + $message = 'Validation exception'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Operation updatePetWithForm + * + * Updates a pet in the store with form data + * + * @param Request $request The Symfony request to handle. + * @return Response The Symfony response. + */ + public function updatePetWithFormAction(Request $request, $petId) + { + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + // Authentication 'petstore_auth' required + // Oauth required + $securitypetstore_auth = $request->headers->get('authorization'); + + // Read out all input parameter values into variables + $name = $request->request->get('name'); + $status = $request->request->get('status'); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + $petId = $this->deserialize($petId, 'int', 'string'); + $name = $request->request->get('name'); + $status = $request->request->get('status'); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + $name = $this->deserialize($name, 'string', 'string'); + $name = $request->request->get('name'); + $status = $request->request->get('status'); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + $status = $this->deserialize($status, 'string', 'string'); + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\Type("int"); + $response = $this->validate($petId, $asserts); + if ($response instanceof Response) { + return $response; + } + $asserts = []; + $asserts[] = new Assert\Type("string"); + $response = $this->validate($name, $asserts); + if ($response instanceof Response) { + return $response; + } + $asserts = []; + $asserts[] = new Assert\Type("string"); + $response = $this->validate($status, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + // Set authentication method 'petstore_auth' + $handler->setpetstore_auth($securitypetstore_auth); + + // Make the call to the business logic + $responseCode = 204; + $responseHeaders = []; + $result = $handler->updatePetWithForm($petId, $name, $status, $responseCode, $responseHeaders); + + // Find default response message + $message = ''; + + // Find a more specific message, if available + switch ($responseCode) { + case 405: + $message = 'Invalid input'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Operation uploadFile + * + * uploads an image + * + * @param Request $request The Symfony request to handle. + * @return Response The Symfony response. + */ + public function uploadFileAction(Request $request, $petId) + { + // Figure out what data format to return to the client + $produces = ['application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + // Authentication 'petstore_auth' required + // Oauth required + $securitypetstore_auth = $request->headers->get('authorization'); + + // Read out all input parameter values into variables + $additionalMetadata = $request->request->get('additionalMetadata'); + $file = $request->files->get('file'); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + $petId = $this->deserialize($petId, 'int', 'string'); + $additionalMetadata = $request->request->get('additionalMetadata'); + $file = $request->files->get('file'); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + $additionalMetadata = $this->deserialize($additionalMetadata, 'string', 'string'); + $additionalMetadata = $request->request->get('additionalMetadata'); + $file = $request->files->get('file'); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\Type("int"); + $response = $this->validate($petId, $asserts); + if ($response instanceof Response) { + return $response; + } + $asserts = []; + $asserts[] = new Assert\Type("string"); + $response = $this->validate($additionalMetadata, $asserts); + if ($response instanceof Response) { + return $response; + } + $asserts = []; + $asserts[] = new Assert\File(); + $response = $this->validate($file, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + // Set authentication method 'petstore_auth' + $handler->setpetstore_auth($securitypetstore_auth); + + // Make the call to the business logic + $responseCode = 200; + $responseHeaders = []; + $result = $handler->uploadFile($petId, $additionalMetadata, $file, $responseCode, $responseHeaders); + + // Find default response message + $message = 'successful operation'; + + // Find a more specific message, if available + switch ($responseCode) { + case 200: + $message = 'successful operation'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Returns the handler for this API controller. + * @return PetApiInterface + */ + public function getApiHandler() + { + return $this->apiServer->getApiHandler('pet'); + } +} diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/StoreController.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/StoreController.php new file mode 100644 index 00000000000..304a847c6eb --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/StoreController.php @@ -0,0 +1,368 @@ +headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + + // Read out all input parameter values into variables + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + $orderId = $this->deserialize($orderId, 'string', 'string'); + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\Type("string"); + $response = $this->validate($orderId, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + + // Make the call to the business logic + $responseCode = 204; + $responseHeaders = []; + $result = $handler->deleteOrder($orderId, $responseCode, $responseHeaders); + + // Find default response message + $message = ''; + + // Find a more specific message, if available + switch ($responseCode) { + case 400: + $message = 'Invalid ID supplied'; + break; + case 404: + $message = 'Order not found'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Operation getInventory + * + * Returns pet inventories by status + * + * @param Request $request The Symfony request to handle. + * @return Response The Symfony response. + */ + public function getInventoryAction(Request $request) + { + // Figure out what data format to return to the client + $produces = ['application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + // Authentication 'api_key' required + // Set key with prefix in header + $securityapi_key = $request->headers->get('api_key'); + + // Read out all input parameter values into variables + + // Validate the input values + + + try { + $handler = $this->getApiHandler(); + + // Set authentication method 'api_key' + $handler->setapi_key($securityapi_key); + + // Make the call to the business logic + $responseCode = 200; + $responseHeaders = []; + $result = $handler->getInventory($responseCode, $responseHeaders); + + // Find default response message + $message = 'successful operation'; + + // Find a more specific message, if available + switch ($responseCode) { + case 200: + $message = 'successful operation'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Operation getOrderById + * + * Find purchase order by ID + * + * @param Request $request The Symfony request to handle. + * @return Response The Symfony response. + */ + public function getOrderByIdAction(Request $request, $orderId) + { + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + + // Read out all input parameter values into variables + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + $orderId = $this->deserialize($orderId, 'int', 'string'); + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\Type("int"); + $asserts[] = new Assert\GreaterThanOrEqual(1); + $asserts[] = new Assert\LessThanOrEqual(1); + $response = $this->validate($orderId, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + + // Make the call to the business logic + $responseCode = 200; + $responseHeaders = []; + $result = $handler->getOrderById($orderId, $responseCode, $responseHeaders); + + // Find default response message + $message = 'successful operation'; + + // Find a more specific message, if available + switch ($responseCode) { + case 200: + $message = 'successful operation'; + break; + case 400: + $message = 'Invalid ID supplied'; + break; + case 404: + $message = 'Order not found'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Operation placeOrder + * + * Place an order for a pet + * + * @param Request $request The Symfony request to handle. + * @return Response The Symfony response. + */ + public function placeOrderAction(Request $request) + { + // Make sure that the client is providing something that we can consume + $consumes = []; + $inputFormat = $request->headers->has('Content-Type')?$request->headers->get('Content-Type'):$consumes[0]; + if (!in_array($inputFormat, $consumes)) { + // We can't consume the content that the client is sending us + return new Response('', 415); + } + + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + + // Read out all input parameter values into variables + $body = $request->getContent(); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + + $body = $this->deserialize($body, 'Swagger\Server\Model\Order', $inputFormat); + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\Type("Swagger\Server\Model\Order"); + $response = $this->validate($body, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + + // Make the call to the business logic + $responseCode = 200; + $responseHeaders = []; + $result = $handler->placeOrder($body, $responseCode, $responseHeaders); + + // Find default response message + $message = 'successful operation'; + + // Find a more specific message, if available + switch ($responseCode) { + case 200: + $message = 'successful operation'; + break; + case 400: + $message = 'Invalid Order'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Returns the handler for this API controller. + * @return StoreApiInterface + */ + public function getApiHandler() + { + return $this->apiServer->getApiHandler('store'); + } +} diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/UserController.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/UserController.php new file mode 100644 index 00000000000..7f182bb1e61 --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/UserController.php @@ -0,0 +1,720 @@ +headers->has('Content-Type')?$request->headers->get('Content-Type'):$consumes[0]; + if (!in_array($inputFormat, $consumes)) { + // We can't consume the content that the client is sending us + return new Response('', 415); + } + + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + + // Read out all input parameter values into variables + $body = $request->getContent(); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + + $body = $this->deserialize($body, 'Swagger\Server\Model\User', $inputFormat); + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\Type("Swagger\Server\Model\User"); + $response = $this->validate($body, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + + // Make the call to the business logic + $responseCode = 204; + $responseHeaders = []; + $result = $handler->createUser($body, $responseCode, $responseHeaders); + + // Find default response message + $message = 'successful operation'; + + // Find a more specific message, if available + switch ($responseCode) { + case 0: + $message = 'successful operation'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Operation createUsersWithArrayInput + * + * Creates list of users with given input array + * + * @param Request $request The Symfony request to handle. + * @return Response The Symfony response. + */ + public function createUsersWithArrayInputAction(Request $request) + { + // Make sure that the client is providing something that we can consume + $consumes = []; + $inputFormat = $request->headers->has('Content-Type')?$request->headers->get('Content-Type'):$consumes[0]; + if (!in_array($inputFormat, $consumes)) { + // We can't consume the content that the client is sending us + return new Response('', 415); + } + + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + + // Read out all input parameter values into variables + $body = $request->getContent(); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + + $body = $this->deserialize($body, 'Swagger\Server\Model\User[]', $inputFormat); + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\All([ + new Assert\Type("Swagger\Server\Model\User[]") + ]); + $response = $this->validate($body, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + + // Make the call to the business logic + $responseCode = 204; + $responseHeaders = []; + $result = $handler->createUsersWithArrayInput($body, $responseCode, $responseHeaders); + + // Find default response message + $message = 'successful operation'; + + // Find a more specific message, if available + switch ($responseCode) { + case 0: + $message = 'successful operation'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Operation createUsersWithListInput + * + * Creates list of users with given input array + * + * @param Request $request The Symfony request to handle. + * @return Response The Symfony response. + */ + public function createUsersWithListInputAction(Request $request) + { + // Make sure that the client is providing something that we can consume + $consumes = []; + $inputFormat = $request->headers->has('Content-Type')?$request->headers->get('Content-Type'):$consumes[0]; + if (!in_array($inputFormat, $consumes)) { + // We can't consume the content that the client is sending us + return new Response('', 415); + } + + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + + // Read out all input parameter values into variables + $body = $request->getContent(); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + + $body = $this->deserialize($body, 'Swagger\Server\Model\User[]', $inputFormat); + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\All([ + new Assert\Type("Swagger\Server\Model\User[]") + ]); + $response = $this->validate($body, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + + // Make the call to the business logic + $responseCode = 204; + $responseHeaders = []; + $result = $handler->createUsersWithListInput($body, $responseCode, $responseHeaders); + + // Find default response message + $message = 'successful operation'; + + // Find a more specific message, if available + switch ($responseCode) { + case 0: + $message = 'successful operation'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Operation deleteUser + * + * Delete user + * + * @param Request $request The Symfony request to handle. + * @return Response The Symfony response. + */ + public function deleteUserAction(Request $request, $username) + { + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + + // Read out all input parameter values into variables + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + $username = $this->deserialize($username, 'string', 'string'); + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\Type("string"); + $response = $this->validate($username, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + + // Make the call to the business logic + $responseCode = 204; + $responseHeaders = []; + $result = $handler->deleteUser($username, $responseCode, $responseHeaders); + + // Find default response message + $message = ''; + + // Find a more specific message, if available + switch ($responseCode) { + case 400: + $message = 'Invalid username supplied'; + break; + case 404: + $message = 'User not found'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Operation getUserByName + * + * Get user by user name + * + * @param Request $request The Symfony request to handle. + * @return Response The Symfony response. + */ + public function getUserByNameAction(Request $request, $username) + { + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + + // Read out all input parameter values into variables + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + $username = $this->deserialize($username, 'string', 'string'); + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\Type("string"); + $response = $this->validate($username, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + + // Make the call to the business logic + $responseCode = 200; + $responseHeaders = []; + $result = $handler->getUserByName($username, $responseCode, $responseHeaders); + + // Find default response message + $message = 'successful operation'; + + // Find a more specific message, if available + switch ($responseCode) { + case 200: + $message = 'successful operation'; + break; + case 400: + $message = 'Invalid username supplied'; + break; + case 404: + $message = 'User not found'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Operation loginUser + * + * Logs user into the system + * + * @param Request $request The Symfony request to handle. + * @return Response The Symfony response. + */ + public function loginUserAction(Request $request) + { + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + + // Read out all input parameter values into variables + $username = $request->query->get('username'); + $password = $request->query->get('password'); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + $username = $this->deserialize($username, 'string', 'string'); + $username = $request->query->get('username'); + $password = $request->query->get('password'); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + $password = $this->deserialize($password, 'string', 'string'); + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\Type("string"); + $response = $this->validate($username, $asserts); + if ($response instanceof Response) { + return $response; + } + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\Type("string"); + $response = $this->validate($password, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + + // Make the call to the business logic + $responseCode = 200; + $responseHeaders = []; + $result = $handler->loginUser($username, $password, $responseCode, $responseHeaders); + + // Find default response message + $message = 'successful operation'; + + // Find a more specific message, if available + switch ($responseCode) { + case 200: + $message = 'successful operation'; + break; + case 400: + $message = 'Invalid username/password supplied'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Operation logoutUser + * + * Logs out current logged in user session + * + * @param Request $request The Symfony request to handle. + * @return Response The Symfony response. + */ + public function logoutUserAction(Request $request) + { + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + + // Read out all input parameter values into variables + + // Validate the input values + + + try { + $handler = $this->getApiHandler(); + + + // Make the call to the business logic + $responseCode = 204; + $responseHeaders = []; + $result = $handler->logoutUser($responseCode, $responseHeaders); + + // Find default response message + $message = 'successful operation'; + + // Find a more specific message, if available + switch ($responseCode) { + case 0: + $message = 'successful operation'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Operation updateUser + * + * Updated user + * + * @param Request $request The Symfony request to handle. + * @return Response The Symfony response. + */ + public function updateUserAction(Request $request, $username) + { + // Make sure that the client is providing something that we can consume + $consumes = []; + $inputFormat = $request->headers->has('Content-Type')?$request->headers->get('Content-Type'):$consumes[0]; + if (!in_array($inputFormat, $consumes)) { + // We can't consume the content that the client is sending us + return new Response('', 415); + } + + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + + // Handle authentication + + // Read out all input parameter values into variables + $body = $request->getContent(); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + + $body = $this->deserialize($body, 'Swagger\Server\Model\User', $inputFormat); + $body = $request->getContent(); + + // Use the default value if no value was provided + + // Deserialize the input values that needs it + + $body = $this->deserialize($body, 'Swagger\Server\Model\User', $inputFormat); + + // Validate the input values + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\Type("string"); + $response = $this->validate($username, $asserts); + if ($response instanceof Response) { + return $response; + } + $asserts = []; + $asserts[] = new Assert\NotNull(); + $asserts[] = new Assert\Type("Swagger\Server\Model\User"); + $response = $this->validate($body, $asserts); + if ($response instanceof Response) { + return $response; + } + + + try { + $handler = $this->getApiHandler(); + + + // Make the call to the business logic + $responseCode = 204; + $responseHeaders = []; + $result = $handler->updateUser($username, $body, $responseCode, $responseHeaders); + + // Find default response message + $message = ''; + + // Find a more specific message, if available + switch ($responseCode) { + case 400: + $message = 'Invalid user supplied'; + break; + case 404: + $message = 'User not found'; + break; + } + + return new Response( + $result?$this->serialize($result, $responseFormat):'', + $responseCode, + array_merge( + $responseHeaders, + [ + 'Content-Type' => $responseFormat, + 'X-Swagger-Message' => $message + ] + ) + ); + } catch (Exception $fallthrough) { + return $this->createErrorResponse(new HttpException(500, 'An unsuspected error occurred.', $fallthrough)); + } + } + + /** + * Returns the handler for this API controller. + * @return UserApiInterface + */ + public function getApiHandler() + { + return $this->apiServer->getApiHandler('user'); + } +} diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/DependencyInjection/Compiler/SwaggerServerApiPass.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/DependencyInjection/Compiler/SwaggerServerApiPass.php new file mode 100644 index 00000000000..7ac5898d143 --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/DependencyInjection/Compiler/SwaggerServerApiPass.php @@ -0,0 +1,70 @@ +has('swagger_server.api.api_server')) { + return; + } + + $definition = $container->findDefinition('swagger_server.api.api_server'); + + // find all service IDs with the swagger_server.api tag + $taggedServices = $container->findTaggedServiceIds('swagger_server.api'); + + foreach ($taggedServices as $id => $tags) { + foreach ($tags as $tag) { + // add the transport service to the ChainTransport service + $definition->addMethodCall('addApiHandler', [$tag['api'], new Reference($id)]); + } + } + } +} diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/DependencyInjection/SwaggerServerExtension.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/DependencyInjection/SwaggerServerExtension.php new file mode 100644 index 00000000000..2f12f034cce --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/DependencyInjection/SwaggerServerExtension.php @@ -0,0 +1,57 @@ +load('services.yml'); + } + + public function getAlias() + { + return 'swagger_server'; + } +} diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/ApiResponse.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/ApiResponse.php new file mode 100644 index 00000000000..5a00e41be2d --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/ApiResponse.php @@ -0,0 +1,154 @@ +code = isset($data['code']) ? $data['code'] : null; + $this->type = isset($data['type']) ? $data['type'] : null; + $this->message = isset($data['message']) ? $data['message'] : null; + } + + /** + * Gets code. + * + * @return int|null + */ + public function getCode() + { + return $this->code; + } + + /** + * Sets code. + * + * @param int|null $code + * + * @return $this + */ + public function setCode($code = null) + { + $this->code = $code; + + return $this; + } + + /** + * Gets type. + * + * @return string|null + */ + public function getType() + { + return $this->type; + } + + /** + * Sets type. + * + * @param string|null $type + * + * @return $this + */ + public function setType($type = null) + { + $this->type = $type; + + return $this; + } + + /** + * Gets message. + * + * @return string|null + */ + public function getMessage() + { + return $this->message; + } + + /** + * Sets message. + * + * @param string|null $message + * + * @return $this + */ + public function setMessage($message = null) + { + $this->message = $message; + + return $this; + } +} + + diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Category.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Category.php new file mode 100644 index 00000000000..e59ecdbe7c4 --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Category.php @@ -0,0 +1,121 @@ +id = isset($data['id']) ? $data['id'] : null; + $this->name = isset($data['name']) ? $data['name'] : null; + } + + /** + * Gets id. + * + * @return int|null + */ + public function getId() + { + return $this->id; + } + + /** + * Sets id. + * + * @param int|null $id + * + * @return $this + */ + public function setId($id = null) + { + $this->id = $id; + + return $this; + } + + /** + * Gets name. + * + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param string|null $name + * + * @return $this + */ + public function setName($name = null) + { + $this->name = $name; + + return $this; + } +} + + diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Order.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Order.php new file mode 100644 index 00000000000..65a7ead3cf2 --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Order.php @@ -0,0 +1,256 @@ +id = isset($data['id']) ? $data['id'] : null; + $this->petId = isset($data['petId']) ? $data['petId'] : null; + $this->quantity = isset($data['quantity']) ? $data['quantity'] : null; + $this->shipDate = isset($data['shipDate']) ? $data['shipDate'] : null; + $this->status = isset($data['status']) ? $data['status'] : null; + $this->complete = isset($data['complete']) ? $data['complete'] : false; + } + + /** + * Gets id. + * + * @return int|null + */ + public function getId() + { + return $this->id; + } + + /** + * Sets id. + * + * @param int|null $id + * + * @return $this + */ + public function setId($id = null) + { + $this->id = $id; + + return $this; + } + + /** + * Gets petId. + * + * @return int|null + */ + public function getPetId() + { + return $this->petId; + } + + /** + * Sets petId. + * + * @param int|null $petId + * + * @return $this + */ + public function setPetId($petId = null) + { + $this->petId = $petId; + + return $this; + } + + /** + * Gets quantity. + * + * @return int|null + */ + public function getQuantity() + { + return $this->quantity; + } + + /** + * Sets quantity. + * + * @param int|null $quantity + * + * @return $this + */ + public function setQuantity($quantity = null) + { + $this->quantity = $quantity; + + return $this; + } + + /** + * Gets shipDate. + * + * @return \DateTime|null + */ + public function getShipDate() + { + return $this->shipDate; + } + + /** + * Sets shipDate. + * + * @param \DateTime|null $shipDate + * + * @return $this + */ + public function setShipDate(\DateTime $shipDate = null) + { + $this->shipDate = $shipDate; + + return $this; + } + + /** + * Gets status. + * + * @return string|null + */ + public function getStatus() + { + return $this->status; + } + + /** + * Sets status. + * + * @param string|null $status Order Status + * + * @return $this + */ + public function setStatus($status = null) + { + $this->status = $status; + + return $this; + } + + /** + * Gets complete. + * + * @return bool|null + */ + public function isComplete() + { + return $this->complete; + } + + /** + * Sets complete. + * + * @param bool|null $complete + * + * @return $this + */ + public function setComplete($complete = null) + { + $this->complete = $complete; + + return $this; + } +} + + diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Pet.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Pet.php new file mode 100644 index 00000000000..ac3fba47a7d --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Pet.php @@ -0,0 +1,262 @@ +") + */ + protected $photoUrls; + + /** + * @var Swagger\Server\Model\Tag[]|null + * @SerializedName("tags") + * @Assert\All({ + * @Assert\Type("Swagger\Server\Model\Tag") + * }) + * @Type("array") + */ + protected $tags; + + /** + * pet status in the store + * + * @var string|null + * @SerializedName("status") + * @Assert\Choice({ "available", "pending", "sold" }) + * @Assert\Type("string") + * @Type("string") + */ + protected $status; + + /** + * Constructor + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->id = isset($data['id']) ? $data['id'] : null; + $this->category = isset($data['category']) ? $data['category'] : null; + $this->name = isset($data['name']) ? $data['name'] : null; + $this->photoUrls = isset($data['photoUrls']) ? $data['photoUrls'] : null; + $this->tags = isset($data['tags']) ? $data['tags'] : null; + $this->status = isset($data['status']) ? $data['status'] : null; + } + + /** + * Gets id. + * + * @return int|null + */ + public function getId() + { + return $this->id; + } + + /** + * Sets id. + * + * @param int|null $id + * + * @return $this + */ + public function setId($id = null) + { + $this->id = $id; + + return $this; + } + + /** + * Gets category. + * + * @return Swagger\Server\Model\Category|null + */ + public function getCategory() + { + return $this->category; + } + + /** + * Sets category. + * + * @param Swagger\Server\Model\Category|null $category + * + * @return $this + */ + public function setCategory(Category $category = null) + { + $this->category = $category; + + return $this; + } + + /** + * Gets name. + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param string $name + * + * @return $this + */ + public function setName($name) + { + $this->name = $name; + + return $this; + } + + /** + * Gets photoUrls. + * + * @return string[] + */ + public function getPhotoUrls() + { + return $this->photoUrls; + } + + /** + * Sets photoUrls. + * + * @param string[] $photoUrls + * + * @return $this + */ + public function setPhotoUrls(array $photoUrls) + { + $this->photoUrls = $photoUrls; + + return $this; + } + + /** + * Gets tags. + * + * @return Swagger\Server\Model\Tag[]|null + */ + public function getTags() + { + return $this->tags; + } + + /** + * Sets tags. + * + * @param Swagger\Server\Model\Tag[]|null $tags + * + * @return $this + */ + public function setTags(array $tags = null) + { + $this->tags = $tags; + + return $this; + } + + /** + * Gets status. + * + * @return string|null + */ + public function getStatus() + { + return $this->status; + } + + /** + * Sets status. + * + * @param string|null $status pet status in the store + * + * @return $this + */ + public function setStatus($status = null) + { + $this->status = $status; + + return $this; + } +} + + diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Tag.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Tag.php new file mode 100644 index 00000000000..ffe2ef4fb4f --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Tag.php @@ -0,0 +1,121 @@ +id = isset($data['id']) ? $data['id'] : null; + $this->name = isset($data['name']) ? $data['name'] : null; + } + + /** + * Gets id. + * + * @return int|null + */ + public function getId() + { + return $this->id; + } + + /** + * Sets id. + * + * @param int|null $id + * + * @return $this + */ + public function setId($id = null) + { + $this->id = $id; + + return $this; + } + + /** + * Gets name. + * + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param string|null $name + * + * @return $this + */ + public function setName($name = null) + { + $this->name = $name; + + return $this; + } +} + + diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/User.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/User.php new file mode 100644 index 00000000000..5f69763a525 --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/User.php @@ -0,0 +1,321 @@ +id = isset($data['id']) ? $data['id'] : null; + $this->username = isset($data['username']) ? $data['username'] : null; + $this->firstName = isset($data['firstName']) ? $data['firstName'] : null; + $this->lastName = isset($data['lastName']) ? $data['lastName'] : null; + $this->email = isset($data['email']) ? $data['email'] : null; + $this->password = isset($data['password']) ? $data['password'] : null; + $this->phone = isset($data['phone']) ? $data['phone'] : null; + $this->userStatus = isset($data['userStatus']) ? $data['userStatus'] : null; + } + + /** + * Gets id. + * + * @return int|null + */ + public function getId() + { + return $this->id; + } + + /** + * Sets id. + * + * @param int|null $id + * + * @return $this + */ + public function setId($id = null) + { + $this->id = $id; + + return $this; + } + + /** + * Gets username. + * + * @return string|null + */ + public function getUsername() + { + return $this->username; + } + + /** + * Sets username. + * + * @param string|null $username + * + * @return $this + */ + public function setUsername($username = null) + { + $this->username = $username; + + return $this; + } + + /** + * Gets firstName. + * + * @return string|null + */ + public function getFirstName() + { + return $this->firstName; + } + + /** + * Sets firstName. + * + * @param string|null $firstName + * + * @return $this + */ + public function setFirstName($firstName = null) + { + $this->firstName = $firstName; + + return $this; + } + + /** + * Gets lastName. + * + * @return string|null + */ + public function getLastName() + { + return $this->lastName; + } + + /** + * Sets lastName. + * + * @param string|null $lastName + * + * @return $this + */ + public function setLastName($lastName = null) + { + $this->lastName = $lastName; + + return $this; + } + + /** + * Gets email. + * + * @return string|null + */ + public function getEmail() + { + return $this->email; + } + + /** + * Sets email. + * + * @param string|null $email + * + * @return $this + */ + public function setEmail($email = null) + { + $this->email = $email; + + return $this; + } + + /** + * Gets password. + * + * @return string|null + */ + public function getPassword() + { + return $this->password; + } + + /** + * Sets password. + * + * @param string|null $password + * + * @return $this + */ + public function setPassword($password = null) + { + $this->password = $password; + + return $this; + } + + /** + * Gets phone. + * + * @return string|null + */ + public function getPhone() + { + return $this->phone; + } + + /** + * Sets phone. + * + * @param string|null $phone + * + * @return $this + */ + public function setPhone($phone = null) + { + $this->phone = $phone; + + return $this; + } + + /** + * Gets userStatus. + * + * @return int|null + */ + public function getUserStatus() + { + return $this->userStatus; + } + + /** + * Sets userStatus. + * + * @param int|null $userStatus User Status + * + * @return $this + */ + public function setUserStatus($userStatus = null) + { + $this->userStatus = $userStatus; + + return $this; + } +} + + diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/README.md b/samples/server/petstore/php-symfony/SymfonyBundle-php/README.md new file mode 100644 index 00000000000..d4375c06941 --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/README.md @@ -0,0 +1,182 @@ +# SwaggerServer +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. + +This [Symfony](https://symfony.com/) bundle is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: 1.0.0 +- Build package: io.swagger.codegen.languages.SymfonyServerCodegen + +## Requirements + +PHP 5.4.0 and later + +## Installation & Usage + +To install the dependencies via [Composer](http://getcomposer.org/), add the following repository to `composer.json` of your Symfony project: + +```json +{ + "repositories": [{ + "type": "path", + "url": "//Path to your generated swagger bundle" + }], +} +``` + +Then run: + +``` +composer require swagger/server-bundle:dev-master +``` + +to add the generated swagger bundle as a dependency. + +## Tests + +To run the unit tests for the generated bundle, first navigate to the directory containing the code, then run the following commands: + +``` +composer install +./vendor/bin/phpunit +``` + + +## Getting Started + +Step 1: Please follow the [installation procedure](#installation--usage) first. + +Step 2: Enable the bundle in the kernel: + +```php + addPet($body) + +Add a new pet to the store + + + +### Example Implementation +```php + deletePet($petId, $apiKey) + +Deletes a pet + + + +### Example Implementation +```php + Swagger\Server\Model\Pet[] findPetsByStatus($status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example Implementation +```php + Swagger\Server\Model\Pet[] findPetsByTags($tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example Implementation +```php + Swagger\Server\Model\Pet getPetById($petId) + +Find pet by ID + +Returns a single pet + +### Example Implementation +```php + updatePet($body) + +Update an existing pet + + + +### Example Implementation +```php + updatePetWithForm($petId, $name, $status) + +Updates a pet in the store with form data + + + +### Example Implementation +```php + Swagger\Server\Model\ApiResponse uploadFile($petId, $additionalMetadata, $file) + +uploads an image + + + +### Example Implementation +```php + 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 Implementation +```php + int[] getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example Implementation +```php + Swagger\Server\Model\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 Implementation +```php + Swagger\Server\Model\Order placeOrder($body) + +Place an order for a pet + + + +### Example Implementation +```php + createUser($body) + +Create user + +This can only be done by the logged in user. + +### Example Implementation +```php + createUsersWithArrayInput($body) + +Creates list of users with given input array + + + +### Example Implementation +```php + createUsersWithListInput($body) + +Creates list of users with given input array + + + +### Example Implementation +```php + deleteUser($username) + +Delete user + +This can only be done by the logged in user. + +### Example Implementation +```php + Swagger\Server\Model\User getUserByName($username) + +Get user by user name + + + +### Example Implementation +```php + string loginUser($username, $password) + +Logs user into the system + + + +### Example Implementation +```php + logoutUser() + +Logs out current logged in user session + + + +### Example Implementation +```php + updateUser($username, $body) + +Updated user + +This can only be done by the logged in user. + +### Example Implementation +```php +serializer = SerializerBuilder::create() + ->setDeserializationVisitor('json', new StrictJsonDeserializationVisitor($naming_strategy)) + ->setDeserializationVisitor('xml', new XmlDeserializationVisitor($naming_strategy)) + ->build(); + } + + public function serialize($data, $format) + { + return SerializerBuilder::create()->build()->serialize($data, $this->convertFormat($format)); + } + + public function deserialize($data, $type, $format) + { + if ($format == 'string') { + return $this->deserializeString($data, $type); + } + + // If we end up here, let JMS serializer handle the deserialization + return $this->serializer->deserialize($data, $type, $this->convertFormat($format)); + } + + private function convertFormat($format) + { + switch ($format) { + case 'application/json': + return 'json'; + case 'application/xml': + return 'xml'; + } + + return null; + } + + private function deserializeString($data, $type) + { + switch ($type) { + case 'int': + case 'integer': + if (is_int($data)) { + return $data; + } + + if (is_numeric($data)) { + return $data + 0; + } + + break; + case 'string': + break; + case 'boolean': + case 'bool': + if (strtolower($data) === 'true') { + return true; + } + + if (strtolower($data) === 'false') { + return false; + } + + break; + case 'array': + return explode(',', $data); + case 'array': + return explode(' ', $data); + case 'array': + return explode("\t", $data); + case 'array': + return explode('|', $data); + } + + // If we end up here, just return data + return $data; + } +} diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Service/SerializerInterface.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Service/SerializerInterface.php new file mode 100644 index 00000000000..bf8bc1896f6 --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Service/SerializerInterface.php @@ -0,0 +1,27 @@ +validator = Validation::createValidator(); + } + + public function validate($value, $constraints = null, $groups = null) + { + return $this->validator->validate($value, $constraints, $groups); + } +} diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Service/TypeMismatchException.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Service/TypeMismatchException.php new file mode 100644 index 00000000000..97a8f2e3197 --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Service/TypeMismatchException.php @@ -0,0 +1,52 @@ +getCurrentPath()) > 0) { + $property = sprintf('property "%s" to be ', implode('.', $context->getCurrentPath())); + } else { + $property = ''; + } + + return new static(sprintf( + 'Expected %s%s, but got %s: %s', + $property, + $expected_type, + gettype($actual_value), + json_encode($actual_value) + )); + } +} diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Service/ValidatorInterface.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Service/ValidatorInterface.php new file mode 100644 index 00000000000..a85241e81f6 --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Service/ValidatorInterface.php @@ -0,0 +1,25 @@ +addCompilerPass(new SwaggerServerApiPass()); + } +} diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/Api/PetApiInterfaceTest.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/Api/PetApiInterfaceTest.php new file mode 100644 index 00000000000..ca0c3b8ec26 --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/Api/PetApiInterfaceTest.php @@ -0,0 +1,217 @@ +request('POST', $path); + } + + /** + * Test case for deletePet + * + * Deletes a pet. + * + */ + public function testDeletePet() + { + $client = static::createClient(); + + $path = '/pet/{petId}'; + $pattern = '{petId}'; + $data = $this->genTestData('\d+'); + $path = str_replace($pattern, $data, $path); + + $crawler = $client->request('DELETE', $path); + } + + /** + * Test case for findPetsByStatus + * + * Finds Pets by status. + * + */ + public function testFindPetsByStatus() + { + $client = static::createClient(); + + $path = '/pet/findByStatus'; + + $crawler = $client->request('GET', $path); + } + + /** + * Test case for findPetsByTags + * + * Finds Pets by tags. + * + */ + public function testFindPetsByTags() + { + $client = static::createClient(); + + $path = '/pet/findByTags'; + + $crawler = $client->request('GET', $path); + } + + /** + * Test case for getPetById + * + * Find pet by ID. + * + */ + public function testGetPetById() + { + $client = static::createClient(); + + $path = '/pet/{petId}'; + $pattern = '{petId}'; + $data = $this->genTestData('\d+'); + $path = str_replace($pattern, $data, $path); + + $crawler = $client->request('GET', $path); + } + + /** + * Test case for updatePet + * + * Update an existing pet. + * + */ + public function testUpdatePet() + { + $client = static::createClient(); + + $path = '/pet'; + + $crawler = $client->request('PUT', $path); + } + + /** + * Test case for updatePetWithForm + * + * Updates a pet in the store with form data. + * + */ + public function testUpdatePetWithForm() + { + $client = static::createClient(); + + $path = '/pet/{petId}'; + $pattern = '{petId}'; + $data = $this->genTestData('\d+'); + $path = str_replace($pattern, $data, $path); + + $crawler = $client->request('POST', $path); + } + + /** + * Test case for uploadFile + * + * uploads an image. + * + */ + public function testUploadFile() + { + $client = static::createClient(); + + $path = '/pet/{petId}/uploadImage'; + $pattern = '{petId}'; + $data = $this->genTestData('\d+'); + $path = str_replace($pattern, $data, $path); + + $crawler = $client->request('POST', $path); + } + + protected function genTestData($regexp) + { + $grammar = new \Hoa\File\Read('hoa://Library/Regex/Grammar.pp'); + $compiler = \Hoa\Compiler\Llk\Llk::load($grammar); + $ast = $compiler->parse($regexp); + $generator = new \Hoa\Regex\Visitor\Isotropic(new \Hoa\Math\Sampler\Random()); + + return $generator->visit($ast); + } +} diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/Api/StoreApiInterfaceTest.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/Api/StoreApiInterfaceTest.php new file mode 100644 index 00000000000..2162289d8dd --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/Api/StoreApiInterfaceTest.php @@ -0,0 +1,151 @@ +genTestData('[a-z0-9]+'); + $path = str_replace($pattern, $data, $path); + + $crawler = $client->request('DELETE', $path); + } + + /** + * Test case for getInventory + * + * Returns pet inventories by status. + * + */ + public function testGetInventory() + { + $client = static::createClient(); + + $path = '/store/inventory'; + + $crawler = $client->request('GET', $path); + } + + /** + * Test case for getOrderById + * + * Find purchase order by ID. + * + */ + public function testGetOrderById() + { + $client = static::createClient(); + + $path = '/store/order/{orderId}'; + $pattern = '{orderId}'; + $data = $this->genTestData('\d+'); + $path = str_replace($pattern, $data, $path); + + $crawler = $client->request('GET', $path); + } + + /** + * Test case for placeOrder + * + * Place an order for a pet. + * + */ + public function testPlaceOrder() + { + $client = static::createClient(); + + $path = '/store/order'; + + $crawler = $client->request('POST', $path); + } + + protected function genTestData($regexp) + { + $grammar = new \Hoa\File\Read('hoa://Library/Regex/Grammar.pp'); + $compiler = \Hoa\Compiler\Llk\Llk::load($grammar); + $ast = $compiler->parse($regexp); + $generator = new \Hoa\Regex\Visitor\Isotropic(new \Hoa\Math\Sampler\Random()); + + return $generator->visit($ast); + } +} diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/Api/UserApiInterfaceTest.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/Api/UserApiInterfaceTest.php new file mode 100644 index 00000000000..9074d020f30 --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/Api/UserApiInterfaceTest.php @@ -0,0 +1,214 @@ +request('POST', $path); + } + + /** + * Test case for createUsersWithArrayInput + * + * Creates list of users with given input array. + * + */ + public function testCreateUsersWithArrayInput() + { + $client = static::createClient(); + + $path = '/user/createWithArray'; + + $crawler = $client->request('POST', $path); + } + + /** + * Test case for createUsersWithListInput + * + * Creates list of users with given input array. + * + */ + public function testCreateUsersWithListInput() + { + $client = static::createClient(); + + $path = '/user/createWithList'; + + $crawler = $client->request('POST', $path); + } + + /** + * Test case for deleteUser + * + * Delete user. + * + */ + public function testDeleteUser() + { + $client = static::createClient(); + + $path = '/user/{username}'; + $pattern = '{username}'; + $data = $this->genTestData('[a-z0-9]+'); + $path = str_replace($pattern, $data, $path); + + $crawler = $client->request('DELETE', $path); + } + + /** + * Test case for getUserByName + * + * Get user by user name. + * + */ + public function testGetUserByName() + { + $client = static::createClient(); + + $path = '/user/{username}'; + $pattern = '{username}'; + $data = $this->genTestData('[a-z0-9]+'); + $path = str_replace($pattern, $data, $path); + + $crawler = $client->request('GET', $path); + } + + /** + * Test case for loginUser + * + * Logs user into the system. + * + */ + public function testLoginUser() + { + $client = static::createClient(); + + $path = '/user/login'; + + $crawler = $client->request('GET', $path); + } + + /** + * Test case for logoutUser + * + * Logs out current logged in user session. + * + */ + public function testLogoutUser() + { + $client = static::createClient(); + + $path = '/user/logout'; + + $crawler = $client->request('GET', $path); + } + + /** + * Test case for updateUser + * + * Updated user. + * + */ + public function testUpdateUser() + { + $client = static::createClient(); + + $path = '/user/{username}'; + $pattern = '{username}'; + $data = $this->genTestData('[a-z0-9]+'); + $path = str_replace($pattern, $data, $path); + + $crawler = $client->request('PUT', $path); + } + + protected function genTestData($regexp) + { + $grammar = new \Hoa\File\Read('hoa://Library/Regex/Grammar.pp'); + $compiler = \Hoa\Compiler\Llk\Llk::load($grammar); + $ast = $compiler->parse($regexp); + $generator = new \Hoa\Regex\Visitor\Isotropic(new \Hoa\Math\Sampler\Random()); + + return $generator->visit($ast); + } +} diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/AppKernel.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/AppKernel.php new file mode 100644 index 00000000000..631690bc978 --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/AppKernel.php @@ -0,0 +1,21 @@ +load(__DIR__.'/test_config.yml'); + } +} diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/Model/ApiResponseTest.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/Model/ApiResponseTest.php new file mode 100644 index 00000000000..47970cb5c0b --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/Model/ApiResponseTest.php @@ -0,0 +1,101 @@ +=5.4", + "ext-curl": "*", + "ext-json": "*", + "ext-mbstring": "*", + "symfony/validator": "*", + "jms/serializer-bundle": "*", + "symfony/framework-bundle": "^2.3|^3.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.8", + "satooshi/php-coveralls": "~1.0", + "squizlabs/php_codesniffer": "~2.6", + "friendsofphp/php-cs-fixer": "~1.12", + "symfony/browser-kit": "*", + "hoa/regex": "~1.0" + }, + "autoload": { + "psr-4": { "Swagger\\Server\\" : "./" } + } +} diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/git_push.sh b/samples/server/petstore/php-symfony/SymfonyBundle-php/git_push.sh new file mode 100644 index 00000000000..792320114fb --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git 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/samples/server/petstore/php-symfony/SymfonyBundle-php/phpunit.xml.dist b/samples/server/petstore/php-symfony/SymfonyBundle-php/phpunit.xml.dist new file mode 100644 index 00000000000..ec07d2081c9 --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/phpunit.xml.dist @@ -0,0 +1,25 @@ + + + + + ./Tests/Api + ./Tests/Model + + + + + + + + + + ././Api + ././Model + + + diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/pom.xml b/samples/server/petstore/php-symfony/SymfonyBundle-php/pom.xml new file mode 100644 index 00000000000..614b3d33f98 --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/pom.xml @@ -0,0 +1,57 @@ + + 4.0.0 + com.penneo + PhpSymfonyPetstoreServerTests + pom + 1.0-SNAPSHOT + PHP Symfony Swagger Petstore Server + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + bundle-install + pre-integration-test + + exec + + + composer + + install + + + + + bundle-test + integration-test + + exec + + + vendor/bin/phpunit + + + + + + + + diff --git a/samples/server/petstore/restbed/model/Order.cpp b/samples/server/petstore/restbed/model/Order.cpp index cf34ceb4d1e..ae0888a7f96 100644 --- a/samples/server/petstore/restbed/model/Order.cpp +++ b/samples/server/petstore/restbed/model/Order.cpp @@ -110,7 +110,7 @@ void Order::setStatus(std::string value) { m_Status = value; } -bool Order::getComplete() const +bool Order::isComplete() const { return m_Complete; } diff --git a/samples/server/petstore/restbed/model/Order.h b/samples/server/petstore/restbed/model/Order.h index 88d9d77eee4..4c44b06faeb 100644 --- a/samples/server/petstore/restbed/model/Order.h +++ b/samples/server/petstore/restbed/model/Order.h @@ -72,7 +72,7 @@ public: /// /// /// - bool getComplete() const; + bool isComplete() const; void setComplete(bool value); protected: diff --git a/samples/server/petstore/rust-server/.cargo/config b/samples/server/petstore/rust-server/.cargo/config new file mode 100644 index 00000000000..b8acc9c00c8 --- /dev/null +++ b/samples/server/petstore/rust-server/.cargo/config @@ -0,0 +1,18 @@ +[build] +rustflags = [ + "-W", "missing_docs", # detects missing documentation for public members + + "-W", "trivial_casts", # detects trivial casts which could be removed + + "-W", "trivial_numeric_casts", # detects trivial casts of numeric types which could be removed + + "-W", "unsafe_code", # usage of `unsafe` code + + "-W", "unused_qualifications", # detects unnecessarily qualified names + + "-W", "unused_extern_crates", # extern crates that are never used + + "-W", "unused_import_braces", # unnecessary braces around an imported item + + "-D", "warnings", # all warnings should be denied +] diff --git a/samples/server/petstore/rust-server/.gitignore b/samples/server/petstore/rust-server/.gitignore new file mode 100644 index 00000000000..a9d37c560c6 --- /dev/null +++ b/samples/server/petstore/rust-server/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/samples/server/petstore/rust-server/.swagger-codegen-ignore b/samples/server/petstore/rust-server/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/rust-server/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/rust-server/.swagger-codegen/VERSION b/samples/server/petstore/rust-server/.swagger-codegen/VERSION new file mode 100644 index 00000000000..f9f7450d135 --- /dev/null +++ b/samples/server/petstore/rust-server/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-server/Cargo.toml b/samples/server/petstore/rust-server/Cargo.toml new file mode 100644 index 00000000000..da42d20714b --- /dev/null +++ b/samples/server/petstore/rust-server/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "petstore_api" +version = "1.0.0" +authors = ["apiteam@swagger.io"] + +[features] +default = ["client", "server"] +client = ["serde_json", "serde-xml-rs", "serde_ignored", "hyper", "hyper-openssl", "uuid", "multipart"] +server = ["serde_json", "serde-xml-rs", "serde_ignored", "hyper", "iron", "router", "bodyparser", "urlencoded", "uuid", "multipart"] + +[dependencies] +bodyparser = {version = "0.7", optional = true} +chrono = { version = "0.4", features = ["serde"] } +futures = "0.1" +hyper = {version = "0.10", optional = true} +hyper-openssl = {version = "0.2", optional = true } +iron = {version = "0.5", optional = true} +lazy_static = "0.2" +log = "0.3.0" +multipart = {version = "0.13", optional = true} +router = {version = "0.5", optional = true} +serde = "1.0" +serde_derive = "1.0" +serde_ignored = {version = "0.0.4", optional = true} +serde_json = {version = "1.0", optional = true} +swagger = "0.7" +urlencoded = {version = "0.5", optional = true} +uuid = {version = "0.5", optional = true, features = ["serde", "v4"]} +# ToDo: this should be updated to point at the official crate once +# https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream +serde-xml-rs = {git = "git://github.com/Metaswitch/serde-xml-rs.git" , branch = "master", optional = true} + +[dev-dependencies] +clap = "2.25" diff --git a/samples/server/petstore/rust-server/README.md b/samples/server/petstore/rust-server/README.md new file mode 100644 index 00000000000..16cfa50d246 --- /dev/null +++ b/samples/server/petstore/rust-server/README.md @@ -0,0 +1,84 @@ +# Rust API for 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: \" \\ + +## Overview +This client/server was generated by the [swagger-codegen] +(https://github.com/swagger-api/swagger-codegen) project. +By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. +- + +To see how to make this your own, look here: + +[README](https://github.com/swagger-api/swagger-codegen/blob/master/README.md) + +- API version: 1.0.0 +- Build date: 2017-10-30T02:13:46.477Z + +## Examples + +Run examples with: + +``` +cargo run --example +``` + +To pass in arguments to the examples, put them after `--`, for example: + +``` +cargo run --example client -- --help +``` + +### Running the server +To run the server, follow these simple steps: + +``` +cargo run --example server +``` + +### Running a client +To run a client, follow one of the following simple steps: + +``` +cargo run --example client TestSpecialTags +cargo run --example client FakeOuterBooleanSerialize +cargo run --example client FakeOuterCompositeSerialize +cargo run --example client FakeOuterNumberSerialize +cargo run --example client FakeOuterStringSerialize +cargo run --example client TestClientModel +cargo run --example client TestEndpointParameters +cargo run --example client TestEnumParameters +cargo run --example client TestInlineAdditionalProperties +cargo run --example client TestJsonFormData +cargo run --example client TestClassname +cargo run --example client AddPet +cargo run --example client DeletePet +cargo run --example client FindPetsByStatus +cargo run --example client FindPetsByTags +cargo run --example client GetPetById +cargo run --example client UpdatePet +cargo run --example client UpdatePetWithForm +cargo run --example client UploadFile +cargo run --example client DeleteOrder +cargo run --example client GetInventory +cargo run --example client GetOrderById +cargo run --example client PlaceOrder +cargo run --example client CreateUser +cargo run --example client CreateUsersWithArrayInput +cargo run --example client CreateUsersWithListInput +cargo run --example client DeleteUser +cargo run --example client GetUserByName +cargo run --example client LoginUser +cargo run --example client LogoutUser +cargo run --example client UpdateUser +``` + +### HTTPS +The examples can be run in HTTPS mode by passing in the flag `--https`, for example: + +``` +cargo run --example server -- --https +``` + +This will use the keys/certificates from the examples directory. Note that the server chain is signed with +`CN=localhost`. diff --git a/samples/server/petstore/rust-server/api/swagger.yaml b/samples/server/petstore/rust-server/api/swagger.yaml new file mode 100644 index 00000000000..dd09ede7a54 --- /dev/null +++ b/samples/server/petstore/rust-server/api/swagger.yaml @@ -0,0 +1,1975 @@ +--- +swagger: "2.0" +info: + description: "This spec is mainly for testing Petstore server and contains fake\ + \ endpoints, models. Please do not use this for any other purpose. Special characters:\ + \ \" \\" + version: "1.0.0" + title: "Swagger Petstore" + termsOfService: "http://swagger.io/terms/" + contact: + email: "apiteam@swagger.io" + license: + name: "Apache-2.0" + url: "http://www.apache.org/licenses/LICENSE-2.0.html" +host: "petstore.swagger.io:80" +basePath: "/v2" +tags: +- name: "pet" + description: "Everything about your Pets" + externalDocs: + description: "Find out more" + url: "http://swagger.io" +- name: "store" + description: "Access to Petstore orders" +- name: "user" + description: "Operations about user" + externalDocs: + description: "Find out more about our store" + url: "http://swagger.io" +schemes: +- "http" +paths: + /pet: + post: + tags: + - "pet" + summary: "Add a new pet to the store" + description: "" + operationId: "addPet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: true + schema: + $ref: "#/definitions/Pet" + uppercase_data_type: "PET" + refName: "Pet" + formatString: "{:?}" + example: "???" + model_key: "OuterBoolean" + uppercase_operation_id: "ADD_PET" + consumesXml: true + responses: + 405: + description: "Invalid input" + uppercase_operation_id: "ADD_PET" + uppercase_message: "INVALID_INPUT" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + operation_id: "add_pet" + uppercase_operation_id: "ADD_PET" + path: "/pet" + HttpMethod: "Post" + httpmethod: "post" + noClientExample: true + put: + tags: + - "pet" + summary: "Update an existing pet" + description: "" + operationId: "updatePet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: true + schema: + $ref: "#/definitions/Pet" + uppercase_data_type: "PET" + refName: "Pet" + formatString: "{:?}" + example: "???" + model_key: "OuterBoolean" + uppercase_operation_id: "UPDATE_PET" + consumesXml: true + responses: + 400: + description: "Invalid ID supplied" + uppercase_operation_id: "UPDATE_PET" + uppercase_message: "INVALID_ID_SUPPLIED" + 404: + description: "Pet not found" + uppercase_operation_id: "UPDATE_PET" + uppercase_message: "PET_NOT_FOUND" + 405: + description: "Validation exception" + uppercase_operation_id: "UPDATE_PET" + uppercase_message: "VALIDATION_EXCEPTION" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + operation_id: "update_pet" + uppercase_operation_id: "UPDATE_PET" + path: "/pet" + HttpMethod: "Put" + httpmethod: "put" + noClientExample: true + /pet/findByStatus: + get: + tags: + - "pet" + summary: "Finds Pets by status" + description: "Multiple status values can be provided with comma separated strings" + operationId: "findPetsByStatus" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "status" + in: "query" + description: "Status values that need to be considered for filter" + required: true + type: "array" + items: + type: "string" + enum: + - "available" + - "pending" + - "sold" + default: "available" + collectionFormat: "csv" + formatString: "{:?}" + example: "&Vec::new()" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + uppercase_operation_id: "FIND_PETS_BY_STATUS" + uppercase_message: "SUCCESSFUL_OPERATION" + uppercase_data_type: "VEC" + producesXml: true + 400: + description: "Invalid status value" + uppercase_operation_id: "FIND_PETS_BY_STATUS" + uppercase_message: "INVALID_STATUS_VALUE" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + operation_id: "find_pets_by_status" + uppercase_operation_id: "FIND_PETS_BY_STATUS" + path: "/pet/findByStatus" + HttpMethod: "Get" + httpmethod: "get" + /pet/findByTags: + get: + tags: + - "pet" + summary: "Finds Pets by tags" + description: "Multiple tags can be provided with comma separated strings. Use\ + \ tag1, tag2, tag3 for testing." + operationId: "findPetsByTags" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "tags" + in: "query" + description: "Tags to filter by" + required: true + type: "array" + items: + type: "string" + collectionFormat: "csv" + formatString: "{:?}" + example: "&Vec::new()" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + uppercase_operation_id: "FIND_PETS_BY_TAGS" + uppercase_message: "SUCCESSFUL_OPERATION" + uppercase_data_type: "VEC" + producesXml: true + 400: + description: "Invalid tag value" + uppercase_operation_id: "FIND_PETS_BY_TAGS" + uppercase_message: "INVALID_TAG_VALUE" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + deprecated: true + operation_id: "find_pets_by_tags" + uppercase_operation_id: "FIND_PETS_BY_TAGS" + path: "/pet/findByTags" + HttpMethod: "Get" + httpmethod: "get" + /pet/{petId}: + get: + tags: + - "pet" + summary: "Find pet by ID" + description: "Returns a single pet" + operationId: "getPetById" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "petId" + in: "path" + description: "ID of pet to return" + required: true + type: "integer" + format: "int64" + formatString: "{}" + example: "789" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Pet" + uppercase_operation_id: "GET_PET_BY_ID" + uppercase_message: "SUCCESSFUL_OPERATION" + uppercase_data_type: "PET" + producesXml: true + 400: + description: "Invalid ID supplied" + uppercase_operation_id: "GET_PET_BY_ID" + uppercase_message: "INVALID_ID_SUPPLIED" + 404: + description: "Pet not found" + uppercase_operation_id: "GET_PET_BY_ID" + uppercase_message: "PET_NOT_FOUND" + security: + - api_key: [] + operation_id: "get_pet_by_id" + uppercase_operation_id: "GET_PET_BY_ID" + path: "/pet/:petId" + HttpMethod: "Get" + httpmethod: "get" + post: + tags: + - "pet" + summary: "Updates a pet in the store with form data" + description: "" + operationId: "updatePetWithForm" + consumes: + - "application/x-www-form-urlencoded" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "petId" + in: "path" + description: "ID of pet that needs to be updated" + required: true + type: "integer" + format: "int64" + formatString: "{}" + example: "789" + - name: "name" + in: "formData" + description: "Updated name of the pet" + required: false + type: "string" + formatString: "{:?}" + example: "Some(\"name_example\".to_string())" + - name: "status" + in: "formData" + description: "Updated status of the pet" + required: false + type: "string" + formatString: "{:?}" + example: "Some(\"status_example\".to_string())" + responses: + 405: + description: "Invalid input" + uppercase_operation_id: "UPDATE_PET_WITH_FORM" + uppercase_message: "INVALID_INPUT" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + operation_id: "update_pet_with_form" + uppercase_operation_id: "UPDATE_PET_WITH_FORM" + path: "/pet/:petId" + HttpMethod: "Post" + httpmethod: "post" + delete: + tags: + - "pet" + summary: "Deletes a pet" + description: "" + operationId: "deletePet" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "api_key" + in: "header" + required: false + type: "string" + formatString: "{:?}" + example: "Some(\"api_key_example\".to_string())" + - name: "petId" + in: "path" + description: "Pet id to delete" + required: true + type: "integer" + format: "int64" + formatString: "{}" + example: "789" + responses: + 400: + description: "Invalid pet value" + uppercase_operation_id: "DELETE_PET" + uppercase_message: "INVALID_PET_VALUE" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + operation_id: "delete_pet" + uppercase_operation_id: "DELETE_PET" + path: "/pet/:petId" + HttpMethod: "Delete" + httpmethod: "delete" + /pet/{petId}/uploadImage: + post: + tags: + - "pet" + summary: "uploads an image" + description: "" + operationId: "uploadFile" + consumes: + - "multipart/form-data" + produces: + - "application/json" + parameters: + - name: "petId" + in: "path" + description: "ID of pet to update" + required: true + type: "integer" + format: "int64" + formatString: "{}" + example: "789" + - name: "additionalMetadata" + in: "formData" + description: "Additional data to pass to server" + required: false + type: "string" + formatString: "{:?}" + example: "Some(\"additional_metadata_example\".to_string())" + - name: "file" + in: "formData" + description: "file to upload" + required: false + type: "file" + formatString: "{:?}" + example: "Box::new(future::ok(Some(Box::new(stream::once(Ok(b\"hello\".to_vec())))\ + \ as Box + Send>))) as Box\ + \ + Send>" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/ApiResponse" + uppercase_operation_id: "UPLOAD_FILE" + uppercase_message: "SUCCESSFUL_OPERATION" + uppercase_data_type: "APIRESPONSE" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + operation_id: "upload_file" + uppercase_operation_id: "UPLOAD_FILE" + path: "/pet/:petId/uploadImage" + HttpMethod: "Post" + httpmethod: "post" + hasFile: true + /store/inventory: + get: + tags: + - "store" + summary: "Returns pet inventories by status" + description: "Returns a map of status codes to quantities" + operationId: "getInventory" + produces: + - "application/json" + parameters: [] + responses: + 200: + description: "successful operation" + schema: + type: "object" + additionalProperties: + type: "integer" + format: "int32" + uppercase_operation_id: "GET_INVENTORY" + uppercase_message: "SUCCESSFUL_OPERATION" + uppercase_data_type: "HASHMAP" + security: + - api_key: [] + operation_id: "get_inventory" + uppercase_operation_id: "GET_INVENTORY" + path: "/store/inventory" + HttpMethod: "Get" + httpmethod: "get" + /store/order: + post: + tags: + - "store" + summary: "Place an order for a pet" + description: "" + operationId: "placeOrder" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "order placed for purchasing the pet" + required: true + schema: + $ref: "#/definitions/Order" + uppercase_data_type: "ORDER" + refName: "Order" + formatString: "{:?}" + example: "???" + model_key: "OuterBoolean" + uppercase_operation_id: "PLACE_ORDER" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + uppercase_operation_id: "PLACE_ORDER" + uppercase_message: "SUCCESSFUL_OPERATION" + uppercase_data_type: "ORDER" + producesXml: true + 400: + description: "Invalid Order" + uppercase_operation_id: "PLACE_ORDER" + uppercase_message: "INVALID_ORDER" + operation_id: "place_order" + uppercase_operation_id: "PLACE_ORDER" + path: "/store/order" + HttpMethod: "Post" + httpmethod: "post" + noClientExample: true + /store/order/{order_id}: + get: + tags: + - "store" + summary: "Find purchase order by ID" + description: "For valid response try integer IDs with value <= 5 or > 10. Other\ + \ values will generated exceptions" + operationId: "getOrderById" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "order_id" + in: "path" + description: "ID of pet that needs to be fetched" + required: true + type: "integer" + maximum: 5 + minimum: 1 + format: "int64" + formatString: "{}" + example: "789" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + uppercase_operation_id: "GET_ORDER_BY_ID" + uppercase_message: "SUCCESSFUL_OPERATION" + uppercase_data_type: "ORDER" + producesXml: true + 400: + description: "Invalid ID supplied" + uppercase_operation_id: "GET_ORDER_BY_ID" + uppercase_message: "INVALID_ID_SUPPLIED" + 404: + description: "Order not found" + uppercase_operation_id: "GET_ORDER_BY_ID" + uppercase_message: "ORDER_NOT_FOUND" + operation_id: "get_order_by_id" + uppercase_operation_id: "GET_ORDER_BY_ID" + path: "/store/order/:order_id" + HttpMethod: "Get" + httpmethod: "get" + delete: + tags: + - "store" + summary: "Delete purchase order by ID" + description: "For valid response try integer IDs with value < 1000. Anything\ + \ above 1000 or nonintegers will generate API errors" + operationId: "deleteOrder" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "order_id" + in: "path" + description: "ID of the order that needs to be deleted" + required: true + type: "string" + formatString: "\\\"{}\\\"" + example: "\"order_id_example\".to_string()" + responses: + 400: + description: "Invalid ID supplied" + uppercase_operation_id: "DELETE_ORDER" + uppercase_message: "INVALID_ID_SUPPLIED" + 404: + description: "Order not found" + uppercase_operation_id: "DELETE_ORDER" + uppercase_message: "ORDER_NOT_FOUND" + operation_id: "delete_order" + uppercase_operation_id: "DELETE_ORDER" + path: "/store/order/:order_id" + HttpMethod: "Delete" + httpmethod: "delete" + /user: + post: + tags: + - "user" + summary: "Create user" + description: "This can only be done by the logged in user." + operationId: "createUser" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Created user object" + required: true + schema: + $ref: "#/definitions/User" + uppercase_data_type: "USER" + refName: "User" + formatString: "{:?}" + example: "???" + model_key: "OuterBoolean" + uppercase_operation_id: "CREATE_USER" + responses: + default: + description: "successful operation" + uppercase_operation_id: "CREATE_USER" + uppercase_message: "SUCCESSFUL_OPERATION" + operation_id: "create_user" + uppercase_operation_id: "CREATE_USER" + path: "/user" + HttpMethod: "Post" + httpmethod: "post" + noClientExample: true + /user/createWithArray: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "createUsersWithArrayInput" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: true + schema: + type: "array" + items: + $ref: "#/definitions/User" + formatString: "{:?}" + example: "&Vec::new()" + model_key: "OuterBoolean" + uppercase_operation_id: "CREATE_USERS_WITH_ARRAY_INPUT" + responses: + default: + description: "successful operation" + uppercase_operation_id: "CREATE_USERS_WITH_ARRAY_INPUT" + uppercase_message: "SUCCESSFUL_OPERATION" + operation_id: "create_users_with_array_input" + uppercase_operation_id: "CREATE_USERS_WITH_ARRAY_INPUT" + path: "/user/createWithArray" + HttpMethod: "Post" + httpmethod: "post" + /user/createWithList: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "createUsersWithListInput" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: true + schema: + type: "array" + items: + $ref: "#/definitions/User" + formatString: "{:?}" + example: "&Vec::new()" + model_key: "OuterBoolean" + uppercase_operation_id: "CREATE_USERS_WITH_LIST_INPUT" + responses: + default: + description: "successful operation" + uppercase_operation_id: "CREATE_USERS_WITH_LIST_INPUT" + uppercase_message: "SUCCESSFUL_OPERATION" + operation_id: "create_users_with_list_input" + uppercase_operation_id: "CREATE_USERS_WITH_LIST_INPUT" + path: "/user/createWithList" + HttpMethod: "Post" + httpmethod: "post" + /user/login: + get: + tags: + - "user" + summary: "Logs user into the system" + description: "" + operationId: "loginUser" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "username" + in: "query" + description: "The user name for login" + required: true + type: "string" + formatString: "\\\"{}\\\"" + example: "\"username_example\".to_string()" + - name: "password" + in: "query" + description: "The password for login in clear text" + required: true + type: "string" + formatString: "\\\"{}\\\"" + example: "\"password_example\".to_string()" + responses: + 200: + description: "successful operation" + schema: + type: "string" + headers: + X-Rate-Limit: + type: "integer" + format: "int32" + description: "calls per hour allowed by the user" + X-Expires-After: + type: "string" + format: "date-time" + description: "date in UTC when toekn expires" + uppercase_operation_id: "LOGIN_USER" + uppercase_message: "SUCCESSFUL_OPERATION" + uppercase_data_type: "STRING" + producesXml: true + 400: + description: "Invalid username/password supplied" + uppercase_operation_id: "LOGIN_USER" + uppercase_message: "INVALID_USERNAME" + operation_id: "login_user" + uppercase_operation_id: "LOGIN_USER" + path: "/user/login" + HttpMethod: "Get" + httpmethod: "get" + /user/logout: + get: + tags: + - "user" + summary: "Logs out current logged in user session" + description: "" + operationId: "logoutUser" + produces: + - "application/xml" + - "application/json" + parameters: [] + responses: + default: + description: "successful operation" + uppercase_operation_id: "LOGOUT_USER" + uppercase_message: "SUCCESSFUL_OPERATION" + operation_id: "logout_user" + uppercase_operation_id: "LOGOUT_USER" + path: "/user/logout" + HttpMethod: "Get" + httpmethod: "get" + /user/{username}: + get: + tags: + - "user" + summary: "Get user by user name" + description: "" + operationId: "getUserByName" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be fetched. Use user1 for testing. " + required: true + type: "string" + formatString: "\\\"{}\\\"" + example: "\"username_example\".to_string()" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/User" + uppercase_operation_id: "GET_USER_BY_NAME" + uppercase_message: "SUCCESSFUL_OPERATION" + uppercase_data_type: "USER" + producesXml: true + 400: + description: "Invalid username supplied" + uppercase_operation_id: "GET_USER_BY_NAME" + uppercase_message: "INVALID_USERNAME_SUPPLIED" + 404: + description: "User not found" + uppercase_operation_id: "GET_USER_BY_NAME" + uppercase_message: "USER_NOT_FOUND" + operation_id: "get_user_by_name" + uppercase_operation_id: "GET_USER_BY_NAME" + path: "/user/:username" + HttpMethod: "Get" + httpmethod: "get" + put: + tags: + - "user" + summary: "Updated user" + description: "This can only be done by the logged in user." + operationId: "updateUser" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "username" + in: "path" + description: "name that need to be deleted" + required: true + type: "string" + formatString: "\\\"{}\\\"" + example: "\"username_example\".to_string()" + - in: "body" + name: "body" + description: "Updated user object" + required: true + schema: + $ref: "#/definitions/User" + uppercase_data_type: "USER" + refName: "User" + formatString: "{:?}" + example: "???" + model_key: "OuterBoolean" + uppercase_operation_id: "UPDATE_USER" + responses: + 400: + description: "Invalid user supplied" + uppercase_operation_id: "UPDATE_USER" + uppercase_message: "INVALID_USER_SUPPLIED" + 404: + description: "User not found" + uppercase_operation_id: "UPDATE_USER" + uppercase_message: "USER_NOT_FOUND" + operation_id: "update_user" + uppercase_operation_id: "UPDATE_USER" + path: "/user/:username" + HttpMethod: "Put" + httpmethod: "put" + noClientExample: true + delete: + tags: + - "user" + summary: "Delete user" + description: "This can only be done by the logged in user." + operationId: "deleteUser" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be deleted" + required: true + type: "string" + formatString: "\\\"{}\\\"" + example: "\"username_example\".to_string()" + responses: + 400: + description: "Invalid username supplied" + uppercase_operation_id: "DELETE_USER" + uppercase_message: "INVALID_USERNAME_SUPPLIED" + 404: + description: "User not found" + uppercase_operation_id: "DELETE_USER" + uppercase_message: "USER_NOT_FOUND" + operation_id: "delete_user" + uppercase_operation_id: "DELETE_USER" + path: "/user/:username" + HttpMethod: "Delete" + httpmethod: "delete" + /fake_classname_test: + patch: + tags: + - "fake_classname_tags 123#$%^" + summary: "To test class name in snake case" + operationId: "testClassname" + consumes: + - "application/json" + produces: + - "application/json" + parameters: + - in: "body" + name: "body" + description: "client model" + required: true + schema: + $ref: "#/definitions/Client" + uppercase_data_type: "CLIENT" + refName: "Client" + formatString: "{:?}" + example: "???" + model_key: "OuterBoolean" + uppercase_operation_id: "TEST_CLASSNAME" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Client" + uppercase_operation_id: "TEST_CLASSNAME" + uppercase_message: "SUCCESSFUL_OPERATION" + uppercase_data_type: "CLIENT" + security: + - api_key_query: [] + operation_id: "test_classname" + uppercase_operation_id: "TEST_CLASSNAME" + path: "/fake_classname_test" + HttpMethod: "Patch" + httpmethod: "patch" + noClientExample: true + /fake: + get: + tags: + - "fake" + summary: "To test enum parameters" + description: "To test enum parameters" + operationId: "testEnumParameters" + consumes: + - "*/*" + produces: + - "*/*" + parameters: + - name: "enum_form_string_array" + in: "formData" + description: "Form parameter enum test (string array)" + required: false + type: "array" + items: + type: "string" + enum: + - ">" + - "$" + default: "$" + formatString: "{:?}" + example: "Some(&Vec::new())" + - name: "enum_form_string" + in: "formData" + description: "Form parameter enum test (string)" + required: false + type: "string" + default: "-efg" + enum: + - "_abc" + - "-efg" + - "(xyz)" + formatString: "{:?}" + example: "Some(\"enum_form_string_example\".to_string())" + - name: "enum_header_string_array" + in: "header" + description: "Header parameter enum test (string array)" + required: false + type: "array" + items: + type: "string" + enum: + - ">" + - "$" + default: "$" + formatString: "{:?}" + example: "Some(&Vec::new())" + - name: "enum_header_string" + in: "header" + description: "Header parameter enum test (string)" + required: false + type: "string" + default: "-efg" + enum: + - "_abc" + - "-efg" + - "(xyz)" + formatString: "{:?}" + example: "Some(\"enum_header_string_example\".to_string())" + - name: "enum_query_string_array" + in: "query" + description: "Query parameter enum test (string array)" + required: false + type: "array" + items: + type: "string" + enum: + - ">" + - "$" + default: "$" + formatString: "{:?}" + example: "Some(&Vec::new())" + - name: "enum_query_string" + in: "query" + description: "Query parameter enum test (string)" + required: false + type: "string" + default: "-efg" + enum: + - "_abc" + - "-efg" + - "(xyz)" + formatString: "{:?}" + example: "Some(\"enum_query_string_example\".to_string())" + - name: "enum_query_integer" + in: "query" + description: "Query parameter enum test (double)" + required: false + type: "integer" + format: "int32" + enum: + - 1 + - -2 + formatString: "{:?}" + example: "Some(56)" + - name: "enum_query_double" + in: "formData" + description: "Query parameter enum test (double)" + required: false + type: "number" + format: "double" + enum: + - 1.1 + - -1.2 + formatString: "{:?}" + example: "Some(1.2)" + responses: + 400: + description: "Invalid request" + uppercase_operation_id: "TEST_ENUM_PARAMETERS" + uppercase_message: "INVALID_REQUEST" + 404: + description: "Not found" + uppercase_operation_id: "TEST_ENUM_PARAMETERS" + uppercase_message: "NOT_FOUND" + operation_id: "test_enum_parameters" + uppercase_operation_id: "TEST_ENUM_PARAMETERS" + path: "/fake" + HttpMethod: "Get" + httpmethod: "get" + post: + tags: + - "fake" + summary: "Fake endpoint for testing various parameters\n假端點\n偽のエンドポイント\n가짜 엔\ + 드 포인트\n" + description: "Fake endpoint for testing various parameters\n假端點\n偽のエンドポイント\n\ + 가짜 엔드 포인트\n" + operationId: "testEndpointParameters" + consumes: + - "application/xml; charset=utf-8" + - "application/json; charset=utf-8" + produces: + - "application/xml; charset=utf-8" + - "application/json; charset=utf-8" + parameters: + - name: "integer" + in: "formData" + description: "None" + required: false + type: "integer" + maximum: 100 + minimum: 10 + formatString: "{:?}" + example: "Some(56)" + - name: "int32" + in: "formData" + description: "None" + required: false + type: "integer" + maximum: 200 + minimum: 20 + format: "int32" + formatString: "{:?}" + example: "Some(56)" + - name: "int64" + in: "formData" + description: "None" + required: false + type: "integer" + format: "int64" + formatString: "{:?}" + example: "Some(789)" + - name: "number" + in: "formData" + description: "None" + required: true + type: "number" + maximum: 543.2 + minimum: 32.1 + formatString: "{}" + example: "3.4" + - name: "float" + in: "formData" + description: "None" + required: false + type: "number" + maximum: 987.6 + format: "float" + formatString: "{:?}" + example: "Some(3.4)" + - name: "double" + in: "formData" + description: "None" + required: true + type: "number" + maximum: 123.4 + minimum: 67.8 + format: "double" + formatString: "{}" + example: "1.2" + - name: "string" + in: "formData" + description: "None" + required: false + type: "string" + pattern: "/[a-z]/i" + formatString: "{:?}" + example: "Some(\"string_example\".to_string())" + - name: "pattern_without_delimiter" + in: "formData" + description: "None" + required: true + type: "string" + pattern: "^[A-Z].*" + formatString: "\\\"{}\\\"" + example: "\"pattern_without_delimiter_example\".to_string()" + - name: "byte" + in: "formData" + description: "None" + required: true + type: "string" + format: "byte" + formatString: "\\\"{:?}\\\"" + example: "swagger::ByteArray(\"byte_example\".to_string().into_bytes())" + - name: "binary" + in: "formData" + description: "None" + required: false + type: "string" + format: "binary" + formatString: "{:?}" + example: "Some(swagger::ByteArray(Vec::from(\"B\")))" + - name: "date" + in: "formData" + description: "None" + required: false + type: "string" + format: "date" + formatString: "{:?}" + example: "None" + - name: "dateTime" + in: "formData" + description: "None" + required: false + type: "string" + format: "date-time" + formatString: "{:?}" + example: "None" + - name: "password" + in: "formData" + description: "None" + required: false + type: "string" + maxLength: 64 + minLength: 10 + format: "password" + formatString: "{:?}" + example: "Some(\"password_example\".to_string())" + - name: "callback" + in: "formData" + description: "None" + required: false + type: "string" + formatString: "{:?}" + example: "Some(\"callback_example\".to_string())" + responses: + 400: + description: "Invalid username supplied" + uppercase_operation_id: "TEST_ENDPOINT_PARAMETERS" + uppercase_message: "INVALID_USERNAME_SUPPLIED" + 404: + description: "User not found" + uppercase_operation_id: "TEST_ENDPOINT_PARAMETERS" + uppercase_message: "USER_NOT_FOUND" + security: + - http_basic_test: [] + operation_id: "test_endpoint_parameters" + uppercase_operation_id: "TEST_ENDPOINT_PARAMETERS" + path: "/fake" + HttpMethod: "Post" + httpmethod: "post" + patch: + tags: + - "fake" + summary: "To test \"client\" model" + description: "To test \"client\" model" + operationId: "testClientModel" + consumes: + - "application/json" + produces: + - "application/json" + parameters: + - in: "body" + name: "body" + description: "client model" + required: true + schema: + $ref: "#/definitions/Client" + uppercase_data_type: "CLIENT" + refName: "Client" + formatString: "{:?}" + example: "???" + model_key: "OuterBoolean" + uppercase_operation_id: "TEST_CLIENT_MODEL" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Client" + uppercase_operation_id: "TEST_CLIENT_MODEL" + uppercase_message: "SUCCESSFUL_OPERATION" + uppercase_data_type: "CLIENT" + operation_id: "test_client_model" + uppercase_operation_id: "TEST_CLIENT_MODEL" + path: "/fake" + HttpMethod: "Patch" + httpmethod: "patch" + noClientExample: true + /fake/outer/number: + post: + tags: + - "fake" + description: "Test serialization of outer number types" + operationId: "fakeOuterNumberSerialize" + parameters: + - in: "body" + name: "body" + description: "Input number as post body" + required: false + schema: + $ref: "#/definitions/OuterNumber" + uppercase_data_type: "OUTERNUMBER" + refName: "OuterNumber" + formatString: "{:?}" + example: "None" + model_key: "OuterBoolean" + uppercase_operation_id: "FAKE_OUTER_NUMBER_SERIALIZE" + responses: + 200: + description: "Output number" + schema: + $ref: "#/definitions/OuterNumber" + uppercase_operation_id: "FAKE_OUTER_NUMBER_SERIALIZE" + uppercase_message: "OUTPUT_NUMBER" + uppercase_data_type: "OUTERNUMBER" + operation_id: "fake_outer_number_serialize" + uppercase_operation_id: "FAKE_OUTER_NUMBER_SERIALIZE" + path: "/fake/outer/number" + HttpMethod: "Post" + httpmethod: "post" + /fake/outer/string: + post: + tags: + - "fake" + description: "Test serialization of outer string types" + operationId: "fakeOuterStringSerialize" + parameters: + - in: "body" + name: "body" + description: "Input string as post body" + required: false + schema: + $ref: "#/definitions/OuterString" + uppercase_data_type: "OUTERSTRING" + refName: "OuterString" + formatString: "{:?}" + example: "None" + model_key: "OuterBoolean" + uppercase_operation_id: "FAKE_OUTER_STRING_SERIALIZE" + responses: + 200: + description: "Output string" + schema: + $ref: "#/definitions/OuterString" + uppercase_operation_id: "FAKE_OUTER_STRING_SERIALIZE" + uppercase_message: "OUTPUT_STRING" + uppercase_data_type: "OUTERSTRING" + operation_id: "fake_outer_string_serialize" + uppercase_operation_id: "FAKE_OUTER_STRING_SERIALIZE" + path: "/fake/outer/string" + HttpMethod: "Post" + httpmethod: "post" + /fake/outer/boolean: + post: + tags: + - "fake" + description: "Test serialization of outer boolean types" + operationId: "fakeOuterBooleanSerialize" + parameters: + - in: "body" + name: "body" + description: "Input boolean as post body" + required: false + schema: + $ref: "#/definitions/OuterBoolean" + uppercase_data_type: "OUTERBOOLEAN" + refName: "OuterBoolean" + formatString: "{:?}" + example: "None" + model_key: "OuterBoolean" + uppercase_operation_id: "FAKE_OUTER_BOOLEAN_SERIALIZE" + responses: + 200: + description: "Output boolean" + schema: + $ref: "#/definitions/OuterBoolean" + uppercase_operation_id: "FAKE_OUTER_BOOLEAN_SERIALIZE" + uppercase_message: "OUTPUT_BOOLEAN" + uppercase_data_type: "OUTERBOOLEAN" + operation_id: "fake_outer_boolean_serialize" + uppercase_operation_id: "FAKE_OUTER_BOOLEAN_SERIALIZE" + path: "/fake/outer/boolean" + HttpMethod: "Post" + httpmethod: "post" + /fake/outer/composite: + post: + tags: + - "fake" + description: "Test serialization of object with outer number type" + operationId: "fakeOuterCompositeSerialize" + parameters: + - in: "body" + name: "body" + description: "Input composite as post body" + required: false + schema: + $ref: "#/definitions/OuterComposite" + uppercase_data_type: "OUTERCOMPOSITE" + refName: "OuterComposite" + formatString: "{:?}" + example: "None" + model_key: "OuterBoolean" + uppercase_operation_id: "FAKE_OUTER_COMPOSITE_SERIALIZE" + responses: + 200: + description: "Output composite" + schema: + $ref: "#/definitions/OuterComposite" + uppercase_operation_id: "FAKE_OUTER_COMPOSITE_SERIALIZE" + uppercase_message: "OUTPUT_COMPOSITE" + uppercase_data_type: "OUTERCOMPOSITE" + operation_id: "fake_outer_composite_serialize" + uppercase_operation_id: "FAKE_OUTER_COMPOSITE_SERIALIZE" + path: "/fake/outer/composite" + HttpMethod: "Post" + httpmethod: "post" + /fake/jsonFormData: + get: + tags: + - "fake" + summary: "test json serialization of form data" + description: "" + operationId: "testJsonFormData" + consumes: + - "application/json" + parameters: + - name: "param" + in: "formData" + description: "field1" + required: true + type: "string" + formatString: "\\\"{}\\\"" + example: "\"param_example\".to_string()" + - name: "param2" + in: "formData" + description: "field2" + required: true + type: "string" + formatString: "\\\"{}\\\"" + example: "\"param2_example\".to_string()" + responses: + 200: + description: "successful operation" + uppercase_operation_id: "TEST_JSON_FORM_DATA" + uppercase_message: "SUCCESSFUL_OPERATION" + operation_id: "test_json_form_data" + uppercase_operation_id: "TEST_JSON_FORM_DATA" + path: "/fake/jsonFormData" + HttpMethod: "Get" + httpmethod: "get" + /fake/inline-additionalProperties: + post: + tags: + - "fake" + summary: "test inline additionalProperties" + description: "" + operationId: "testInlineAdditionalProperties" + consumes: + - "application/json" + parameters: + - in: "body" + name: "param" + description: "request body" + required: true + schema: + type: "object" + additionalProperties: + type: "string" + upperCaseName: "PARAM" + refName: null + formatString: "{:?}" + example: "???" + model_key: "OuterBoolean" + uppercase_operation_id: "TEST_INLINE_ADDITIONAL_PROPERTIES" + responses: + 200: + description: "successful operation" + uppercase_operation_id: "TEST_INLINE_ADDITIONAL_PROPERTIES" + uppercase_message: "SUCCESSFUL_OPERATION" + operation_id: "test_inline_additional_properties" + uppercase_operation_id: "TEST_INLINE_ADDITIONAL_PROPERTIES" + path: "/fake/inline-additionalProperties" + HttpMethod: "Post" + httpmethod: "post" + noClientExample: true + /another-fake/dummy: + patch: + tags: + - "$another-fake?" + summary: "To test special tags" + description: "To test special tags" + operationId: "test_special_tags" + consumes: + - "application/json" + produces: + - "application/json" + parameters: + - in: "body" + name: "body" + description: "client model" + required: true + schema: + $ref: "#/definitions/Client" + uppercase_data_type: "CLIENT" + refName: "Client" + formatString: "{:?}" + example: "???" + model_key: "OuterBoolean" + uppercase_operation_id: "TEST_SPECIAL_TAGS" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Client" + uppercase_operation_id: "TEST_SPECIAL_TAGS" + uppercase_message: "SUCCESSFUL_OPERATION" + uppercase_data_type: "CLIENT" + operation_id: "test_special_tags" + uppercase_operation_id: "TEST_SPECIAL_TAGS" + path: "/another-fake/dummy" + HttpMethod: "Patch" + httpmethod: "patch" + noClientExample: true +securityDefinitions: + petstore_auth: + type: "oauth2" + authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" + flow: "implicit" + scopes: + write:pets: "modify pets in your account" + read:pets: "read your pets" + api_key: + type: "apiKey" + name: "api_key" + in: "header" + api_key_query: + type: "apiKey" + name: "api_key_query" + in: "query" + http_basic_test: + type: "basic" +definitions: + Order: + type: "object" + properties: + id: + type: "integer" + format: "int64" + petId: + type: "integer" + format: "int64" + quantity: + type: "integer" + format: "int32" + shipDate: + type: "string" + format: "date-time" + status: + type: "string" + description: "Order Status" + enum: + - "placed" + - "approved" + - "delivered" + complete: + type: "boolean" + default: false + example: + petId: 6 + quantity: 1 + id: 0 + shipDate: "2000-01-23T04:56:07.000+00:00" + complete: false + status: "placed" + xml: + name: "Order" + upperCaseName: "ORDER" + Category: + type: "object" + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + example: + name: "name" + id: 6 + xml: + name: "Category" + upperCaseName: "CATEGORY" + User: + type: "object" + properties: + id: + type: "integer" + format: "int64" + x-is-unique: true + username: + type: "string" + firstName: + type: "string" + lastName: + type: "string" + email: + type: "string" + password: + type: "string" + phone: + type: "string" + userStatus: + type: "integer" + format: "int32" + description: "User Status" + example: + firstName: "firstName" + lastName: "lastName" + password: "password" + userStatus: 6 + phone: "phone" + id: 0 + email: "email" + username: "username" + xml: + name: "User" + upperCaseName: "USER" + Tag: + type: "object" + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + example: + name: "name" + id: 1 + xml: + name: "Tag" + upperCaseName: "TAG" + Pet: + type: "object" + required: + - "name" + - "photoUrls" + properties: + id: + type: "integer" + format: "int64" + x-is-unique: true + category: + $ref: "#/definitions/Category" + name: + type: "string" + example: "doggie" + photoUrls: + type: "array" + xml: + name: "photoUrl" + wrapped: true + items: + type: "string" + tags: + type: "array" + xml: + name: "tag" + wrapped: true + items: + $ref: "#/definitions/Tag" + status: + type: "string" + description: "pet status in the store" + enum: + - "available" + - "pending" + - "sold" + example: + photoUrls: + - "photoUrls" + - "photoUrls" + name: "doggie" + id: 0 + category: + name: "name" + id: 6 + tags: + - name: "name" + id: 1 + - name: "name" + id: 1 + status: "available" + xml: + name: "Pet" + upperCaseName: "PET" + ApiResponse: + type: "object" + properties: + code: + type: "integer" + format: "int32" + type: + type: "string" + message: + type: "string" + example: + code: 0 + type: "type" + message: "message" + upperCaseName: "APIRESPONSE" + $special[model.name]: + properties: + $special[property.name]: + type: "integer" + format: "int64" + xml: + name: "$special[model.name]" + upperCaseName: "$SPECIAL[MODEL.NAME]" + Return: + properties: + return: + type: "integer" + format: "int32" + description: "Model for testing reserved words" + xml: + name: "Return" + upperCaseName: "RETURN" + Name: + required: + - "name" + properties: + name: + type: "integer" + format: "int32" + snake_case: + type: "integer" + format: "int32" + readOnly: true + property: + type: "string" + 123Number: + type: "integer" + readOnly: true + description: "Model for testing model name same as property name" + xml: + name: "Name" + upperCaseName: "NAME" + 200_response: + properties: + name: + type: "integer" + format: "int32" + class: + type: "string" + description: "Model for testing model name starting with number" + xml: + name: "Name" + upperCaseName: "200_RESPONSE" + ClassModel: + properties: + _class: + type: "string" + description: "Model for testing model with \"_class\" property" + upperCaseName: "CLASSMODEL" + Dog: + allOf: + - $ref: "#/definitions/Animal" + - type: "object" + properties: + breed: + type: "string" + upperCaseName: "DOG" + Cat: + allOf: + - $ref: "#/definitions/Animal" + - type: "object" + properties: + declawed: + type: "boolean" + upperCaseName: "CAT" + Animal: + type: "object" + required: + - "className" + discriminator: "className" + properties: + className: + type: "string" + color: + type: "string" + default: "red" + upperCaseName: "ANIMAL" + AnimalFarm: + type: "array" + items: + $ref: "#/definitions/Animal" + upperCaseName: "ANIMALFARM" + format_test: + type: "object" + required: + - "byte" + - "date" + - "number" + - "password" + properties: + integer: + type: "integer" + minimum: 10 + maximum: 100 + int32: + type: "integer" + format: "int32" + minimum: 20 + maximum: 200 + int64: + type: "integer" + format: "int64" + number: + type: "number" + minimum: 32.1 + maximum: 543.2 + float: + type: "number" + format: "float" + minimum: 54.3 + maximum: 987.6 + double: + type: "number" + format: "double" + minimum: 67.8 + maximum: 123.4 + string: + type: "string" + pattern: "/[a-z]/i" + byte: + type: "string" + format: "byte" + pattern: "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$" + binary: + type: "string" + format: "binary" + date: + type: "string" + format: "date" + dateTime: + type: "string" + format: "date-time" + uuid: + type: "string" + format: "uuid" + password: + type: "string" + format: "password" + minLength: 10 + maxLength: 64 + upperCaseName: "FORMAT_TEST" + EnumClass: + type: "string" + enum: + - "_abc" + - "-efg" + - "(xyz)" + default: "-efg" + upperCaseName: "ENUMCLASS" + Enum_Test: + type: "object" + properties: + enum_string: + type: "string" + enum: + - "UPPER" + - "lower" + - "" + enum_integer: + type: "integer" + format: "int32" + enum: + - 1 + - -1 + enum_number: + type: "number" + format: "double" + enum: + - 1.1 + - -1.2 + outerEnum: + $ref: "#/definitions/OuterEnum" + upperCaseName: "ENUM_TEST" + AdditionalPropertiesClass: + type: "object" + properties: + map_property: + type: "object" + additionalProperties: + type: "string" + map_of_map_property: + type: "object" + additionalProperties: + type: "object" + additionalProperties: + type: "string" + upperCaseName: "ADDITIONALPROPERTIESCLASS" + MixedPropertiesAndAdditionalPropertiesClass: + type: "object" + properties: + uuid: + type: "string" + format: "uuid" + dateTime: + type: "string" + format: "date-time" + map: + type: "object" + additionalProperties: + $ref: "#/definitions/Animal" + upperCaseName: "MIXEDPROPERTIESANDADDITIONALPROPERTIESCLASS" + List: + type: "object" + properties: + 123-list: + type: "string" + upperCaseName: "LIST" + Client: + type: "object" + properties: + client: + type: "string" + example: + client: "client" + upperCaseName: "CLIENT" + ReadOnlyFirst: + type: "object" + properties: + bar: + type: "string" + readOnly: true + baz: + type: "string" + upperCaseName: "READONLYFIRST" + hasOnlyReadOnly: + type: "object" + properties: + bar: + type: "string" + readOnly: true + foo: + type: "string" + readOnly: true + upperCaseName: "HASONLYREADONLY" + Capitalization: + type: "object" + properties: + smallCamel: + type: "string" + CapitalCamel: + type: "string" + small_Snake: + type: "string" + Capital_Snake: + type: "string" + SCA_ETH_Flow_Points: + type: "string" + ATT_NAME: + type: "string" + description: "Name of the pet\n" + upperCaseName: "CAPITALIZATION" + MapTest: + type: "object" + properties: + map_map_of_string: + type: "object" + additionalProperties: + type: "object" + additionalProperties: + type: "string" + map_of_enum_string: + type: "object" + additionalProperties: + type: "string" + enum: + - "UPPER" + - "lower" + upperCaseName: "MAPTEST" + 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" + upperCaseName: "ARRAYTEST" + NumberOnly: + type: "object" + properties: + JustNumber: + type: "number" + upperCaseName: "NUMBERONLY" + ArrayOfNumberOnly: + type: "object" + properties: + ArrayNumber: + type: "array" + items: + type: "number" + upperCaseName: "ARRAYOFNUMBERONLY" + ArrayOfArrayOfNumberOnly: + type: "object" + properties: + ArrayArrayNumber: + type: "array" + items: + type: "array" + items: + type: "number" + upperCaseName: "ARRAYOFARRAYOFNUMBERONLY" + EnumArrays: + type: "object" + properties: + just_symbol: + type: "string" + enum: + - ">=" + - "$" + array_enum: + type: "array" + items: + type: "string" + enum: + - "fish" + - "crab" + upperCaseName: "ENUMARRAYS" + OuterEnum: + type: "string" + enum: + - "placed" + - "approved" + - "delivered" + upperCaseName: "OUTERENUM" + OuterComposite: + type: "object" + properties: + my_number: + $ref: "#/definitions/OuterNumber" + my_string: + $ref: "#/definitions/OuterString" + my_boolean: + $ref: "#/definitions/OuterBoolean" + example: + my_string: {} + my_number: {} + my_boolean: {} + upperCaseName: "OUTERCOMPOSITE" + OuterNumber: + type: "number" + upperCaseName: "OUTERNUMBER" + OuterString: + type: "string" + upperCaseName: "OUTERSTRING" + OuterBoolean: + type: "boolean" + upperCaseName: "OUTERBOOLEAN" +externalDocs: + description: "Find out more about Swagger" + url: "http://swagger.io" diff --git a/samples/server/petstore/rust-server/examples/ca.pem b/samples/server/petstore/rust-server/examples/ca.pem new file mode 100644 index 00000000000..d2317fb5db7 --- /dev/null +++ b/samples/server/petstore/rust-server/examples/ca.pem @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE----- +MIICtjCCAZ4CCQDpKecRERZ0xDANBgkqhkiG9w0BAQsFADAdMQswCQYDVQQGEwJV +UzEOMAwGA1UEAxMFTXkgQ0EwHhcNMTcwNTIzMTYwMDIzWhcNMTcwNjIyMTYwMDIz +WjAdMQswCQYDVQQGEwJVUzEOMAwGA1UEAxMFTXkgQ0EwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQCt66py3x7sCSASRF2D05L5wkNDxAUjQKYx23W8Gbwv +GMGykk89BIdU5LX1JB1cKiUOkoIxfwAYuWc2V/wzTvVV7+11besnk3uX1c9KiqUF +LIX7kn/z5hzS4aelhKvH+MJlSZCSlp1ytpZbwo5GB5Pi2SGH56jDBiBoDRNBVdWL +z4wH7TdrQjqWwNxIZumD5OGMtcfJyuX08iPiEOaslOeoMqzObhvjc9aUgjVjhqyA +FkJGTXsi0oaD7oml+NE+mTNfEeZvEJQpLSjBY0OvQHzuHkyGBShBnfu/9x7/NRwd +WaqsLiF7/re9KDGYdJwP7Cu6uxYfKAyWarp6h2mG/GIdAgMBAAEwDQYJKoZIhvcN +AQELBQADggEBAGIl/VVIafeq/AJOQ9r7TzzB2ABJYr7NZa6bTu5O1jSp1Fonac15 +SZ8gvRxODgH22ZYSqghPG4xzq4J3hkytlQqm57ZEt2I2M3OqIp17Ndcc1xDYzpLl +tA0FrVn6crQTM8vQkTDtGesaCWX+7Fir5dK7HnYWzfpSmsOpST07PfbNisEXKOxG +Dj4lBL1OnhTjsJeymVS1pFvkKkrcEJO+IxFiHL3CDsWjcXB0Z+E1zBtPoYyYsNsO +rBrjUxcZewF4xqWZhpW90Mt61fY2nRgU0uUwHcvDQUqvmzKcsqYa4mPKzfBI5mxo +01Ta96cDD6pS5Y1hOflZ0g84f2g/7xBLLDA= +-----END CERTIFICATE----- diff --git a/samples/server/petstore/rust-server/examples/client.rs b/samples/server/petstore/rust-server/examples/client.rs new file mode 100644 index 00000000000..42a24e44241 --- /dev/null +++ b/samples/server/petstore/rust-server/examples/client.rs @@ -0,0 +1,268 @@ +#![allow(missing_docs, unused_variables, trivial_casts)] + +extern crate petstore_api; +#[allow(unused_extern_crates)] +extern crate futures; +#[allow(unused_extern_crates)] +extern crate swagger; +#[allow(unused_extern_crates)] +extern crate uuid; +extern crate clap; + +#[allow(unused_imports)] +use futures::{Future, future, Stream, stream}; +#[allow(unused_imports)] +use petstore_api::{ApiNoContext, ContextWrapperExt, + ApiError, + TestSpecialTagsResponse, + FakeOuterBooleanSerializeResponse, + FakeOuterCompositeSerializeResponse, + FakeOuterNumberSerializeResponse, + FakeOuterStringSerializeResponse, + TestClientModelResponse, + TestEndpointParametersResponse, + TestEnumParametersResponse, + TestInlineAdditionalPropertiesResponse, + TestJsonFormDataResponse, + TestClassnameResponse, + AddPetResponse, + DeletePetResponse, + FindPetsByStatusResponse, + FindPetsByTagsResponse, + GetPetByIdResponse, + UpdatePetResponse, + UpdatePetWithFormResponse, + UploadFileResponse, + DeleteOrderResponse, + GetInventoryResponse, + GetOrderByIdResponse, + PlaceOrderResponse, + CreateUserResponse, + CreateUsersWithArrayInputResponse, + CreateUsersWithListInputResponse, + DeleteUserResponse, + GetUserByNameResponse, + LoginUserResponse, + LogoutUserResponse, + UpdateUserResponse + }; +use clap::{App, Arg}; + +fn main() { + let matches = App::new("client") + .arg(Arg::with_name("operation") + .help("Sets the operation to run") + .possible_values(&[ + "FakeOuterBooleanSerialize", + "FakeOuterCompositeSerialize", + "FakeOuterNumberSerialize", + "FakeOuterStringSerialize", + "TestEndpointParameters", + "TestEnumParameters", + "TestJsonFormData", + "DeletePet", + "FindPetsByStatus", + "FindPetsByTags", + "GetPetById", + "UpdatePetWithForm", + "UploadFile", + "DeleteOrder", + "GetInventory", + "GetOrderById", + "CreateUsersWithArrayInput", + "CreateUsersWithListInput", + "DeleteUser", + "GetUserByName", + "LoginUser", + "LogoutUser", +]) + .required(true) + .index(1)) + .arg(Arg::with_name("https") + .long("https") + .help("Whether to use HTTPS or not")) + .get_matches(); + + let client = if matches.is_present("https") { + // Using Simple HTTPS + petstore_api::Client::try_new_https("https://localhost:8080", "examples/ca.pem").expect("Failed to create HTTPS client") + } else { + // Using HTTP + petstore_api::Client::try_new_http("http://localhost:8080").expect("Failed to create HTTP client") + }; + + // Using a non-default `Context` is not required; this is just an example! + let client = client.with_context(petstore_api::Context::new_with_span_id(self::uuid::Uuid::new_v4().to_string())); + + match matches.value_of("operation") { + + // Disabled because there's no example. + // Some("TestSpecialTags") => { + // let result = client.test_special_tags(???).wait(); + // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // }, + + Some("FakeOuterBooleanSerialize") => { + let result = client.fake_outer_boolean_serialize(None).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + Some("FakeOuterCompositeSerialize") => { + let result = client.fake_outer_composite_serialize(None).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + Some("FakeOuterNumberSerialize") => { + let result = client.fake_outer_number_serialize(None).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + Some("FakeOuterStringSerialize") => { + let result = client.fake_outer_string_serialize(None).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + // Disabled because there's no example. + // Some("TestClientModel") => { + // let result = client.test_client_model(???).wait(); + // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // }, + + Some("TestEndpointParameters") => { + let result = client.test_endpoint_parameters(3.4, 1.2, "pattern_without_delimiter_example".to_string(), swagger::ByteArray("byte_example".to_string().into_bytes()), Some(56), Some(56), Some(789), Some(3.4), Some("string_example".to_string()), Some(swagger::ByteArray(Vec::from("B"))), None, None, Some("password_example".to_string()), Some("callback_example".to_string())).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + Some("TestEnumParameters") => { + let result = client.test_enum_parameters(Some(&Vec::new()), Some("enum_form_string_example".to_string()), Some(&Vec::new()), Some("enum_header_string_example".to_string()), Some(&Vec::new()), Some("enum_query_string_example".to_string()), Some(56), Some(1.2)).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + // Disabled because there's no example. + // Some("TestInlineAdditionalProperties") => { + // let result = client.test_inline_additional_properties(???).wait(); + // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // }, + + Some("TestJsonFormData") => { + let result = client.test_json_form_data("param_example".to_string(), "param2_example".to_string()).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + // Disabled because there's no example. + // Some("TestClassname") => { + // let result = client.test_classname(???).wait(); + // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // }, + + // Disabled because there's no example. + // Some("AddPet") => { + // let result = client.add_pet(???).wait(); + // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // }, + + Some("DeletePet") => { + let result = client.delete_pet(789, Some("api_key_example".to_string())).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + Some("FindPetsByStatus") => { + let result = client.find_pets_by_status(&Vec::new()).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + Some("FindPetsByTags") => { + let result = client.find_pets_by_tags(&Vec::new()).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + Some("GetPetById") => { + let result = client.get_pet_by_id(789).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + // Disabled because there's no example. + // Some("UpdatePet") => { + // let result = client.update_pet(???).wait(); + // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // }, + + Some("UpdatePetWithForm") => { + let result = client.update_pet_with_form(789, Some("name_example".to_string()), Some("status_example".to_string())).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + Some("UploadFile") => { + let result = client.upload_file(789, Some("additional_metadata_example".to_string()), Box::new(future::ok(Some(Box::new(stream::once(Ok(b"hello".to_vec()))) as Box + Send>))) as Box + Send>).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + Some("DeleteOrder") => { + let result = client.delete_order("order_id_example".to_string()).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + Some("GetInventory") => { + let result = client.get_inventory().wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + Some("GetOrderById") => { + let result = client.get_order_by_id(789).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + // Disabled because there's no example. + // Some("PlaceOrder") => { + // let result = client.place_order(???).wait(); + // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // }, + + // Disabled because there's no example. + // Some("CreateUser") => { + // let result = client.create_user(???).wait(); + // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // }, + + Some("CreateUsersWithArrayInput") => { + let result = client.create_users_with_array_input(&Vec::new()).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + Some("CreateUsersWithListInput") => { + let result = client.create_users_with_list_input(&Vec::new()).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + Some("DeleteUser") => { + let result = client.delete_user("username_example".to_string()).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + Some("GetUserByName") => { + let result = client.get_user_by_name("username_example".to_string()).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + Some("LoginUser") => { + let result = client.login_user("username_example".to_string(), "password_example".to_string()).wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + Some("LogoutUser") => { + let result = client.logout_user().wait(); + println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + }, + + // Disabled because there's no example. + // Some("UpdateUser") => { + // let result = client.update_user("username_example".to_string(), ???).wait(); + // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // }, + + _ => { + panic!("Invalid operation provided") + } + } +} + diff --git a/samples/server/petstore/rust-server/examples/server-chain.pem b/samples/server/petstore/rust-server/examples/server-chain.pem new file mode 100644 index 00000000000..47d7e201404 --- /dev/null +++ b/samples/server/petstore/rust-server/examples/server-chain.pem @@ -0,0 +1,66 @@ +Certificate: + Data: + Version: 1 (0x0) + Serial Number: 4096 (0x1000) + Signature Algorithm: sha256WithRSAEncryption + Issuer: C=US, CN=My CA + Validity + Not Before: May 23 16:00:23 2017 GMT + Not After : Apr 29 16:00:23 2117 GMT + Subject: CN=localhost, C=US + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:c9:d4:43:60:50:fc:d6:0f:38:4d:5d:5e:aa:7c: + c0:5e:a9:ec:d9:93:78:d3:93:72:28:41:f5:08:a5: + ea:ac:67:07:d7:1f:f7:7d:74:69:7e:46:89:20:4b: + 7a:2d:9b:02:08:e7:6f:0f:1d:0c:0f:c7:60:69:19: + 4b:df:7e:ca:75:94:0b:49:71:e3:6d:f2:e8:79:fd: + ed:0a:94:67:55:f3:ca:6b:61:ba:58:b7:2e:dd:7b: + ca:b9:02:9f:24:36:ac:26:8f:04:8f:81:c8:35:10: + f4:aa:33:b2:24:16:f8:f7:1e:ea:f7:16:fe:fa:34: + c3:dd:bb:2c:ba:7a:df:4d:e2:da:1e:e5:d2:28:44: + 6e:c8:96:e0:fd:09:0c:14:0c:31:dc:e0:ca:c1:a7: + 9b:bf:16:8c:f7:36:3f:1b:2e:dd:90:eb:45:78:51: + bf:59:22:1e:c6:8c:0a:69:88:e5:03:5e:73:b7:fc: + 93:7f:1b:46:1b:97:68:c5:c0:8b:35:1f:bb:1e:67: + 7f:55:b7:3b:55:3f:ea:f2:ca:db:cc:52:cd:16:89: + db:15:47:bd:f2:cd:6c:7a:d7:b4:1a:ac:c8:15:6c: + 6a:fb:77:c4:e9:f2:30:e0:14:24:66:65:6f:2a:e5: + 2d:cc:f6:81:ae:57:c8:d1:9b:38:90:dc:60:93:02: + 5e:cb + Exponent: 65537 (0x10001) + Signature Algorithm: sha256WithRSAEncryption + 1c:7c:39:e8:3d:49:b2:09:1e:68:5a:2f:74:18:f4:63:b5:8c: + f6:e6:a1:e3:4d:95:90:99:ef:32:5c:34:40:e8:55:13:0e:e0: + 1c:be:cd:ab:3f:64:38:99:5e:2b:c1:81:53:a0:18:a8:f6:ee: + 6a:33:73:6c:9a:73:9d:86:08:5d:c7:11:38:46:4c:cd:a0:47: + 37:8f:fe:a6:50:a9:02:21:99:42:86:5e:47:fe:65:56:60:1d: + 16:53:86:bd:e4:63:c5:69:cf:fa:30:51:ab:a1:c3:50:53:cc: + 66:1c:4c:ff:3f:2a:39:4d:a2:8f:9d:d1:a7:8b:22:e4:78:69: + 24:06:83:4d:cc:0a:c0:87:69:9b:bc:80:a9:d2:b7:a5:23:84: + 7e:a2:32:26:7c:78:0e:bd:db:cd:3b:69:18:33:b8:44:ef:96: + b4:99:86:ee:06:bd:51:1c:c7:a1:a4:0c:c4:4c:51:a0:df:ac: + 14:07:88:8e:d7:39:45:fe:52:e0:a3:4c:db:5d:7a:ab:4d:e4: + ca:06:e8:bd:74:6f:46:e7:93:4a:4f:1b:67:e7:a5:9f:ef:9c: + 02:49:d1:f2:d5:e9:53:ee:09:21:ac:08:c8:15:f7:af:35:b9: + 4f:11:0f:43:ae:46:8e:fd:5b:8d:a3:4e:a7:2c:b7:25:ed:e4: + e5:94:1d:e3 +-----BEGIN CERTIFICATE----- +MIICtTCCAZ0CAhAAMA0GCSqGSIb3DQEBCwUAMB0xCzAJBgNVBAYTAlVTMQ4wDAYD +VQQDEwVNeSBDQTAgFw0xNzA1MjMxNjAwMjNaGA8yMTE3MDQyOTE2MDAyM1owITES +MBAGA1UEAxMJbG9jYWxob3N0MQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEB +BQADggEPADCCAQoCggEBAMnUQ2BQ/NYPOE1dXqp8wF6p7NmTeNOTcihB9Qil6qxn +B9cf9310aX5GiSBLei2bAgjnbw8dDA/HYGkZS99+ynWUC0lx423y6Hn97QqUZ1Xz +ymthuli3Lt17yrkCnyQ2rCaPBI+ByDUQ9KozsiQW+Pce6vcW/vo0w927LLp6303i +2h7l0ihEbsiW4P0JDBQMMdzgysGnm78WjPc2Pxsu3ZDrRXhRv1kiHsaMCmmI5QNe +c7f8k38bRhuXaMXAizUfux5nf1W3O1U/6vLK28xSzRaJ2xVHvfLNbHrXtBqsyBVs +avt3xOnyMOAUJGZlbyrlLcz2ga5XyNGbOJDcYJMCXssCAwEAATANBgkqhkiG9w0B +AQsFAAOCAQEAHHw56D1JsgkeaFovdBj0Y7WM9uah402VkJnvMlw0QOhVEw7gHL7N +qz9kOJleK8GBU6AYqPbuajNzbJpznYYIXccROEZMzaBHN4/+plCpAiGZQoZeR/5l +VmAdFlOGveRjxWnP+jBRq6HDUFPMZhxM/z8qOU2ij53Rp4si5HhpJAaDTcwKwIdp +m7yAqdK3pSOEfqIyJnx4Dr3bzTtpGDO4RO+WtJmG7ga9URzHoaQMxExRoN+sFAeI +jtc5Rf5S4KNM2116q03kygbovXRvRueTSk8bZ+eln++cAknR8tXpU+4JIawIyBX3 +rzW5TxEPQ65Gjv1bjaNOpyy3Je3k5ZQd4w== +-----END CERTIFICATE----- diff --git a/samples/server/petstore/rust-server/examples/server-key.pem b/samples/server/petstore/rust-server/examples/server-key.pem new file mode 100644 index 00000000000..29c00682922 --- /dev/null +++ b/samples/server/petstore/rust-server/examples/server-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDJ1ENgUPzWDzhN +XV6qfMBeqezZk3jTk3IoQfUIpeqsZwfXH/d9dGl+RokgS3otmwII528PHQwPx2Bp +GUvffsp1lAtJceNt8uh5/e0KlGdV88prYbpYty7de8q5Ap8kNqwmjwSPgcg1EPSq +M7IkFvj3Hur3Fv76NMPduyy6et9N4toe5dIoRG7IluD9CQwUDDHc4MrBp5u/Foz3 +Nj8bLt2Q60V4Ub9ZIh7GjAppiOUDXnO3/JN/G0Ybl2jFwIs1H7seZ39VtztVP+ry +ytvMUs0WidsVR73yzWx617QarMgVbGr7d8Tp8jDgFCRmZW8q5S3M9oGuV8jRmziQ +3GCTAl7LAgMBAAECggEBAKEd1q9j14KWYc64s6KLthGbutyxsinMMbxbct11fdIk +6YhdF3fJ35ETg9IJDr6rWEN9ZRX+jStncNpVfFEs6ThVd3Eo/nI+EEGaaIkikR93 +X2a7fEPn7/yVHu70XdBN6L1bPDvHUeiy4W2hmRrgT90OjGm1rNRWHOm7yugOwIZu +HclzbR9Ca7EInFnotUiDQm9sw9VKHbJHqWx6OORdZrxR2ytYs0Qkq0XpGMvti2HW +7WAmKTg5QM8myXW7+/4iqb/u68wVBR2BBalShKmIf7lim9O3W2a1RjDdsvm/wNe9 +I+D+Iq825vpqkKXcrxYlpVg7hYiaQaW/MNsEb7lQRjECgYEA/RJYby0POW+/k0Jn +jO8UmJVEMiuGa8WIUu/JJWMOmzRCukjSRNQOkt7niQrZPJYE8W6clM6RJTolWf9L +IL6mIb+mRaoudUk8SHGDq7ho1iMg9GK8lhYxvKh1Q6uv8EyVSkgLknAEY0NANKC1 +zNdU5Dhven9aRX2gq9vP4XwMz2MCgYEAzCogQ7IFk+gkp3k491dOZnrGRoRCfuzo +4CJtyKFgOSd7BjmpcKkj0IPfVBjw6GjMIxfQRMTQmxAjjWevH45vG8l0Iiwz/gSp +81b5nsDEX5uv2Olcmcz5zxRFy36jOZ9ihMWinxcIlT2oDbyCdbruDKZq9ieJ9S8g +4qGx0OkwE3kCgYEA7CmAiU89U9YqqttfEq/RQoqY91CSwmO10d+ej9seuEtOsdRf +FIfnibulycdr7hP5TOxyBpO1802NqayJiWcgVYIpQf2MGTtcnCYCP+95NcvWZvj1 +EAJqK6nwtFO1fcOZ1ZXh5qfOEGujsPkAbsXLnKXlsiTCMvMHSxl3pu5Cbg0CgYBf +JjbZNctRrjv+7Qj2hPLd4dQsIxGWc7ToWENP4J2mpVa5hQAJqFovoHXhjKohtk2F +AWEn243Y5oGbMjo0e74edhmwn2cvuF64MM2vBem/ISCn98IXT6cQskMA3qkVfsl8 +VVs/x41ReGWs2TD3y0GMFbb9t1mdMfSiincDhNnKCQKBgGfeT4jKyYeCoCw4OLI1 +G75Gd0METt/IkppwODPpNwj3Rp9I5jctWZFA/3wCX/zk0HgBeou5AFNS4nQZ/X/L +L9axbSdR7UJTGkT1r4gu3rLkPV4Tk+8XM03/JT2cofMlzQBuhvl1Pn4SgKowz7hl +lS76ECw4Av3T0S34VW9Z5oye +-----END PRIVATE KEY----- diff --git a/samples/server/petstore/rust-server/examples/server.rs b/samples/server/petstore/rust-server/examples/server.rs new file mode 100644 index 00000000000..f3f3f50de4b --- /dev/null +++ b/samples/server/petstore/rust-server/examples/server.rs @@ -0,0 +1,58 @@ +#![allow(missing_docs)] + +extern crate petstore_api; +extern crate iron; +extern crate futures; +extern crate hyper_openssl; +extern crate clap; +extern crate swagger; + +use hyper_openssl::OpensslServer; +use hyper_openssl::openssl::x509::X509_FILETYPE_PEM; +use hyper_openssl::openssl::ssl::{SslAcceptorBuilder, SslMethod}; +use hyper_openssl::openssl::error::ErrorStack; +use clap::{App, Arg}; +use iron::{Iron, Chain}; +use swagger::auth::AllowAllMiddleware; + +// Import the module that defines the Server struct. +mod server_lib; + +/// Builds an SSL implementation for Simple HTTPS from some hard-coded file names +fn ssl() -> Result { + let mut ssl = SslAcceptorBuilder::mozilla_intermediate_raw(SslMethod::tls())?; + + // Server authentication + ssl.builder_mut().set_private_key_file("examples/server-key.pem", X509_FILETYPE_PEM)?; + ssl.builder_mut().set_certificate_chain_file("examples/server-chain.pem")?; + ssl.builder_mut().check_private_key()?; + + Ok(OpensslServer::from(ssl.build())) +} + +/// Create custom server, wire it to the autogenerated router, +/// and pass it to the web server. +fn main() { + let matches = App::new("server") + .arg(Arg::with_name("https") + .long("https") + .help("Whether to use HTTPS or not")) + .get_matches(); + + let server = server_lib::Server{}; + let router = petstore_api::router(server); + + let mut chain = Chain::new(router); + chain.link_before(petstore_api::server::ExtractAuthData); + // add authentication middlewares into the chain here + // for the purpose of this example, pretend we have authenticated a user + chain.link_before(AllowAllMiddleware::new("cosmo")); + + if matches.is_present("https") { + // Using Simple HTTPS + Iron::new(chain).https("localhost:8080", ssl().expect("Failed to load SSL keys")).expect("Failed to start HTTPS server"); + } else { + // Using HTTP + Iron::new(chain).http("localhost:8080").expect("Failed to start HTTP server"); + } +} diff --git a/samples/server/petstore/rust-server/examples/server_lib/mod.rs b/samples/server/petstore/rust-server/examples/server_lib/mod.rs new file mode 100644 index 00000000000..6427d552390 --- /dev/null +++ b/samples/server/petstore/rust-server/examples/server_lib/mod.rs @@ -0,0 +1,271 @@ +#![allow(missing_docs, unused_extern_crates)] +extern crate chrono; +extern crate swagger; + +use futures::{self, Future}; +use futures::Stream; + +#[allow(unused_imports)] +use std::collections::HashMap; +use std::io::Error; + +use petstore_api::{Api, ApiError, Context, + TestSpecialTagsResponse, + FakeOuterBooleanSerializeResponse, + FakeOuterCompositeSerializeResponse, + FakeOuterNumberSerializeResponse, + FakeOuterStringSerializeResponse, + TestClientModelResponse, + TestEndpointParametersResponse, + TestEnumParametersResponse, + TestInlineAdditionalPropertiesResponse, + TestJsonFormDataResponse, + TestClassnameResponse, + AddPetResponse, + DeletePetResponse, + FindPetsByStatusResponse, + FindPetsByTagsResponse, + GetPetByIdResponse, + UpdatePetResponse, + UpdatePetWithFormResponse, + UploadFileResponse, + DeleteOrderResponse, + GetInventoryResponse, + GetOrderByIdResponse, + PlaceOrderResponse, + CreateUserResponse, + CreateUsersWithArrayInputResponse, + CreateUsersWithListInputResponse, + DeleteUserResponse, + GetUserByNameResponse, + LoginUserResponse, + LogoutUserResponse, + UpdateUserResponse +}; +#[allow(unused_imports)] +use petstore_api::models; + +#[derive(Copy, Clone)] +pub struct Server; + +impl Api for Server { + + /// To test special tags + fn test_special_tags(&self, body: models::Client, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("test_special_tags({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + + fn fake_outer_boolean_serialize(&self, body: Option, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("fake_outer_boolean_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + + fn fake_outer_composite_serialize(&self, body: Option, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("fake_outer_composite_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + + fn fake_outer_number_serialize(&self, body: Option, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("fake_outer_number_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + + fn fake_outer_string_serialize(&self, body: Option, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("fake_outer_string_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// To test \"client\" model + fn test_client_model(&self, body: models::Client, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("test_client_model({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("test_endpoint_parameters({}, {}, \"{}\", \"{:?}\", {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", number, double, pattern_without_delimiter, byte, integer, int32, int64, float, string, binary, date, date_time, password, callback, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// To test enum parameters + fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec>, enum_form_string: Option, enum_header_string_array: Option<&Vec>, enum_header_string: Option, enum_query_string_array: Option<&Vec>, enum_query_string: Option, enum_query_integer: Option, enum_query_double: Option, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("test_enum_parameters({:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", enum_form_string_array, enum_form_string, enum_header_string_array, enum_header_string, enum_query_string_array, enum_query_string, enum_query_integer, enum_query_double, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// test inline additionalProperties + fn test_inline_additional_properties(&self, param: object, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("test_inline_additional_properties({:?}) - X-Span-ID: {:?}", param, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// test json serialization of form data + fn test_json_form_data(&self, param: String, param2: String, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("test_json_form_data(\"{}\", \"{}\") - X-Span-ID: {:?}", param, param2, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// To test class name in snake case + fn test_classname(&self, body: models::Client, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("test_classname({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Add a new pet to the store + fn add_pet(&self, body: models::Pet, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("add_pet({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Deletes a pet + fn delete_pet(&self, pet_id: i64, api_key: Option, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("delete_pet({}, {:?}) - X-Span-ID: {:?}", pet_id, api_key, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Finds Pets by status + fn find_pets_by_status(&self, status: &Vec, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("find_pets_by_status({:?}) - X-Span-ID: {:?}", status, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Finds Pets by tags + fn find_pets_by_tags(&self, tags: &Vec, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("find_pets_by_tags({:?}) - X-Span-ID: {:?}", tags, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Find pet by ID + fn get_pet_by_id(&self, pet_id: i64, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("get_pet_by_id({}) - X-Span-ID: {:?}", pet_id, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Update an existing pet + fn update_pet(&self, body: models::Pet, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("update_pet({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Updates a pet in the store with form data + fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("update_pet_with_form({}, {:?}, {:?}) - X-Span-ID: {:?}", pet_id, name, status, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// uploads an image + fn upload_file(&self, pet_id: i64, additional_metadata: Option, file: Box, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("upload_file({}, {:?}, ) - X-Span-ID: {:?}", pet_id, additional_metadata, context.x_span_id.unwrap_or(String::from("")).clone()); + let _ = file; //Suppresses unused param warning + Box::new(futures::failed("Generic failure".into())) + } + + /// Delete purchase order by ID + fn delete_order(&self, order_id: String, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("delete_order(\"{}\") - X-Span-ID: {:?}", order_id, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Returns pet inventories by status + fn get_inventory(&self, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("get_inventory() - X-Span-ID: {:?}", context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Find purchase order by ID + fn get_order_by_id(&self, order_id: i64, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("get_order_by_id({}) - X-Span-ID: {:?}", order_id, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Place an order for a pet + fn place_order(&self, body: models::Order, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("place_order({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Create user + fn create_user(&self, body: models::User, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("create_user({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Creates list of users with given input array + fn create_users_with_array_input(&self, body: &Vec, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("create_users_with_array_input({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Creates list of users with given input array + fn create_users_with_list_input(&self, body: &Vec, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("create_users_with_list_input({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Delete user + fn delete_user(&self, username: String, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("delete_user(\"{}\") - X-Span-ID: {:?}", username, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Get user by user name + fn get_user_by_name(&self, username: String, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("get_user_by_name(\"{}\") - X-Span-ID: {:?}", username, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Logs user into the system + fn login_user(&self, username: String, password: String, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("login_user(\"{}\", \"{}\") - X-Span-ID: {:?}", username, password, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Logs out current logged in user session + fn logout_user(&self, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("logout_user() - X-Span-ID: {:?}", context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Updated user + fn update_user(&self, username: String, body: models::User, context: &Context) -> Box + Send> { + let context = context.clone(); + println!("update_user(\"{}\", {:?}) - X-Span-ID: {:?}", username, body, context.x_span_id.unwrap_or(String::from("")).clone()); + Box::new(futures::failed("Generic failure".into())) + } + +} diff --git a/samples/server/petstore/rust-server/src/client.rs b/samples/server/petstore/rust-server/src/client.rs new file mode 100644 index 00000000000..be7653886cb --- /dev/null +++ b/samples/server/petstore/rust-server/src/client.rs @@ -0,0 +1,1915 @@ +#![allow(unused_extern_crates)] +extern crate hyper_openssl; +extern crate chrono; +extern crate multipart; + +use multipart::client::lazy::Multipart; +use hyper; +use hyper::client::IntoUrl; +use hyper::mime; +use hyper::header::{Headers, ContentType}; +use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use hyper::Url; +use self::hyper_openssl::openssl; +use futures; +use futures::{Future, Stream}; +use futures::{future, stream}; +use std::borrow::Cow; +use std::io::{Read, Error}; +use std::error; +use std::fmt; +use std::path::Path; +use std::sync::Arc; +use std::str; + +use mimetypes; + +use serde_json; +use serde_xml_rs; + +#[allow(unused_imports)] +use std::collections::{HashMap, BTreeMap}; +#[allow(unused_imports)] +use swagger; + +use swagger::{Context, ApiError, XSpanId}; + +use {Api, + TestSpecialTagsResponse, + FakeOuterBooleanSerializeResponse, + FakeOuterCompositeSerializeResponse, + FakeOuterNumberSerializeResponse, + FakeOuterStringSerializeResponse, + TestClientModelResponse, + TestEndpointParametersResponse, + TestEnumParametersResponse, + TestInlineAdditionalPropertiesResponse, + TestJsonFormDataResponse, + TestClassnameResponse, + AddPetResponse, + DeletePetResponse, + FindPetsByStatusResponse, + FindPetsByTagsResponse, + GetPetByIdResponse, + UpdatePetResponse, + UpdatePetWithFormResponse, + UploadFileResponse, + DeleteOrderResponse, + GetInventoryResponse, + GetOrderByIdResponse, + PlaceOrderResponse, + CreateUserResponse, + CreateUsersWithArrayInputResponse, + CreateUsersWithListInputResponse, + DeleteUserResponse, + GetUserByNameResponse, + LoginUserResponse, + LogoutUserResponse, + UpdateUserResponse + }; +use models; + +/// Convert input into a base path, e.g. "http://example:123". Also checks the scheme as it goes. +fn into_base_path(input: T, correct_scheme: Option<&'static str>) -> Result { + // First convert to Url, since a base path is a subset of Url. + let url = input.into_url()?; + + let scheme = url.scheme(); + + // Check the scheme if necessary + if let Some(correct_scheme) = correct_scheme { + if scheme != correct_scheme { + return Err(ClientInitError::InvalidScheme); + } + } + + let host = url.host().ok_or_else(|| ClientInitError::MissingHost)?; + let port = url.port().map(|x| format!(":{}", x)).unwrap_or_default(); + Ok(format!("{}://{}{}", scheme, host, port)) +} + +/// A client that implements the API by making HTTP calls out to a server. +#[derive(Clone)] +pub struct Client { + base_path: String, + hyper_client: Arc hyper::client::Client + Sync + Send>, +} + +impl fmt::Debug for Client { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Client {{ base_path: {} }}", self.base_path) + } +} + +impl Client { + pub fn try_new_http(base_path: T) -> Result + where T: IntoUrl + { + Ok(Client { + base_path: into_base_path(base_path, Some("http"))?, + hyper_client: Arc::new(hyper::client::Client::new), + }) + } + + pub fn try_new_https(base_path: T, + ca_certificate: CA) + -> Result + where T: IntoUrl, + CA: AsRef + { + let ca_certificate = ca_certificate.as_ref().to_owned(); + + let https_hyper_client = move || { + // SSL implementation + let mut ssl = openssl::ssl::SslConnectorBuilder::new(openssl::ssl::SslMethod::tls()).unwrap(); + + // Server authentication + ssl.builder_mut().set_ca_file(ca_certificate.clone()).unwrap(); + + let ssl = hyper_openssl::OpensslClient::from(ssl.build()); + let connector = hyper::net::HttpsConnector::new(ssl); + hyper::client::Client::with_connector(connector) + }; + + Ok(Client { + base_path: into_base_path(base_path, Some("https"))?, + hyper_client: Arc::new(https_hyper_client), + }) + } + + pub fn try_new_https_mutual(base_path: T, + ca_certificate: CA, + client_key: K, + client_certificate: C) + -> Result + where T: IntoUrl, + CA: AsRef, + K: AsRef, + C: AsRef + { + let ca_certificate = ca_certificate.as_ref().to_owned(); + let client_key = client_key.as_ref().to_owned(); + let client_certificate = client_certificate.as_ref().to_owned(); + + let https_mutual_hyper_client = move || { + // SSL implementation + let mut ssl = openssl::ssl::SslConnectorBuilder::new(openssl::ssl::SslMethod::tls()).unwrap(); + + // Server authentication + ssl.builder_mut().set_ca_file(ca_certificate.clone()).unwrap(); + + // Client authentication + ssl.builder_mut().set_private_key_file(client_key.clone(), openssl::x509::X509_FILETYPE_PEM).unwrap(); + ssl.builder_mut().set_certificate_chain_file(client_certificate.clone()).unwrap(); + ssl.builder_mut().check_private_key().unwrap(); + + let ssl = hyper_openssl::OpensslClient::from(ssl.build()); + let connector = hyper::net::HttpsConnector::new(ssl); + hyper::client::Client::with_connector(connector) + }; + + Ok(Client { + base_path: into_base_path(base_path, Some("https"))?, + hyper_client: Arc::new(https_mutual_hyper_client) + }) + } + + /// Constructor for creating a `Client` by passing in a pre-made `hyper` client. + /// + /// One should avoid relying on this function if possible, since it adds a dependency on the underlying transport + /// implementation, which it would be better to abstract away. Therefore, using this function may lead to a loss of + /// code generality, which may make it harder to move the application to a serverless environment, for example. + /// + /// The reason for this function's existence is to support legacy test code, which did mocking at the hyper layer. + /// This is not a recommended way to write new tests. If other reasons are found for using this function, they + /// should be mentioned here. + pub fn try_new_with_hyper_client(base_path: T, + hyper_client: Arc hyper::client::Client + Sync + Send>) + -> Result + where T: IntoUrl + { + Ok(Client { + base_path: into_base_path(base_path, None)?, + hyper_client: hyper_client + }) + } +} + +impl Api for Client { + + fn test_special_tags(&self, param_body: models::Client, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/another-fake/dummy?", self.base_path); + + + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Patch, &url); + let mut custom_headers = hyper::header::Headers::new(); + + let request = request.body(&body); + + custom_headers.set(ContentType(mimetypes::requests::TEST_SPECIAL_TAGS.clone())); + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + let mut buf = String::new(); + response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + let body = serde_json::from_str::(&buf)?; + + + + Ok(TestSpecialTagsResponse::SuccessfulOperation(body)) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn fake_outer_boolean_serialize(&self, param_body: Option, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/fake/outer/boolean?", self.base_path); + + let body = param_body.map(|ref body| { + + serde_json::to_string(body).expect("impossible to fail to serialize") + }); + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Post, &url); + let mut custom_headers = hyper::header::Headers::new(); + + let request = match body { + Some(ref body) => request.body(body), + None => request, + }; + + custom_headers.set(ContentType(mimetypes::requests::FAKE_OUTER_BOOLEAN_SERIALIZE.clone())); + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + let mut buf = String::new(); + response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + let body = serde_json::from_str::(&buf)?; + + + + Ok(FakeOuterBooleanSerializeResponse::OutputBoolean(body)) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn fake_outer_composite_serialize(&self, param_body: Option, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/fake/outer/composite?", self.base_path); + + let body = param_body.map(|ref body| { + + serde_json::to_string(body).expect("impossible to fail to serialize") + }); + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Post, &url); + let mut custom_headers = hyper::header::Headers::new(); + + let request = match body { + Some(ref body) => request.body(body), + None => request, + }; + + custom_headers.set(ContentType(mimetypes::requests::FAKE_OUTER_COMPOSITE_SERIALIZE.clone())); + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + let mut buf = String::new(); + response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + let body = serde_json::from_str::(&buf)?; + + + + Ok(FakeOuterCompositeSerializeResponse::OutputComposite(body)) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn fake_outer_number_serialize(&self, param_body: Option, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/fake/outer/number?", self.base_path); + + let body = param_body.map(|ref body| { + + serde_json::to_string(body).expect("impossible to fail to serialize") + }); + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Post, &url); + let mut custom_headers = hyper::header::Headers::new(); + + let request = match body { + Some(ref body) => request.body(body), + None => request, + }; + + custom_headers.set(ContentType(mimetypes::requests::FAKE_OUTER_NUMBER_SERIALIZE.clone())); + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + let mut buf = String::new(); + response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + let body = serde_json::from_str::(&buf)?; + + + + Ok(FakeOuterNumberSerializeResponse::OutputNumber(body)) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn fake_outer_string_serialize(&self, param_body: Option, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/fake/outer/string?", self.base_path); + + let body = param_body.map(|ref body| { + + serde_json::to_string(body).expect("impossible to fail to serialize") + }); + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Post, &url); + let mut custom_headers = hyper::header::Headers::new(); + + let request = match body { + Some(ref body) => request.body(body), + None => request, + }; + + custom_headers.set(ContentType(mimetypes::requests::FAKE_OUTER_STRING_SERIALIZE.clone())); + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + let mut buf = String::new(); + response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + let body = serde_json::from_str::(&buf)?; + + + + Ok(FakeOuterStringSerializeResponse::OutputString(body)) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn test_client_model(&self, param_body: models::Client, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/fake?", self.base_path); + + + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Patch, &url); + let mut custom_headers = hyper::header::Headers::new(); + + let request = request.body(&body); + + custom_headers.set(ContentType(mimetypes::requests::TEST_CLIENT_MODEL.clone())); + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + let mut buf = String::new(); + response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + let body = serde_json::from_str::(&buf)?; + + + + Ok(TestClientModelResponse::SuccessfulOperation(body)) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn test_endpoint_parameters(&self, param_number: f64, param_double: f64, param_pattern_without_delimiter: String, param_byte: swagger::ByteArray, param_integer: Option, param_int32: Option, param_int64: Option, param_float: Option, param_string: Option, param_binary: Option, param_date: Option>, param_date_time: Option>, param_password: Option, param_callback: Option, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/fake?", self.base_path); + + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Post, &url); + let mut custom_headers = hyper::header::Headers::new(); + + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 400 => { + + + Ok(TestEndpointParametersResponse::InvalidUsernameSupplied) + }, + 404 => { + + + Ok(TestEndpointParametersResponse::UserNotFound) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn test_enum_parameters(&self, param_enum_form_string_array: Option<&Vec>, param_enum_form_string: Option, param_enum_header_string_array: Option<&Vec>, param_enum_header_string: Option, param_enum_query_string_array: Option<&Vec>, param_enum_query_string: Option, param_enum_query_integer: Option, param_enum_query_double: Option, context: &Context) -> Box + Send> { + + // Query parameters + let query_enum_query_string_array = param_enum_query_string_array.map_or_else(String::new, |query| format!("enum_query_string_array={enum_query_string_array}&", enum_query_string_array=query.join(","))); + let query_enum_query_string = param_enum_query_string.map_or_else(String::new, |query| format!("enum_query_string={enum_query_string}&", enum_query_string=query.to_string())); + let query_enum_query_integer = param_enum_query_integer.map_or_else(String::new, |query| format!("enum_query_integer={enum_query_integer}&", enum_query_integer=query.to_string())); + + + let url = format!("{}/v2/fake?{enum_query_string_array}{enum_query_string}{enum_query_integer}", self.base_path, enum_query_string_array=query_enum_query_string_array, enum_query_string=query_enum_query_string, enum_query_integer=query_enum_query_integer); + + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Get, &url); + let mut custom_headers = hyper::header::Headers::new(); + + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + // Header parameters + header! { (RequestEnumHeaderStringArray, "enum_header_string_array") => (String)* } + param_enum_header_string_array.map(|header| custom_headers.set(RequestEnumHeaderStringArray(header.clone()))); + header! { (RequestEnumHeaderString, "enum_header_string") => [String] } + param_enum_header_string.map(|header| custom_headers.set(RequestEnumHeaderString(header))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 400 => { + + + Ok(TestEnumParametersResponse::InvalidRequest) + }, + 404 => { + + + Ok(TestEnumParametersResponse::NotFound) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn test_inline_additional_properties(&self, param_param: object, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/fake/inline-additionalProperties?", self.base_path); + + + let body = serde_json::to_string(¶m_param).expect("impossible to fail to serialize"); + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Post, &url); + let mut custom_headers = hyper::header::Headers::new(); + + let request = request.body(&body); + + custom_headers.set(ContentType(mimetypes::requests::TEST_INLINE_ADDITIONAL_PROPERTIES.clone())); + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + + + Ok(TestInlineAdditionalPropertiesResponse::SuccessfulOperation) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn test_json_form_data(&self, param_param: String, param_param2: String, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/fake/jsonFormData?", self.base_path); + + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Get, &url); + let mut custom_headers = hyper::header::Headers::new(); + + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + + + Ok(TestJsonFormDataResponse::SuccessfulOperation) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn test_classname(&self, param_body: models::Client, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/fake_classname_test?", self.base_path); + + + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Patch, &url); + let mut custom_headers = hyper::header::Headers::new(); + + let request = request.body(&body); + + custom_headers.set(ContentType(mimetypes::requests::TEST_CLASSNAME.clone())); + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + let mut buf = String::new(); + response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + let body = serde_json::from_str::(&buf)?; + + + + Ok(TestClassnameResponse::SuccessfulOperation(body)) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn add_pet(&self, param_body: models::Pet, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/pet?", self.base_path); + + + let body = serde_xml_rs::to_string(¶m_body).expect("impossible to fail to serialize"); + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Post, &url); + let mut custom_headers = hyper::header::Headers::new(); + + let request = request.body(&body); + + custom_headers.set(ContentType(mimetypes::requests::ADD_PET.clone())); + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 405 => { + + + Ok(AddPetResponse::InvalidInput) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn delete_pet(&self, param_pet_id: i64, param_api_key: Option, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/pet/{petId}?", self.base_path, petId=param_pet_id.to_string()); + + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Delete, &url); + let mut custom_headers = hyper::header::Headers::new(); + + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + // Header parameters + header! { (RequestApiKey, "api_key") => [String] } + param_api_key.map(|header| custom_headers.set(RequestApiKey(header))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 400 => { + + + Ok(DeletePetResponse::InvalidPetValue) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn find_pets_by_status(&self, param_status: &Vec, context: &Context) -> Box + Send> { + + // Query parameters + let query_status = format!("status={status}&", status=param_status.join(",")); + + + let url = format!("{}/v2/pet/findByStatus?{status}", self.base_path, status=query_status); + + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Get, &url); + let mut custom_headers = hyper::header::Headers::new(); + + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + let mut buf = String::new(); + response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + let body = serde_xml_rs::from_str::>(&buf) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + + + Ok(FindPetsByStatusResponse::SuccessfulOperation(body)) + }, + 400 => { + + + Ok(FindPetsByStatusResponse::InvalidStatusValue) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn find_pets_by_tags(&self, param_tags: &Vec, context: &Context) -> Box + Send> { + + // Query parameters + let query_tags = format!("tags={tags}&", tags=param_tags.join(",")); + + + let url = format!("{}/v2/pet/findByTags?{tags}", self.base_path, tags=query_tags); + + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Get, &url); + let mut custom_headers = hyper::header::Headers::new(); + + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + let mut buf = String::new(); + response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + let body = serde_xml_rs::from_str::>(&buf) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + + + Ok(FindPetsByTagsResponse::SuccessfulOperation(body)) + }, + 400 => { + + + Ok(FindPetsByTagsResponse::InvalidTagValue) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn get_pet_by_id(&self, param_pet_id: i64, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/pet/{petId}?", self.base_path, petId=param_pet_id.to_string()); + + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Get, &url); + let mut custom_headers = hyper::header::Headers::new(); + + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + let mut buf = String::new(); + response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + let body = serde_xml_rs::from_str::(&buf) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + + + Ok(GetPetByIdResponse::SuccessfulOperation(body)) + }, + 400 => { + + + Ok(GetPetByIdResponse::InvalidIDSupplied) + }, + 404 => { + + + Ok(GetPetByIdResponse::PetNotFound) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn update_pet(&self, param_body: models::Pet, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/pet?", self.base_path); + + + let body = serde_xml_rs::to_string(¶m_body).expect("impossible to fail to serialize"); + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Put, &url); + let mut custom_headers = hyper::header::Headers::new(); + + let request = request.body(&body); + + custom_headers.set(ContentType(mimetypes::requests::UPDATE_PET.clone())); + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 400 => { + + + Ok(UpdatePetResponse::InvalidIDSupplied) + }, + 404 => { + + + Ok(UpdatePetResponse::PetNotFound) + }, + 405 => { + + + Ok(UpdatePetResponse::ValidationException) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn update_pet_with_form(&self, param_pet_id: i64, param_name: Option, param_status: Option, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/pet/{petId}?", self.base_path, petId=param_pet_id.to_string()); + + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Post, &url); + let mut custom_headers = hyper::header::Headers::new(); + + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 405 => { + + + Ok(UpdatePetWithFormResponse::InvalidInput) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn upload_file(&self, param_pet_id: i64, param_additional_metadata: Option, param_file: Box, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/pet/{petId}/uploadImage?", self.base_path, petId=param_pet_id.to_string()); + + // Form data body + let mut multipart = Multipart::new(); + + if let Ok(Some(param_file)) = param_file.wait() { + match convert_stream_to_string(param_file) { + Ok(param_file) => { + // Add file to multipart form. + multipart.add_text("file", param_file); + }, + Err(err) => return Box::new(futures::done(Err(err))), + } + } + + let mut fields = match multipart.prepare() { + Ok(fields) => fields, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build request: {}", err))))), + }; + + let mut body_string = String::new(); + let body = fields.to_body().read_to_string(&mut body_string); + let boundary = fields.boundary(); + let multipart_header = Mime(TopLevel::Multipart, SubLevel::FormData, vec![(Attr::Boundary, Value::Ext(boundary.to_string()))]); + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Post, &url); + let mut custom_headers = hyper::header::Headers::new(); + + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + let request = request.header(ContentType(multipart_header)) + .body(&body_string); + + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + let mut buf = String::new(); + response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + let body = serde_json::from_str::(&buf)?; + + + + Ok(UploadFileResponse::SuccessfulOperation(body)) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + // Helper function to convert a Stream into a String. The String can then be used to build the HTTP body. + fn convert_stream_to_string(stream: Box, Error=Error> + Send>) -> Result { + + stream.fold(Vec::new(), |mut body, chunk| { + body.extend(chunk.iter()); + future::ok::,Error>(body) + }).wait() + .map_err(|e| ApiError(format!("Unable to fold stream: {}", e))) + .and_then(|body| String::from_utf8(body) + .map_err(|e| ApiError(format!("Failed to convert utf8 stream to String: {}", e)))) + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn delete_order(&self, param_order_id: String, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/store/order/{order_id}?", self.base_path, order_id=param_order_id.to_string()); + + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Delete, &url); + let mut custom_headers = hyper::header::Headers::new(); + + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 400 => { + + + Ok(DeleteOrderResponse::InvalidIDSupplied) + }, + 404 => { + + + Ok(DeleteOrderResponse::OrderNotFound) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn get_inventory(&self, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/store/inventory?", self.base_path); + + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Get, &url); + let mut custom_headers = hyper::header::Headers::new(); + + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + let mut buf = String::new(); + response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + let body = serde_json::from_str::>(&buf)?; + + + + Ok(GetInventoryResponse::SuccessfulOperation(body)) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn get_order_by_id(&self, param_order_id: i64, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/store/order/{order_id}?", self.base_path, order_id=param_order_id.to_string()); + + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Get, &url); + let mut custom_headers = hyper::header::Headers::new(); + + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + let mut buf = String::new(); + response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + let body = serde_xml_rs::from_str::(&buf) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + + + Ok(GetOrderByIdResponse::SuccessfulOperation(body)) + }, + 400 => { + + + Ok(GetOrderByIdResponse::InvalidIDSupplied) + }, + 404 => { + + + Ok(GetOrderByIdResponse::OrderNotFound) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn place_order(&self, param_body: models::Order, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/store/order?", self.base_path); + + + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Post, &url); + let mut custom_headers = hyper::header::Headers::new(); + + let request = request.body(&body); + + custom_headers.set(ContentType(mimetypes::requests::PLACE_ORDER.clone())); + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + let mut buf = String::new(); + response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + let body = serde_xml_rs::from_str::(&buf) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + + + Ok(PlaceOrderResponse::SuccessfulOperation(body)) + }, + 400 => { + + + Ok(PlaceOrderResponse::InvalidOrder) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn create_user(&self, param_body: models::User, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/user?", self.base_path); + + + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Post, &url); + let mut custom_headers = hyper::header::Headers::new(); + + let request = request.body(&body); + + custom_headers.set(ContentType(mimetypes::requests::CREATE_USER.clone())); + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 0 => { + + + Ok(CreateUserResponse::SuccessfulOperation) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn create_users_with_array_input(&self, param_body: &Vec, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/user/createWithArray?", self.base_path); + + + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Post, &url); + let mut custom_headers = hyper::header::Headers::new(); + + let request = request.body(&body); + + custom_headers.set(ContentType(mimetypes::requests::CREATE_USERS_WITH_ARRAY_INPUT.clone())); + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 0 => { + + + Ok(CreateUsersWithArrayInputResponse::SuccessfulOperation) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn create_users_with_list_input(&self, param_body: &Vec, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/user/createWithList?", self.base_path); + + + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Post, &url); + let mut custom_headers = hyper::header::Headers::new(); + + let request = request.body(&body); + + custom_headers.set(ContentType(mimetypes::requests::CREATE_USERS_WITH_LIST_INPUT.clone())); + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 0 => { + + + Ok(CreateUsersWithListInputResponse::SuccessfulOperation) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn delete_user(&self, param_username: String, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/user/{username}?", self.base_path, username=param_username.to_string()); + + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Delete, &url); + let mut custom_headers = hyper::header::Headers::new(); + + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 400 => { + + + Ok(DeleteUserResponse::InvalidUsernameSupplied) + }, + 404 => { + + + Ok(DeleteUserResponse::UserNotFound) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn get_user_by_name(&self, param_username: String, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/user/{username}?", self.base_path, username=param_username.to_string()); + + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Get, &url); + let mut custom_headers = hyper::header::Headers::new(); + + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + let mut buf = String::new(); + response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + let body = serde_xml_rs::from_str::(&buf) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + + + Ok(GetUserByNameResponse::SuccessfulOperation(body)) + }, + 400 => { + + + Ok(GetUserByNameResponse::InvalidUsernameSupplied) + }, + 404 => { + + + Ok(GetUserByNameResponse::UserNotFound) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn login_user(&self, param_username: String, param_password: String, context: &Context) -> Box + Send> { + + // Query parameters + let query_username = format!("username={username}&", username=param_username.to_string()); + let query_password = format!("password={password}&", password=param_password.to_string()); + + + let url = format!("{}/v2/user/login?{username}{password}", self.base_path, username=query_username, password=query_password); + + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Get, &url); + let mut custom_headers = hyper::header::Headers::new(); + + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 200 => { + let mut buf = String::new(); + response.read_to_string(&mut buf).map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + let body = serde_xml_rs::from_str::(&buf) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + + header! { (ResponseXRateLimit, "X-Rate-Limit") => [i32] } + let response_x_rate_limit = response.headers.get::().ok_or_else(|| "Required response header X-Rate-Limit for response 200 was not found.")?; + header! { (ResponseXExpiresAfter, "X-Expires-After") => [chrono::DateTime] } + let response_x_expires_after = response.headers.get::().ok_or_else(|| "Required response header X-Expires-After for response 200 was not found.")?; + + Ok(LoginUserResponse::SuccessfulOperation{ body: body, x_rate_limit: response_x_rate_limit.0.clone(), x_expires_after: response_x_expires_after.0.clone() }) + }, + 400 => { + + + Ok(LoginUserResponse::InvalidUsername) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn logout_user(&self, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/user/logout?", self.base_path); + + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Get, &url); + let mut custom_headers = hyper::header::Headers::new(); + + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 0 => { + + + Ok(LogoutUserResponse::SuccessfulOperation) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + + fn update_user(&self, param_username: String, param_body: models::User, context: &Context) -> Box + Send> { + + + let url = format!("{}/v2/user/{username}?", self.base_path, username=param_username.to_string()); + + + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + + let hyper_client = (self.hyper_client)(); + let request = hyper_client.request(hyper::method::Method::Put, &url); + let mut custom_headers = hyper::header::Headers::new(); + + let request = request.body(&body); + + custom_headers.set(ContentType(mimetypes::requests::UPDATE_USER.clone())); + context.x_span_id.as_ref().map(|header| custom_headers.set(XSpanId(header.clone()))); + + + let request = request.headers(custom_headers); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn parse_response(mut response: hyper::client::response::Response) -> Result { + match response.status.to_u16() { + 400 => { + + + Ok(UpdateUserResponse::InvalidUserSupplied) + }, + 404 => { + + + Ok(UpdateUserResponse::UserNotFound) + }, + code => { + let mut buf = [0; 100]; + let debug_body = match response.read(&mut buf) { + Ok(len) => match str::from_utf8(&buf[..len]) { + Ok(body) => Cow::from(body), + Err(_) => Cow::from(format!("", &buf[..len].to_vec())), + }, + Err(e) => Cow::from(format!("", e)), + }; + Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + response.headers, + debug_body))) + } + } + } + + let result = request.send().map_err(|e| ApiError(format!("No response received: {}", e))).and_then(parse_response); + Box::new(futures::done(result)) + } + +} + +#[derive(Debug)] +pub enum ClientInitError { + InvalidScheme, + InvalidUrl(hyper::error::ParseError), + MissingHost, + SslError(openssl::error::ErrorStack) +} + +impl From for ClientInitError { + fn from(err: hyper::error::ParseError) -> ClientInitError { + ClientInitError::InvalidUrl(err) + } +} + +impl From for ClientInitError { + fn from(err: openssl::error::ErrorStack) -> ClientInitError { + ClientInitError::SslError(err) + } +} + +impl fmt::Display for ClientInitError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + (self as &fmt::Debug).fmt(f) + } +} + +impl error::Error for ClientInitError { + fn description(&self) -> &str { + "Failed to produce a hyper client." + } +} diff --git a/samples/server/petstore/rust-server/src/lib.rs b/samples/server/petstore/rust-server/src/lib.rs new file mode 100644 index 00000000000..5f381501b15 --- /dev/null +++ b/samples/server/petstore/rust-server/src/lib.rs @@ -0,0 +1,590 @@ +#![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +extern crate serde; +#[macro_use] +extern crate serde_derive; +extern crate serde_json; +extern crate serde_xml_rs; +extern crate futures; +extern crate chrono; +extern crate multipart; +#[macro_use] +extern crate lazy_static; +#[macro_use] +extern crate log; + +// Logically this should be in the client and server modules, but rust doesn't allow `macro_use` from a module. +#[cfg(any(feature = "client", feature = "server"))] +#[macro_use] +extern crate hyper; + +extern crate swagger; + +use futures::Stream; +use std::io::Error; + +#[allow(unused_imports)] +use std::collections::HashMap; + +pub use futures::Future; + +#[cfg(any(feature = "client", feature = "server"))] +mod mimetypes; + +pub use swagger::{ApiError, Context, ContextWrapper}; + + +#[derive(Debug, PartialEq)] +pub enum TestSpecialTagsResponse { + SuccessfulOperation ( models::Client ) , +} + +#[derive(Debug, PartialEq)] +pub enum FakeOuterBooleanSerializeResponse { + OutputBoolean ( models::OuterBoolean ) , +} + +#[derive(Debug, PartialEq)] +pub enum FakeOuterCompositeSerializeResponse { + OutputComposite ( models::OuterComposite ) , +} + +#[derive(Debug, PartialEq)] +pub enum FakeOuterNumberSerializeResponse { + OutputNumber ( models::OuterNumber ) , +} + +#[derive(Debug, PartialEq)] +pub enum FakeOuterStringSerializeResponse { + OutputString ( models::OuterString ) , +} + +#[derive(Debug, PartialEq)] +pub enum TestClientModelResponse { + SuccessfulOperation ( models::Client ) , +} + +#[derive(Debug, PartialEq)] +pub enum TestEndpointParametersResponse { + InvalidUsernameSupplied , + UserNotFound , +} + +#[derive(Debug, PartialEq)] +pub enum TestEnumParametersResponse { + InvalidRequest , + NotFound , +} + +#[derive(Debug, PartialEq)] +pub enum TestInlineAdditionalPropertiesResponse { + SuccessfulOperation , +} + +#[derive(Debug, PartialEq)] +pub enum TestJsonFormDataResponse { + SuccessfulOperation , +} + +#[derive(Debug, PartialEq)] +pub enum TestClassnameResponse { + SuccessfulOperation ( models::Client ) , +} + +#[derive(Debug, PartialEq)] +pub enum AddPetResponse { + InvalidInput , +} + +#[derive(Debug, PartialEq)] +pub enum DeletePetResponse { + InvalidPetValue , +} + +#[derive(Debug, PartialEq)] +pub enum FindPetsByStatusResponse { + SuccessfulOperation ( Vec ) , + InvalidStatusValue , +} + +#[derive(Debug, PartialEq)] +pub enum FindPetsByTagsResponse { + SuccessfulOperation ( Vec ) , + InvalidTagValue , +} + +#[derive(Debug, PartialEq)] +pub enum GetPetByIdResponse { + SuccessfulOperation ( models::Pet ) , + InvalidIDSupplied , + PetNotFound , +} + +#[derive(Debug, PartialEq)] +pub enum UpdatePetResponse { + InvalidIDSupplied , + PetNotFound , + ValidationException , +} + +#[derive(Debug, PartialEq)] +pub enum UpdatePetWithFormResponse { + InvalidInput , +} + +#[derive(Debug, PartialEq)] +pub enum UploadFileResponse { + SuccessfulOperation ( models::ApiResponse ) , +} + +#[derive(Debug, PartialEq)] +pub enum DeleteOrderResponse { + InvalidIDSupplied , + OrderNotFound , +} + +#[derive(Debug, PartialEq)] +pub enum GetInventoryResponse { + SuccessfulOperation ( HashMap ) , +} + +#[derive(Debug, PartialEq)] +pub enum GetOrderByIdResponse { + SuccessfulOperation ( models::Order ) , + InvalidIDSupplied , + OrderNotFound , +} + +#[derive(Debug, PartialEq)] +pub enum PlaceOrderResponse { + SuccessfulOperation ( models::Order ) , + InvalidOrder , +} + +#[derive(Debug, PartialEq)] +pub enum CreateUserResponse { + SuccessfulOperation , +} + +#[derive(Debug, PartialEq)] +pub enum CreateUsersWithArrayInputResponse { + SuccessfulOperation , +} + +#[derive(Debug, PartialEq)] +pub enum CreateUsersWithListInputResponse { + SuccessfulOperation , +} + +#[derive(Debug, PartialEq)] +pub enum DeleteUserResponse { + InvalidUsernameSupplied , + UserNotFound , +} + +#[derive(Debug, PartialEq)] +pub enum GetUserByNameResponse { + SuccessfulOperation ( models::User ) , + InvalidUsernameSupplied , + UserNotFound , +} + +#[derive(Debug, PartialEq)] +pub enum LoginUserResponse { + SuccessfulOperation { body: String, x_rate_limit: i32, x_expires_after: chrono::DateTime } , + InvalidUsername , +} + +#[derive(Debug, PartialEq)] +pub enum LogoutUserResponse { + SuccessfulOperation , +} + +#[derive(Debug, PartialEq)] +pub enum UpdateUserResponse { + InvalidUserSupplied , + UserNotFound , +} + + +/// API +pub trait Api { + + /// To test special tags + fn test_special_tags(&self, body: models::Client, context: &Context) -> Box + Send>; + + + fn fake_outer_boolean_serialize(&self, body: Option, context: &Context) -> Box + Send>; + + + fn fake_outer_composite_serialize(&self, body: Option, context: &Context) -> Box + Send>; + + + fn fake_outer_number_serialize(&self, body: Option, context: &Context) -> Box + Send>; + + + fn fake_outer_string_serialize(&self, body: Option, context: &Context) -> Box + Send>; + + /// To test \"client\" model + fn test_client_model(&self, body: models::Client, context: &Context) -> Box + Send>; + + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option, context: &Context) -> Box + Send>; + + /// To test enum parameters + fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec>, enum_form_string: Option, enum_header_string_array: Option<&Vec>, enum_header_string: Option, enum_query_string_array: Option<&Vec>, enum_query_string: Option, enum_query_integer: Option, enum_query_double: Option, context: &Context) -> Box + Send>; + + /// test inline additionalProperties + fn test_inline_additional_properties(&self, param: object, context: &Context) -> Box + Send>; + + /// test json serialization of form data + fn test_json_form_data(&self, param: String, param2: String, context: &Context) -> Box + Send>; + + /// To test class name in snake case + fn test_classname(&self, body: models::Client, context: &Context) -> Box + Send>; + + /// Add a new pet to the store + fn add_pet(&self, body: models::Pet, context: &Context) -> Box + Send>; + + /// Deletes a pet + fn delete_pet(&self, pet_id: i64, api_key: Option, context: &Context) -> Box + Send>; + + /// Finds Pets by status + fn find_pets_by_status(&self, status: &Vec, context: &Context) -> Box + Send>; + + /// Finds Pets by tags + fn find_pets_by_tags(&self, tags: &Vec, context: &Context) -> Box + Send>; + + /// Find pet by ID + fn get_pet_by_id(&self, pet_id: i64, context: &Context) -> Box + Send>; + + /// Update an existing pet + fn update_pet(&self, body: models::Pet, context: &Context) -> Box + Send>; + + /// Updates a pet in the store with form data + fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option, context: &Context) -> Box + Send>; + + /// uploads an image + fn upload_file(&self, pet_id: i64, additional_metadata: Option, file: Box, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box + Send>; + + /// Delete purchase order by ID + fn delete_order(&self, order_id: String, context: &Context) -> Box + Send>; + + /// Returns pet inventories by status + fn get_inventory(&self, context: &Context) -> Box + Send>; + + /// Find purchase order by ID + fn get_order_by_id(&self, order_id: i64, context: &Context) -> Box + Send>; + + /// Place an order for a pet + fn place_order(&self, body: models::Order, context: &Context) -> Box + Send>; + + /// Create user + fn create_user(&self, body: models::User, context: &Context) -> Box + Send>; + + /// Creates list of users with given input array + fn create_users_with_array_input(&self, body: &Vec, context: &Context) -> Box + Send>; + + /// Creates list of users with given input array + fn create_users_with_list_input(&self, body: &Vec, context: &Context) -> Box + Send>; + + /// Delete user + fn delete_user(&self, username: String, context: &Context) -> Box + Send>; + + /// Get user by user name + fn get_user_by_name(&self, username: String, context: &Context) -> Box + Send>; + + /// Logs user into the system + fn login_user(&self, username: String, password: String, context: &Context) -> Box + Send>; + + /// Logs out current logged in user session + fn logout_user(&self, context: &Context) -> Box + Send>; + + /// Updated user + fn update_user(&self, username: String, body: models::User, context: &Context) -> Box + Send>; + +} + +/// API without a `Context` +pub trait ApiNoContext { + + /// To test special tags + fn test_special_tags(&self, body: models::Client) -> Box + Send>; + + + fn fake_outer_boolean_serialize(&self, body: Option) -> Box + Send>; + + + fn fake_outer_composite_serialize(&self, body: Option) -> Box + Send>; + + + fn fake_outer_number_serialize(&self, body: Option) -> Box + Send>; + + + fn fake_outer_string_serialize(&self, body: Option) -> Box + Send>; + + /// To test \"client\" model + fn test_client_model(&self, body: models::Client) -> Box + Send>; + + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option) -> Box + Send>; + + /// To test enum parameters + fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec>, enum_form_string: Option, enum_header_string_array: Option<&Vec>, enum_header_string: Option, enum_query_string_array: Option<&Vec>, enum_query_string: Option, enum_query_integer: Option, enum_query_double: Option) -> Box + Send>; + + /// test inline additionalProperties + fn test_inline_additional_properties(&self, param: object) -> Box + Send>; + + /// test json serialization of form data + fn test_json_form_data(&self, param: String, param2: String) -> Box + Send>; + + /// To test class name in snake case + fn test_classname(&self, body: models::Client) -> Box + Send>; + + /// Add a new pet to the store + fn add_pet(&self, body: models::Pet) -> Box + Send>; + + /// Deletes a pet + fn delete_pet(&self, pet_id: i64, api_key: Option) -> Box + Send>; + + /// Finds Pets by status + fn find_pets_by_status(&self, status: &Vec) -> Box + Send>; + + /// Finds Pets by tags + fn find_pets_by_tags(&self, tags: &Vec) -> Box + Send>; + + /// Find pet by ID + fn get_pet_by_id(&self, pet_id: i64) -> Box + Send>; + + /// Update an existing pet + fn update_pet(&self, body: models::Pet) -> Box + Send>; + + /// Updates a pet in the store with form data + fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option) -> Box + Send>; + + /// uploads an image + fn upload_file(&self, pet_id: i64, additional_metadata: Option, file: Box, Error=Error> + Send>>, Error=Error> + Send>) -> Box + Send>; + + /// Delete purchase order by ID + fn delete_order(&self, order_id: String) -> Box + Send>; + + /// Returns pet inventories by status + fn get_inventory(&self) -> Box + Send>; + + /// Find purchase order by ID + fn get_order_by_id(&self, order_id: i64) -> Box + Send>; + + /// Place an order for a pet + fn place_order(&self, body: models::Order) -> Box + Send>; + + /// Create user + fn create_user(&self, body: models::User) -> Box + Send>; + + /// Creates list of users with given input array + fn create_users_with_array_input(&self, body: &Vec) -> Box + Send>; + + /// Creates list of users with given input array + fn create_users_with_list_input(&self, body: &Vec) -> Box + Send>; + + /// Delete user + fn delete_user(&self, username: String) -> Box + Send>; + + /// Get user by user name + fn get_user_by_name(&self, username: String) -> Box + Send>; + + /// Logs user into the system + fn login_user(&self, username: String, password: String) -> Box + Send>; + + /// Logs out current logged in user session + fn logout_user(&self) -> Box + Send>; + + /// Updated user + fn update_user(&self, username: String, body: models::User) -> Box + Send>; + +} + +/// Trait to extend an API to make it easy to bind it to a context. +pub trait ContextWrapperExt<'a> where Self: Sized { + /// Binds this API to a context. + fn with_context(self: &'a Self, context: Context) -> ContextWrapper<'a, Self>; +} + +impl<'a, T: Api + Sized> ContextWrapperExt<'a> for T { + fn with_context(self: &'a T, context: Context) -> ContextWrapper<'a, T> { + ContextWrapper::::new(self, context) + } +} + +impl<'a, T: Api> ApiNoContext for ContextWrapper<'a, T> { + + /// To test special tags + fn test_special_tags(&self, body: models::Client) -> Box + Send> { + self.api().test_special_tags(body, &self.context()) + } + + + fn fake_outer_boolean_serialize(&self, body: Option) -> Box + Send> { + self.api().fake_outer_boolean_serialize(body, &self.context()) + } + + + fn fake_outer_composite_serialize(&self, body: Option) -> Box + Send> { + self.api().fake_outer_composite_serialize(body, &self.context()) + } + + + fn fake_outer_number_serialize(&self, body: Option) -> Box + Send> { + self.api().fake_outer_number_serialize(body, &self.context()) + } + + + fn fake_outer_string_serialize(&self, body: Option) -> Box + Send> { + self.api().fake_outer_string_serialize(body, &self.context()) + } + + /// To test \"client\" model + fn test_client_model(&self, body: models::Client) -> Box + Send> { + self.api().test_client_model(body, &self.context()) + } + + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option) -> Box + Send> { + self.api().test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer, int32, int64, float, string, binary, date, date_time, password, callback, &self.context()) + } + + /// To test enum parameters + fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec>, enum_form_string: Option, enum_header_string_array: Option<&Vec>, enum_header_string: Option, enum_query_string_array: Option<&Vec>, enum_query_string: Option, enum_query_integer: Option, enum_query_double: Option) -> Box + Send> { + self.api().test_enum_parameters(enum_form_string_array, enum_form_string, enum_header_string_array, enum_header_string, enum_query_string_array, enum_query_string, enum_query_integer, enum_query_double, &self.context()) + } + + /// test inline additionalProperties + fn test_inline_additional_properties(&self, param: object) -> Box + Send> { + self.api().test_inline_additional_properties(param, &self.context()) + } + + /// test json serialization of form data + fn test_json_form_data(&self, param: String, param2: String) -> Box + Send> { + self.api().test_json_form_data(param, param2, &self.context()) + } + + /// To test class name in snake case + fn test_classname(&self, body: models::Client) -> Box + Send> { + self.api().test_classname(body, &self.context()) + } + + /// Add a new pet to the store + fn add_pet(&self, body: models::Pet) -> Box + Send> { + self.api().add_pet(body, &self.context()) + } + + /// Deletes a pet + fn delete_pet(&self, pet_id: i64, api_key: Option) -> Box + Send> { + self.api().delete_pet(pet_id, api_key, &self.context()) + } + + /// Finds Pets by status + fn find_pets_by_status(&self, status: &Vec) -> Box + Send> { + self.api().find_pets_by_status(status, &self.context()) + } + + /// Finds Pets by tags + fn find_pets_by_tags(&self, tags: &Vec) -> Box + Send> { + self.api().find_pets_by_tags(tags, &self.context()) + } + + /// Find pet by ID + fn get_pet_by_id(&self, pet_id: i64) -> Box + Send> { + self.api().get_pet_by_id(pet_id, &self.context()) + } + + /// Update an existing pet + fn update_pet(&self, body: models::Pet) -> Box + Send> { + self.api().update_pet(body, &self.context()) + } + + /// Updates a pet in the store with form data + fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option) -> Box + Send> { + self.api().update_pet_with_form(pet_id, name, status, &self.context()) + } + + /// uploads an image + fn upload_file(&self, pet_id: i64, additional_metadata: Option, file: Box, Error=Error> + Send>>, Error=Error> + Send>) -> Box + Send> { + self.api().upload_file(pet_id, additional_metadata, file, &self.context()) + } + + /// Delete purchase order by ID + fn delete_order(&self, order_id: String) -> Box + Send> { + self.api().delete_order(order_id, &self.context()) + } + + /// Returns pet inventories by status + fn get_inventory(&self) -> Box + Send> { + self.api().get_inventory(&self.context()) + } + + /// Find purchase order by ID + fn get_order_by_id(&self, order_id: i64) -> Box + Send> { + self.api().get_order_by_id(order_id, &self.context()) + } + + /// Place an order for a pet + fn place_order(&self, body: models::Order) -> Box + Send> { + self.api().place_order(body, &self.context()) + } + + /// Create user + fn create_user(&self, body: models::User) -> Box + Send> { + self.api().create_user(body, &self.context()) + } + + /// Creates list of users with given input array + fn create_users_with_array_input(&self, body: &Vec) -> Box + Send> { + self.api().create_users_with_array_input(body, &self.context()) + } + + /// Creates list of users with given input array + fn create_users_with_list_input(&self, body: &Vec) -> Box + Send> { + self.api().create_users_with_list_input(body, &self.context()) + } + + /// Delete user + fn delete_user(&self, username: String) -> Box + Send> { + self.api().delete_user(username, &self.context()) + } + + /// Get user by user name + fn get_user_by_name(&self, username: String) -> Box + Send> { + self.api().get_user_by_name(username, &self.context()) + } + + /// Logs user into the system + fn login_user(&self, username: String, password: String) -> Box + Send> { + self.api().login_user(username, password, &self.context()) + } + + /// Logs out current logged in user session + fn logout_user(&self) -> Box + Send> { + self.api().logout_user(&self.context()) + } + + /// Updated user + fn update_user(&self, username: String, body: models::User) -> Box + Send> { + self.api().update_user(username, body, &self.context()) + } + +} + +#[cfg(feature = "client")] +pub mod client; + +// Re-export Client as a top-level name +#[cfg(feature = "client")] +pub use self::client::Client; + +#[cfg(feature = "server")] +pub mod server; + +// Re-export router() as a top-level name +#[cfg(feature = "server")] +pub use self::server::router; + +pub mod models; diff --git a/samples/server/petstore/rust-server/src/mimetypes.rs b/samples/server/petstore/rust-server/src/mimetypes.rs new file mode 100644 index 00000000000..401c05bedd5 --- /dev/null +++ b/samples/server/petstore/rust-server/src/mimetypes.rs @@ -0,0 +1,121 @@ +/// mime types for requests and responses + +pub mod responses { + use hyper::mime::*; + + // The macro is called per-operation to beat the recursion limit + /// Create Mime objects for the response content types for TestSpecialTags + lazy_static! { + pub static ref TEST_SPECIAL_TAGS_SUCCESSFUL_OPERATION: Mime = mime!(Application/Json); + } + /// Create Mime objects for the response content types for TestClientModel + lazy_static! { + pub static ref TEST_CLIENT_MODEL_SUCCESSFUL_OPERATION: Mime = mime!(Application/Json); + } + /// Create Mime objects for the response content types for TestClassname + lazy_static! { + pub static ref TEST_CLASSNAME_SUCCESSFUL_OPERATION: Mime = mime!(Application/Json); + } + /// Create Mime objects for the response content types for FindPetsByStatus + lazy_static! { + pub static ref FIND_PETS_BY_STATUS_SUCCESSFUL_OPERATION: Mime = mime!(Application/Xml); + } + /// Create Mime objects for the response content types for FindPetsByTags + lazy_static! { + pub static ref FIND_PETS_BY_TAGS_SUCCESSFUL_OPERATION: Mime = mime!(Application/Xml); + } + /// Create Mime objects for the response content types for GetPetById + lazy_static! { + pub static ref GET_PET_BY_ID_SUCCESSFUL_OPERATION: Mime = mime!(Application/Xml); + } + /// Create Mime objects for the response content types for UploadFile + lazy_static! { + pub static ref UPLOAD_FILE_SUCCESSFUL_OPERATION: Mime = mime!(Application/Json); + } + /// Create Mime objects for the response content types for GetInventory + lazy_static! { + pub static ref GET_INVENTORY_SUCCESSFUL_OPERATION: Mime = mime!(Application/Json); + } + /// Create Mime objects for the response content types for GetOrderById + lazy_static! { + pub static ref GET_ORDER_BY_ID_SUCCESSFUL_OPERATION: Mime = mime!(Application/Xml); + } + /// Create Mime objects for the response content types for PlaceOrder + lazy_static! { + pub static ref PLACE_ORDER_SUCCESSFUL_OPERATION: Mime = mime!(Application/Xml); + } + /// Create Mime objects for the response content types for GetUserByName + lazy_static! { + pub static ref GET_USER_BY_NAME_SUCCESSFUL_OPERATION: Mime = mime!(Application/Xml); + } + /// Create Mime objects for the response content types for LoginUser + lazy_static! { + pub static ref LOGIN_USER_SUCCESSFUL_OPERATION: Mime = mime!(Application/Xml); + } + +} + +pub mod requests { + use hyper::mime::*; + /// Create Mime objects for the request content types for TestSpecialTags + lazy_static! { + pub static ref TEST_SPECIAL_TAGS: Mime = mime!(Application/Json); + } + /// Create Mime objects for the request content types for FakeOuterBooleanSerialize + lazy_static! { + pub static ref FAKE_OUTER_BOOLEAN_SERIALIZE: Mime = mime!(Application/Json); + } + /// Create Mime objects for the request content types for FakeOuterCompositeSerialize + lazy_static! { + pub static ref FAKE_OUTER_COMPOSITE_SERIALIZE: Mime = mime!(Application/Json); + } + /// Create Mime objects for the request content types for FakeOuterNumberSerialize + lazy_static! { + pub static ref FAKE_OUTER_NUMBER_SERIALIZE: Mime = mime!(Application/Json); + } + /// Create Mime objects for the request content types for FakeOuterStringSerialize + lazy_static! { + pub static ref FAKE_OUTER_STRING_SERIALIZE: Mime = mime!(Application/Json); + } + /// Create Mime objects for the request content types for TestClientModel + lazy_static! { + pub static ref TEST_CLIENT_MODEL: Mime = mime!(Application/Json); + } + /// Create Mime objects for the request content types for TestInlineAdditionalProperties + lazy_static! { + pub static ref TEST_INLINE_ADDITIONAL_PROPERTIES: Mime = mime!(Application/Json); + } + /// Create Mime objects for the request content types for TestClassname + lazy_static! { + pub static ref TEST_CLASSNAME: Mime = mime!(Application/Json); + } + /// Create Mime objects for the request content types for AddPet + lazy_static! { + pub static ref ADD_PET: Mime = mime!(Application/Json); + } + /// Create Mime objects for the request content types for UpdatePet + lazy_static! { + pub static ref UPDATE_PET: Mime = mime!(Application/Json); + } + /// Create Mime objects for the request content types for PlaceOrder + lazy_static! { + pub static ref PLACE_ORDER: Mime = mime!(Application/Json); + } + /// Create Mime objects for the request content types for CreateUser + lazy_static! { + pub static ref CREATE_USER: Mime = mime!(Application/Json); + } + /// Create Mime objects for the request content types for CreateUsersWithArrayInput + lazy_static! { + pub static ref CREATE_USERS_WITH_ARRAY_INPUT: Mime = mime!(Application/Json); + } + /// Create Mime objects for the request content types for CreateUsersWithListInput + lazy_static! { + pub static ref CREATE_USERS_WITH_LIST_INPUT: Mime = mime!(Application/Json); + } + /// Create Mime objects for the request content types for UpdateUser + lazy_static! { + pub static ref UPDATE_USER: Mime = mime!(Application/Json); + } + +} diff --git a/samples/server/petstore/rust-server/src/models.rs b/samples/server/petstore/rust-server/src/models.rs new file mode 100644 index 00000000000..e956aae2bb9 --- /dev/null +++ b/samples/server/petstore/rust-server/src/models.rs @@ -0,0 +1,1037 @@ +#![allow(unused_imports, unused_qualifications, unused_extern_crates)] +extern crate chrono; +extern crate uuid; + +use serde_xml_rs; +use serde::ser::Serializer; + +use std::collections::HashMap; +use models; +use swagger; + + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct AdditionalPropertiesClass { + #[serde(rename = "map_property")] + #[serde(skip_serializing_if="Option::is_none")] + pub map_property: Option>, + + #[serde(rename = "map_of_map_property")] + #[serde(skip_serializing_if="Option::is_none")] + pub map_of_map_property: Option>>, + +} + +impl AdditionalPropertiesClass { + pub fn new() -> AdditionalPropertiesClass { + AdditionalPropertiesClass { + map_property: None, + map_of_map_property: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Animal { + #[serde(rename = "className")] + pub class_name: String, + + #[serde(rename = "color")] + #[serde(skip_serializing_if="Option::is_none")] + pub color: Option, + +} + +impl Animal { + pub fn new(class_name: String, ) -> Animal { + Animal { + class_name: class_name, + color: Some("red".to_string()), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct AnimalFarm(Vec); + +impl ::std::convert::From> for AnimalFarm { + fn from(x: Vec) -> Self { + AnimalFarm(x) + } +} + +impl ::std::convert::From for Vec { + fn from(x: AnimalFarm) -> Self { + x.0 + } +} + +impl ::std::iter::FromIterator for AnimalFarm { + fn from_iter>(u: U) -> Self { + AnimalFarm(Vec::::from_iter(u)) + } +} + +impl ::std::iter::IntoIterator for AnimalFarm { + type Item = Animal; + type IntoIter = ::std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a> ::std::iter::IntoIterator for &'a AnimalFarm { + type Item = &'a Animal; + type IntoIter = ::std::slice::Iter<'a, Animal>; + + fn into_iter(self) -> Self::IntoIter { + (&self.0).into_iter() + } +} + +impl<'a> ::std::iter::IntoIterator for &'a mut AnimalFarm { + type Item = &'a mut Animal; + type IntoIter = ::std::slice::IterMut<'a, Animal>; + + fn into_iter(self) -> Self::IntoIter { + (&mut self.0).into_iter() + } +} + +impl ::std::ops::Deref for AnimalFarm { + type Target = Vec; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl ::std::ops::DerefMut for AnimalFarm { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ApiResponse { + #[serde(rename = "code")] + #[serde(skip_serializing_if="Option::is_none")] + pub code: Option, + + #[serde(rename = "type")] + #[serde(skip_serializing_if="Option::is_none")] + pub _type: Option, + + #[serde(rename = "message")] + #[serde(skip_serializing_if="Option::is_none")] + pub message: Option, + +} + +impl ApiResponse { + pub fn new() -> ApiResponse { + ApiResponse { + code: None, + _type: None, + message: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ArrayOfArrayOfNumberOnly { + #[serde(rename = "ArrayArrayNumber")] + #[serde(skip_serializing_if="Option::is_none")] + pub array_array_number: Option>>, + +} + +impl ArrayOfArrayOfNumberOnly { + pub fn new() -> ArrayOfArrayOfNumberOnly { + ArrayOfArrayOfNumberOnly { + array_array_number: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ArrayOfNumberOnly { + #[serde(rename = "ArrayNumber")] + #[serde(skip_serializing_if="Option::is_none")] + pub array_number: Option>, + +} + +impl ArrayOfNumberOnly { + pub fn new() -> ArrayOfNumberOnly { + ArrayOfNumberOnly { + array_number: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ArrayTest { + #[serde(rename = "array_of_string")] + #[serde(skip_serializing_if="Option::is_none")] + pub array_of_string: Option>, + + #[serde(rename = "array_array_of_integer")] + #[serde(skip_serializing_if="Option::is_none")] + pub array_array_of_integer: Option>>, + + #[serde(rename = "array_array_of_model")] + #[serde(skip_serializing_if="Option::is_none")] + pub array_array_of_model: Option>>, + +} + +impl ArrayTest { + pub fn new() -> ArrayTest { + ArrayTest { + array_of_string: None, + array_array_of_integer: None, + array_array_of_model: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Capitalization { + #[serde(rename = "smallCamel")] + #[serde(skip_serializing_if="Option::is_none")] + pub small_camel: Option, + + #[serde(rename = "CapitalCamel")] + #[serde(skip_serializing_if="Option::is_none")] + pub capital_camel: Option, + + #[serde(rename = "small_Snake")] + #[serde(skip_serializing_if="Option::is_none")] + pub small_snake: Option, + + #[serde(rename = "Capital_Snake")] + #[serde(skip_serializing_if="Option::is_none")] + pub capital_snake: Option, + + #[serde(rename = "SCA_ETH_Flow_Points")] + #[serde(skip_serializing_if="Option::is_none")] + pub sca_eth_flow_points: Option, + + /// Name of the pet + #[serde(rename = "ATT_NAME")] + #[serde(skip_serializing_if="Option::is_none")] + pub att_name: Option, + +} + +impl Capitalization { + pub fn new() -> Capitalization { + Capitalization { + small_camel: None, + capital_camel: None, + small_snake: None, + capital_snake: None, + sca_eth_flow_points: None, + att_name: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename = "Category")] +pub struct Category { + #[serde(rename = "id")] + #[serde(skip_serializing_if="Option::is_none")] + pub id: Option, + + #[serde(rename = "name")] + #[serde(skip_serializing_if="Option::is_none")] + pub name: Option, + +} + +impl Category { + pub fn new() -> Category { + Category { + id: None, + name: None, + } + } +} + +/// Model for testing model with \"_class\" property +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ClassModel { + #[serde(rename = "_class")] + #[serde(skip_serializing_if="Option::is_none")] + pub _class: Option, + +} + +impl ClassModel { + pub fn new() -> ClassModel { + ClassModel { + _class: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Client { + #[serde(rename = "client")] + #[serde(skip_serializing_if="Option::is_none")] + pub client: Option, + +} + +impl Client { + pub fn new() -> Client { + Client { + client: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct EnumArrays { + // Note: inline enums are not fully supported by swagger-codegen + #[serde(rename = "just_symbol")] + #[serde(skip_serializing_if="Option::is_none")] + pub just_symbol: Option, + + // Note: inline enums are not fully supported by swagger-codegen + #[serde(rename = "array_enum")] + #[serde(skip_serializing_if="Option::is_none")] + pub array_enum: Option>, + +} + +impl EnumArrays { + pub fn new() -> EnumArrays { + EnumArrays { + just_symbol: None, + array_enum: None, + } + } +} + +/// Enumeration of values. +/// Since this enum's variants do not hold data, we can easily define them them as `#[repr(C)]` +/// which helps with FFI. +#[allow(non_camel_case_types)] +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize, Deserialize)] +pub enum EnumClass { + #[serde(rename = "_abc")] + _ABC, + #[serde(rename = "-efg")] + _EFG, + #[serde(rename = "(xyz)")] + _XYZ_, +} + +impl ::std::fmt::Display for EnumClass { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + match *self { + EnumClass::_ABC => write!(f, "{}", "_abc"), + EnumClass::_EFG => write!(f, "{}", "-efg"), + EnumClass::_XYZ_ => write!(f, "{}", "(xyz)"), + } + } +} + +impl ::std::str::FromStr for EnumClass { + type Err = (); + fn from_str(s: &str) -> Result { + match s { + "_abc" => Ok(EnumClass::_ABC), + "-efg" => Ok(EnumClass::_EFG), + "(xyz)" => Ok(EnumClass::_XYZ_), + _ => Err(()), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct EnumTest { + // Note: inline enums are not fully supported by swagger-codegen + #[serde(rename = "enum_string")] + #[serde(skip_serializing_if="Option::is_none")] + pub enum_string: Option, + + // Note: inline enums are not fully supported by swagger-codegen + #[serde(rename = "enum_integer")] + #[serde(skip_serializing_if="Option::is_none")] + pub enum_integer: Option, + + // Note: inline enums are not fully supported by swagger-codegen + #[serde(rename = "enum_number")] + #[serde(skip_serializing_if="Option::is_none")] + pub enum_number: Option, + + #[serde(rename = "outerEnum")] + #[serde(skip_serializing_if="Option::is_none")] + pub outer_enum: Option, + +} + +impl EnumTest { + pub fn new() -> EnumTest { + EnumTest { + enum_string: None, + enum_integer: None, + enum_number: None, + outer_enum: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FormatTest { + #[serde(rename = "integer")] + #[serde(skip_serializing_if="Option::is_none")] + pub integer: Option, + + #[serde(rename = "int32")] + #[serde(skip_serializing_if="Option::is_none")] + pub int32: Option, + + #[serde(rename = "int64")] + #[serde(skip_serializing_if="Option::is_none")] + pub int64: Option, + + #[serde(rename = "number")] + pub number: f64, + + #[serde(rename = "float")] + #[serde(skip_serializing_if="Option::is_none")] + pub float: Option, + + #[serde(rename = "double")] + #[serde(skip_serializing_if="Option::is_none")] + pub double: Option, + + #[serde(rename = "string")] + #[serde(skip_serializing_if="Option::is_none")] + pub string: Option, + + #[serde(rename = "byte")] + pub byte: swagger::ByteArray, + + #[serde(rename = "binary")] + #[serde(skip_serializing_if="Option::is_none")] + pub binary: Option, + + #[serde(rename = "date")] + pub date: chrono::DateTime, + + #[serde(rename = "dateTime")] + #[serde(skip_serializing_if="Option::is_none")] + pub date_time: Option>, + + #[serde(rename = "uuid")] + #[serde(skip_serializing_if="Option::is_none")] + pub uuid: Option, + + #[serde(rename = "password")] + pub password: String, + +} + +impl FormatTest { + pub fn new(number: f64, byte: swagger::ByteArray, date: chrono::DateTime, password: String, ) -> FormatTest { + FormatTest { + integer: None, + int32: None, + int64: None, + number: number, + float: None, + double: None, + string: None, + byte: byte, + binary: None, + date: date, + date_time: None, + uuid: None, + password: password, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct HasOnlyReadOnly { + #[serde(rename = "bar")] + #[serde(skip_serializing_if="Option::is_none")] + pub bar: Option, + + #[serde(rename = "foo")] + #[serde(skip_serializing_if="Option::is_none")] + pub foo: Option, + +} + +impl HasOnlyReadOnly { + pub fn new() -> HasOnlyReadOnly { + HasOnlyReadOnly { + bar: None, + foo: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct List { + #[serde(rename = "123-list")] + #[serde(skip_serializing_if="Option::is_none")] + pub _123_list: Option, + +} + +impl List { + pub fn new() -> List { + List { + _123_list: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct MapTest { + #[serde(rename = "map_map_of_string")] + #[serde(skip_serializing_if="Option::is_none")] + pub map_map_of_string: Option>>, + + // Note: inline enums are not fully supported by swagger-codegen + #[serde(rename = "map_of_enum_string")] + #[serde(skip_serializing_if="Option::is_none")] + pub map_of_enum_string: Option>, + +} + +impl MapTest { + pub fn new() -> MapTest { + MapTest { + map_map_of_string: None, + map_of_enum_string: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct MixedPropertiesAndAdditionalPropertiesClass { + #[serde(rename = "uuid")] + #[serde(skip_serializing_if="Option::is_none")] + pub uuid: Option, + + #[serde(rename = "dateTime")] + #[serde(skip_serializing_if="Option::is_none")] + pub date_time: Option>, + + #[serde(rename = "map")] + #[serde(skip_serializing_if="Option::is_none")] + pub map: Option>, + +} + +impl MixedPropertiesAndAdditionalPropertiesClass { + pub fn new() -> MixedPropertiesAndAdditionalPropertiesClass { + MixedPropertiesAndAdditionalPropertiesClass { + uuid: None, + date_time: None, + map: None, + } + } +} + +/// Model for testing model name starting with number +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename = "Name")] +pub struct Model200Response { + #[serde(rename = "name")] + #[serde(skip_serializing_if="Option::is_none")] + pub name: Option, + + #[serde(rename = "class")] + #[serde(skip_serializing_if="Option::is_none")] + pub class: Option, + +} + +impl Model200Response { + pub fn new() -> Model200Response { + Model200Response { + name: None, + class: None, + } + } +} + +/// Model for testing reserved words +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename = "Return")] +pub struct ModelReturn { + #[serde(rename = "return")] + #[serde(skip_serializing_if="Option::is_none")] + pub _return: Option, + +} + +impl ModelReturn { + pub fn new() -> ModelReturn { + ModelReturn { + _return: None, + } + } +} + +/// Model for testing model name same as property name +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename = "Name")] +pub struct Name { + #[serde(rename = "name")] + pub name: i32, + + #[serde(rename = "snake_case")] + #[serde(skip_serializing_if="Option::is_none")] + pub snake_case: Option, + + #[serde(rename = "property")] + #[serde(skip_serializing_if="Option::is_none")] + pub property: Option, + + #[serde(rename = "123Number")] + #[serde(skip_serializing_if="Option::is_none")] + pub _123_number: Option, + +} + +impl Name { + pub fn new(name: i32, ) -> Name { + Name { + name: name, + snake_case: None, + property: None, + _123_number: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct NumberOnly { + #[serde(rename = "JustNumber")] + #[serde(skip_serializing_if="Option::is_none")] + pub just_number: Option, + +} + +impl NumberOnly { + pub fn new() -> NumberOnly { + NumberOnly { + just_number: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename = "Order")] +pub struct Order { + #[serde(rename = "id")] + #[serde(skip_serializing_if="Option::is_none")] + pub id: Option, + + #[serde(rename = "petId")] + #[serde(skip_serializing_if="Option::is_none")] + pub pet_id: Option, + + #[serde(rename = "quantity")] + #[serde(skip_serializing_if="Option::is_none")] + pub quantity: Option, + + #[serde(rename = "shipDate")] + #[serde(skip_serializing_if="Option::is_none")] + pub ship_date: Option>, + + /// Order Status + // Note: inline enums are not fully supported by swagger-codegen + #[serde(rename = "status")] + #[serde(skip_serializing_if="Option::is_none")] + pub status: Option, + + #[serde(rename = "complete")] + #[serde(skip_serializing_if="Option::is_none")] + pub complete: Option, + +} + +impl Order { + pub fn new() -> Order { + Order { + id: None, + pet_id: None, + quantity: None, + ship_date: None, + status: None, + complete: Some(false), + } + } +} + +#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] + +pub struct OuterBoolean(bool); + +impl ::std::convert::From for OuterBoolean { + fn from(x: bool) -> Self { + OuterBoolean(x) + } +} + +impl ::std::convert::From for bool { + fn from(x: OuterBoolean) -> Self { + x.0 + } +} + +impl ::std::ops::Deref for OuterBoolean { + type Target = bool; + fn deref(&self) -> &bool { + &self.0 + } +} + +impl ::std::ops::DerefMut for OuterBoolean { + fn deref_mut(&mut self) -> &mut bool { + &mut self.0 + } +} + + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct OuterComposite { + #[serde(rename = "my_number")] + #[serde(skip_serializing_if="Option::is_none")] + pub my_number: Option, + + #[serde(rename = "my_string")] + #[serde(skip_serializing_if="Option::is_none")] + pub my_string: Option, + + #[serde(rename = "my_boolean")] + #[serde(skip_serializing_if="Option::is_none")] + pub my_boolean: Option, + +} + +impl OuterComposite { + pub fn new() -> OuterComposite { + OuterComposite { + my_number: None, + my_string: None, + my_boolean: None, + } + } +} + +/// Enumeration of values. +/// Since this enum's variants do not hold data, we can easily define them them as `#[repr(C)]` +/// which helps with FFI. +#[allow(non_camel_case_types)] +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize, Deserialize)] +pub enum OuterEnum { + #[serde(rename = "placed")] + PLACED, + #[serde(rename = "approved")] + APPROVED, + #[serde(rename = "delivered")] + DELIVERED, +} + +impl ::std::fmt::Display for OuterEnum { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + match *self { + OuterEnum::PLACED => write!(f, "{}", "placed"), + OuterEnum::APPROVED => write!(f, "{}", "approved"), + OuterEnum::DELIVERED => write!(f, "{}", "delivered"), + } + } +} + +impl ::std::str::FromStr for OuterEnum { + type Err = (); + fn from_str(s: &str) -> Result { + match s { + "placed" => Ok(OuterEnum::PLACED), + "approved" => Ok(OuterEnum::APPROVED), + "delivered" => Ok(OuterEnum::DELIVERED), + _ => Err(()), + } + } +} + +#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] + +pub struct OuterNumber(f64); + +impl ::std::convert::From for OuterNumber { + fn from(x: f64) -> Self { + OuterNumber(x) + } +} + +impl ::std::convert::From for f64 { + fn from(x: OuterNumber) -> Self { + x.0 + } +} + +impl ::std::ops::Deref for OuterNumber { + type Target = f64; + fn deref(&self) -> &f64 { + &self.0 + } +} + +impl ::std::ops::DerefMut for OuterNumber { + fn deref_mut(&mut self) -> &mut f64 { + &mut self.0 + } +} + + +#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] + +pub struct OuterString(String); + +impl ::std::convert::From for OuterString { + fn from(x: String) -> Self { + OuterString(x) + } +} + +impl ::std::convert::From for String { + fn from(x: OuterString) -> Self { + x.0 + } +} + +impl ::std::ops::Deref for OuterString { + type Target = String; + fn deref(&self) -> &String { + &self.0 + } +} + +impl ::std::ops::DerefMut for OuterString { + fn deref_mut(&mut self) -> &mut String { + &mut self.0 + } +} + + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename = "Pet")] +pub struct Pet { + #[serde(rename = "id")] + #[serde(skip_serializing_if="Option::is_none")] + pub id: Option, + + #[serde(rename = "category")] + #[serde(skip_serializing_if="Option::is_none")] + pub category: Option, + + #[serde(rename = "name")] + pub name: String, + + #[serde(rename = "photoUrls")] + pub photo_urls: Vec, + + #[serde(rename = "tags")] + #[serde(skip_serializing_if="Option::is_none")] + pub tags: Option>, + + /// pet status in the store + // Note: inline enums are not fully supported by swagger-codegen + #[serde(rename = "status")] + #[serde(skip_serializing_if="Option::is_none")] + pub status: Option, + +} + +impl Pet { + pub fn new(name: String, photo_urls: Vec, ) -> Pet { + Pet { + id: None, + category: None, + name: name, + photo_urls: photo_urls, + tags: None, + status: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ReadOnlyFirst { + #[serde(rename = "bar")] + #[serde(skip_serializing_if="Option::is_none")] + pub bar: Option, + + #[serde(rename = "baz")] + #[serde(skip_serializing_if="Option::is_none")] + pub baz: Option, + +} + +impl ReadOnlyFirst { + pub fn new() -> ReadOnlyFirst { + ReadOnlyFirst { + bar: None, + baz: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename = "$special[model.name]")] +pub struct SpecialModelName { + #[serde(rename = "$special[property.name]")] + #[serde(skip_serializing_if="Option::is_none")] + pub special_property_name: Option, + +} + +impl SpecialModelName { + pub fn new() -> SpecialModelName { + SpecialModelName { + special_property_name: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename = "Tag")] +pub struct Tag { + #[serde(rename = "id")] + #[serde(skip_serializing_if="Option::is_none")] + pub id: Option, + + #[serde(rename = "name")] + #[serde(skip_serializing_if="Option::is_none")] + pub name: Option, + +} + +impl Tag { + pub fn new() -> Tag { + Tag { + id: None, + name: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename = "User")] +pub struct User { + #[serde(rename = "id")] + #[serde(skip_serializing_if="Option::is_none")] + pub id: Option, + + #[serde(rename = "username")] + #[serde(skip_serializing_if="Option::is_none")] + pub username: Option, + + #[serde(rename = "firstName")] + #[serde(skip_serializing_if="Option::is_none")] + pub first_name: Option, + + #[serde(rename = "lastName")] + #[serde(skip_serializing_if="Option::is_none")] + pub last_name: Option, + + #[serde(rename = "email")] + #[serde(skip_serializing_if="Option::is_none")] + pub email: Option, + + #[serde(rename = "password")] + #[serde(skip_serializing_if="Option::is_none")] + pub password: Option, + + #[serde(rename = "phone")] + #[serde(skip_serializing_if="Option::is_none")] + pub phone: Option, + + /// User Status + #[serde(rename = "userStatus")] + #[serde(skip_serializing_if="Option::is_none")] + pub user_status: Option, + +} + +impl User { + pub fn new() -> User { + User { + id: None, + username: None, + first_name: None, + last_name: None, + email: None, + password: None, + phone: None, + user_status: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Cat { + #[serde(rename = "className")] + pub class_name: String, + + #[serde(rename = "color")] + #[serde(skip_serializing_if="Option::is_none")] + pub color: Option, + + #[serde(rename = "declawed")] + #[serde(skip_serializing_if="Option::is_none")] + pub declawed: Option, + +} + +impl Cat { + pub fn new(class_name: String, ) -> Cat { + Cat { + class_name: class_name, + color: Some("red".to_string()), + declawed: None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Dog { + #[serde(rename = "className")] + pub class_name: String, + + #[serde(rename = "color")] + #[serde(skip_serializing_if="Option::is_none")] + pub color: Option, + + #[serde(rename = "breed")] + #[serde(skip_serializing_if="Option::is_none")] + pub breed: Option, + +} + +impl Dog { + pub fn new(class_name: String, ) -> Dog { + Dog { + class_name: class_name, + color: Some("red".to_string()), + breed: None, + } + } +} diff --git a/samples/server/petstore/rust-server/src/server.rs b/samples/server/petstore/rust-server/src/server.rs new file mode 100644 index 00000000000..db24dfa2263 --- /dev/null +++ b/samples/server/petstore/rust-server/src/server.rs @@ -0,0 +1,2465 @@ +#![allow(unused_extern_crates)] +extern crate serde_ignored; +extern crate iron; +extern crate router; +extern crate bodyparser; +extern crate urlencoded; +extern crate uuid; +extern crate chrono; +extern crate multipart; + +use futures::Future; +use futures::future; +use futures::{stream, Stream}; +use hyper; +use hyper::header::{Headers, ContentType}; +use self::iron::prelude::*; +use self::iron::{status, modifiers, BeforeMiddleware}; +use self::iron::url::percent_encoding::percent_decode; +use self::router::Router; +use self::urlencoded::UrlEncodedQuery; +use mimetypes; +use multipart::server::{Multipart, SaveResult}; + +use serde_json; +use serde_xml_rs; + +#[allow(unused_imports)] +use std::collections::{HashMap, BTreeMap}; +#[allow(unused_imports)] +use swagger; +use std::io::Error; + +#[allow(unused_imports)] +use std::collections::BTreeSet; + +use swagger::auth::{Authorization, AuthData, Scopes}; +use swagger::{ApiError, Context, XSpanId}; + +use {Api, + TestSpecialTagsResponse, + FakeOuterBooleanSerializeResponse, + FakeOuterCompositeSerializeResponse, + FakeOuterNumberSerializeResponse, + FakeOuterStringSerializeResponse, + TestClientModelResponse, + TestEndpointParametersResponse, + TestEnumParametersResponse, + TestInlineAdditionalPropertiesResponse, + TestJsonFormDataResponse, + TestClassnameResponse, + AddPetResponse, + DeletePetResponse, + FindPetsByStatusResponse, + FindPetsByTagsResponse, + GetPetByIdResponse, + UpdatePetResponse, + UpdatePetWithFormResponse, + UploadFileResponse, + DeleteOrderResponse, + GetInventoryResponse, + GetOrderByIdResponse, + PlaceOrderResponse, + CreateUserResponse, + CreateUsersWithArrayInputResponse, + CreateUsersWithListInputResponse, + DeleteUserResponse, + GetUserByNameResponse, + LoginUserResponse, + LogoutUserResponse, + UpdateUserResponse + }; +#[allow(unused_imports)] +use models; + +header! { (Warning, "Warning") => [String] } + +/// Create a new router for `Api` +pub fn router(api: T) -> Router where T: Api + Send + Sync + Clone + 'static { + let mut router = Router::new(); + add_routes(&mut router, api); + router +} + +/// Add routes for `Api` to a provided router. +/// +/// Note that these routes are added straight onto the router. This means that if the router +/// already has a route for an endpoint which clashes with those provided by this API, then the +/// old route will be lost. +/// +/// It is generally a bad idea to add routes in this way to an existing router, which may have +/// routes on it for other APIs. Distinct APIs should be behind distinct paths to encourage +/// separation of interfaces, which this function does not enforce. APIs should not overlap. +/// +/// Alternative approaches include: +/// +/// - generate an `iron::middleware::Handler` (usually a `router::Router` or +/// `iron::middleware::chain`) for each interface, and add those handlers inside an existing +/// router, mounted at different paths - so the interfaces are separated by path +/// - use a different instance of `iron::Iron` for each interface - so the interfaces are +/// separated by the address/port they listen on +/// +/// This function exists to allow legacy code, which doesn't separate its APIs properly, to make +/// use of this crate. +#[deprecated(note="APIs should not overlap - only for use in legacy code.")] +pub fn route(router: &mut Router, api: T) where T: Api + Send + Sync + Clone + 'static { + add_routes(router, api) +} + +/// Add routes for `Api` to a provided router +fn add_routes(router: &mut Router, api: T) where T: Api + Send + Sync + Clone + 'static { + + let api_clone = api.clone(); + router.patch( + "/v2/another-fake/dummy", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + + let param_body_raw = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; + let mut unused_elements = Vec::new(); + + let param_body = if let Some(param_body_raw) = param_body_raw { + let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); + + let param_body: Option = serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; + + param_body + } else { + None + }; + let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; + + + match api.test_special_tags(param_body, context).wait() { + Ok(rsp) => match rsp { + TestSpecialTagsResponse::SuccessfulOperation(body) => { + + let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + let mut response = Response::with((status::Status::from_u16(200), body_string)); + response.headers.set(ContentType(mimetypes::responses::TEST_SPECIAL_TAGS_SUCCESSFUL_OPERATION.clone())); + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "TestSpecialTags"); + + let api_clone = api.clone(); + router.post( + "/v2/fake/outer/boolean", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + + let param_body_raw = req.get::().unwrap_or(None); + let mut unused_elements = Vec::new(); + + let param_body = if let Some(param_body_raw) = param_body_raw { + let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); + + let param_body: Option = serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }).unwrap_or(None); + + param_body + } else { + None + };; + + + match api.fake_outer_boolean_serialize(param_body, context).wait() { + Ok(rsp) => match rsp { + FakeOuterBooleanSerializeResponse::OutputBoolean(body) => { + + let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + let mut response = Response::with((status::Status::from_u16(200), body_string)); + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "FakeOuterBooleanSerialize"); + + let api_clone = api.clone(); + router.post( + "/v2/fake/outer/composite", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + + let param_body_raw = req.get::().unwrap_or(None); + let mut unused_elements = Vec::new(); + + let param_body = if let Some(param_body_raw) = param_body_raw { + let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); + + let param_body: Option = serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }).unwrap_or(None); + + param_body + } else { + None + };; + + + match api.fake_outer_composite_serialize(param_body, context).wait() { + Ok(rsp) => match rsp { + FakeOuterCompositeSerializeResponse::OutputComposite(body) => { + + let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + let mut response = Response::with((status::Status::from_u16(200), body_string)); + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "FakeOuterCompositeSerialize"); + + let api_clone = api.clone(); + router.post( + "/v2/fake/outer/number", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + + let param_body_raw = req.get::().unwrap_or(None); + let mut unused_elements = Vec::new(); + + let param_body = if let Some(param_body_raw) = param_body_raw { + let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); + + let param_body: Option = serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }).unwrap_or(None); + + param_body + } else { + None + };; + + + match api.fake_outer_number_serialize(param_body, context).wait() { + Ok(rsp) => match rsp { + FakeOuterNumberSerializeResponse::OutputNumber(body) => { + + let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + let mut response = Response::with((status::Status::from_u16(200), body_string)); + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "FakeOuterNumberSerialize"); + + let api_clone = api.clone(); + router.post( + "/v2/fake/outer/string", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + + let param_body_raw = req.get::().unwrap_or(None); + let mut unused_elements = Vec::new(); + + let param_body = if let Some(param_body_raw) = param_body_raw { + let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); + + let param_body: Option = serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }).unwrap_or(None); + + param_body + } else { + None + };; + + + match api.fake_outer_string_serialize(param_body, context).wait() { + Ok(rsp) => match rsp { + FakeOuterStringSerializeResponse::OutputString(body) => { + + let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + let mut response = Response::with((status::Status::from_u16(200), body_string)); + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "FakeOuterStringSerialize"); + + let api_clone = api.clone(); + router.patch( + "/v2/fake", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + + let param_body_raw = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; + let mut unused_elements = Vec::new(); + + let param_body = if let Some(param_body_raw) = param_body_raw { + let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); + + let param_body: Option = serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; + + param_body + } else { + None + }; + let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; + + + match api.test_client_model(param_body, context).wait() { + Ok(rsp) => match rsp { + TestClientModelResponse::SuccessfulOperation(body) => { + + let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + let mut response = Response::with((status::Status::from_u16(200), body_string)); + response.headers.set(ContentType(mimetypes::responses::TEST_CLIENT_MODEL_SUCCESSFUL_OPERATION.clone())); + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "TestClientModel"); + + let api_clone = api.clone(); + router.post( + "/v2/fake", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + let authorization = context.authorization.as_ref().ok_or_else(|| { + Response::with(( + status::Forbidden, + "Unauthenticated".to_string() + )) + })?; + + + + + // Form parameters + let param_number = 3.4; + let param_double = 1.2; + let param_pattern_without_delimiter = "pattern_without_delimiter_example".to_string(); + let param_byte = swagger::ByteArray("byte_example".to_string().into_bytes()); + let param_integer = Some(56); + let param_int32 = Some(56); + let param_int64 = Some(789); + let param_float = Some(3.4); + let param_string = Some("string_example".to_string()); + let param_binary = Some(swagger::ByteArray(Vec::from("B"))); + let param_date = None; + let param_date_time = None; + let param_password = Some("password_example".to_string()); + let param_callback = Some("callback_example".to_string()); + + match api.test_endpoint_parameters(param_number, param_double, param_pattern_without_delimiter, param_byte, param_integer, param_int32, param_int64, param_float, param_string, param_binary, param_date, param_date_time, param_password, param_callback, context).wait() { + Ok(rsp) => match rsp { + TestEndpointParametersResponse::InvalidUsernameSupplied => { + + + let mut response = Response::with((status::Status::from_u16(400))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + TestEndpointParametersResponse::UserNotFound => { + + + let mut response = Response::with((status::Status::from_u16(404))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "TestEndpointParameters"); + + let api_clone = api.clone(); + router.get( + "/v2/fake", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + // Header parameters + header! { (RequestEnumHeaderStringArray, "enum_header_string_array") => (String)* } + let param_enum_header_string_array = req.headers.get::().map(|header| header.0.clone()); + header! { (RequestEnumHeaderString, "enum_header_string") => [String] } + let param_enum_header_string = req.headers.get::().map(|header| header.0.clone()); + + + // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) + let query_params = req.get::().unwrap_or_default(); + let param_enum_query_string_array = query_params.get("enum_query_string_array") + .map(|list| list.iter().flat_map(|x| x.parse::()).collect::>()); + let param_enum_query_string = query_params.get("enum_query_string") + .and_then(|list| list.first()).and_then(|x| x.parse::().ok()); + let param_enum_query_integer = query_params.get("enum_query_integer") + .and_then(|list| list.first()).and_then(|x| x.parse::().ok()); + + // Form parameters + let param_enum_form_string_array = None; + let param_enum_form_string = Some("enum_form_string_example".to_string()); + let param_enum_query_double = Some(1.2); + + match api.test_enum_parameters(param_enum_form_string_array.as_ref(), param_enum_form_string, param_enum_header_string_array.as_ref(), param_enum_header_string, param_enum_query_string_array.as_ref(), param_enum_query_string, param_enum_query_integer, param_enum_query_double, context).wait() { + Ok(rsp) => match rsp { + TestEnumParametersResponse::InvalidRequest => { + + + let mut response = Response::with((status::Status::from_u16(400))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + TestEnumParametersResponse::NotFound => { + + + let mut response = Response::with((status::Status::from_u16(404))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "TestEnumParameters"); + + let api_clone = api.clone(); + router.post( + "/v2/fake/inline-additionalProperties", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + + let param_param_raw = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter param - not valid UTF-8: {}", e))))?; + let mut unused_elements = Vec::new(); + + let param_param = if let Some(param_param_raw) = param_param_raw { + let deserializer = &mut serde_json::Deserializer::from_str(¶m_param_raw); + + let param_param: Option = serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter param - doesn't match schema: {}", e))))?; + + param_param + } else { + None + }; + let param_param = param_param.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter param".to_string())))?; + + + match api.test_inline_additional_properties(param_param, context).wait() { + Ok(rsp) => match rsp { + TestInlineAdditionalPropertiesResponse::SuccessfulOperation => { + + + let mut response = Response::with((status::Status::from_u16(200))); + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "TestInlineAdditionalProperties"); + + let api_clone = api.clone(); + router.get( + "/v2/fake/jsonFormData", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + + // Form parameters + let param_param = "param_example".to_string(); + let param_param2 = "param2_example".to_string(); + + match api.test_json_form_data(param_param, param_param2, context).wait() { + Ok(rsp) => match rsp { + TestJsonFormDataResponse::SuccessfulOperation => { + + + let mut response = Response::with((status::Status::from_u16(200))); + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "TestJsonFormData"); + + let api_clone = api.clone(); + router.patch( + "/v2/fake_classname_test", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + let authorization = context.authorization.as_ref().ok_or_else(|| { + Response::with(( + status::Forbidden, + "Unauthenticated".to_string() + )) + })?; + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + + let param_body_raw = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; + let mut unused_elements = Vec::new(); + + let param_body = if let Some(param_body_raw) = param_body_raw { + let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); + + let param_body: Option = serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; + + param_body + } else { + None + }; + let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; + + + match api.test_classname(param_body, context).wait() { + Ok(rsp) => match rsp { + TestClassnameResponse::SuccessfulOperation(body) => { + + let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + let mut response = Response::with((status::Status::from_u16(200), body_string)); + response.headers.set(ContentType(mimetypes::responses::TEST_CLASSNAME_SUCCESSFUL_OPERATION.clone())); + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "TestClassname"); + + let api_clone = api.clone(); + router.post( + "/v2/pet", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + let authorization = context.authorization.as_ref().ok_or_else(|| { + Response::with(( + status::Forbidden, + "Unauthenticated".to_string() + )) + })?; + + // Authorization + if let Scopes::Some(ref scopes) = authorization.scopes { + let required_scopes: BTreeSet = vec![ + "write:pets".to_string(), // modify pets in your account + "read:pets".to_string(), // read your pets + ].into_iter().collect(); + + if !required_scopes.is_subset(scopes) { + let missing_scopes = required_scopes.difference(scopes); + return Err(Response::with(( + status::Forbidden, + missing_scopes.fold( + "Insufficient authorization, missing scopes".to_string(), + |s, scope| format!("{} {}", s, scope) + ) + ))); + } + } + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + + let param_body_raw = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; + let mut unused_elements = Vec::new(); + + let param_body = if let Some(param_body_raw) = param_body_raw { + let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(param_body_raw.as_bytes()); + + let param_body: Option = serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; + + param_body + } else { + None + }; + let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; + + + match api.add_pet(param_body, context).wait() { + Ok(rsp) => match rsp { + AddPetResponse::InvalidInput => { + + + let mut response = Response::with((status::Status::from_u16(405))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "AddPet"); + + let api_clone = api.clone(); + router.delete( + "/v2/pet/:petId", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + let authorization = context.authorization.as_ref().ok_or_else(|| { + Response::with(( + status::Forbidden, + "Unauthenticated".to_string() + )) + })?; + + // Authorization + if let Scopes::Some(ref scopes) = authorization.scopes { + let required_scopes: BTreeSet = vec![ + "write:pets".to_string(), // modify pets in your account + "read:pets".to_string(), // read your pets + ].into_iter().collect(); + + if !required_scopes.is_subset(scopes) { + let missing_scopes = required_scopes.difference(scopes); + return Err(Response::with(( + status::Forbidden, + missing_scopes.fold( + "Insufficient authorization, missing scopes".to_string(), + |s, scope| format!("{} {}", s, scope) + ) + ))); + } + } + + + // Path parameters + let param_pet_id = { + let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? + .find("petId").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter petId".to_string())))?; + percent_decode(param.as_bytes()).decode_utf8() + .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? + .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter petId: {}", e))))? + }; + + // Header parameters + header! { (RequestApiKey, "api_key") => [String] } + let param_api_key = req.headers.get::().map(|header| header.0.clone()); + + + + match api.delete_pet(param_pet_id, param_api_key, context).wait() { + Ok(rsp) => match rsp { + DeletePetResponse::InvalidPetValue => { + + + let mut response = Response::with((status::Status::from_u16(400))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "DeletePet"); + + let api_clone = api.clone(); + router.get( + "/v2/pet/findByStatus", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + let authorization = context.authorization.as_ref().ok_or_else(|| { + Response::with(( + status::Forbidden, + "Unauthenticated".to_string() + )) + })?; + + // Authorization + if let Scopes::Some(ref scopes) = authorization.scopes { + let required_scopes: BTreeSet = vec![ + "write:pets".to_string(), // modify pets in your account + "read:pets".to_string(), // read your pets + ].into_iter().collect(); + + if !required_scopes.is_subset(scopes) { + let missing_scopes = required_scopes.difference(scopes); + return Err(Response::with(( + status::Forbidden, + missing_scopes.fold( + "Insufficient authorization, missing scopes".to_string(), + |s, scope| format!("{} {}", s, scope) + ) + ))); + } + } + + + + // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) + let query_params = req.get::().unwrap_or_default(); + let param_status = query_params.get("status") + .ok_or_else(|| Response::with((status::BadRequest, "Missing required query parameter status".to_string())))? + .iter().flat_map(|x| x.parse::()).collect::>(); + + + match api.find_pets_by_status(param_status.as_ref(), context).wait() { + Ok(rsp) => match rsp { + FindPetsByStatusResponse::SuccessfulOperation(body) => { + + let body_string = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + + let mut response = Response::with((status::Status::from_u16(200), body_string)); + response.headers.set(ContentType(mimetypes::responses::FIND_PETS_BY_STATUS_SUCCESSFUL_OPERATION.clone())); + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + FindPetsByStatusResponse::InvalidStatusValue => { + + + let mut response = Response::with((status::Status::from_u16(400))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "FindPetsByStatus"); + + let api_clone = api.clone(); + router.get( + "/v2/pet/findByTags", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + let authorization = context.authorization.as_ref().ok_or_else(|| { + Response::with(( + status::Forbidden, + "Unauthenticated".to_string() + )) + })?; + + // Authorization + if let Scopes::Some(ref scopes) = authorization.scopes { + let required_scopes: BTreeSet = vec![ + "write:pets".to_string(), // modify pets in your account + "read:pets".to_string(), // read your pets + ].into_iter().collect(); + + if !required_scopes.is_subset(scopes) { + let missing_scopes = required_scopes.difference(scopes); + return Err(Response::with(( + status::Forbidden, + missing_scopes.fold( + "Insufficient authorization, missing scopes".to_string(), + |s, scope| format!("{} {}", s, scope) + ) + ))); + } + } + + + + // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) + let query_params = req.get::().unwrap_or_default(); + let param_tags = query_params.get("tags") + .ok_or_else(|| Response::with((status::BadRequest, "Missing required query parameter tags".to_string())))? + .iter().flat_map(|x| x.parse::()).collect::>(); + + + match api.find_pets_by_tags(param_tags.as_ref(), context).wait() { + Ok(rsp) => match rsp { + FindPetsByTagsResponse::SuccessfulOperation(body) => { + + let body_string = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + + let mut response = Response::with((status::Status::from_u16(200), body_string)); + response.headers.set(ContentType(mimetypes::responses::FIND_PETS_BY_TAGS_SUCCESSFUL_OPERATION.clone())); + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + FindPetsByTagsResponse::InvalidTagValue => { + + + let mut response = Response::with((status::Status::from_u16(400))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "FindPetsByTags"); + + let api_clone = api.clone(); + router.get( + "/v2/pet/:petId", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + let authorization = context.authorization.as_ref().ok_or_else(|| { + Response::with(( + status::Forbidden, + "Unauthenticated".to_string() + )) + })?; + + + + // Path parameters + let param_pet_id = { + let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? + .find("petId").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter petId".to_string())))?; + percent_decode(param.as_bytes()).decode_utf8() + .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? + .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter petId: {}", e))))? + }; + + + + match api.get_pet_by_id(param_pet_id, context).wait() { + Ok(rsp) => match rsp { + GetPetByIdResponse::SuccessfulOperation(body) => { + + let body_string = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + + let mut response = Response::with((status::Status::from_u16(200), body_string)); + response.headers.set(ContentType(mimetypes::responses::GET_PET_BY_ID_SUCCESSFUL_OPERATION.clone())); + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + GetPetByIdResponse::InvalidIDSupplied => { + + + let mut response = Response::with((status::Status::from_u16(400))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + GetPetByIdResponse::PetNotFound => { + + + let mut response = Response::with((status::Status::from_u16(404))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "GetPetById"); + + let api_clone = api.clone(); + router.put( + "/v2/pet", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + let authorization = context.authorization.as_ref().ok_or_else(|| { + Response::with(( + status::Forbidden, + "Unauthenticated".to_string() + )) + })?; + + // Authorization + if let Scopes::Some(ref scopes) = authorization.scopes { + let required_scopes: BTreeSet = vec![ + "write:pets".to_string(), // modify pets in your account + "read:pets".to_string(), // read your pets + ].into_iter().collect(); + + if !required_scopes.is_subset(scopes) { + let missing_scopes = required_scopes.difference(scopes); + return Err(Response::with(( + status::Forbidden, + missing_scopes.fold( + "Insufficient authorization, missing scopes".to_string(), + |s, scope| format!("{} {}", s, scope) + ) + ))); + } + } + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + + let param_body_raw = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; + let mut unused_elements = Vec::new(); + + let param_body = if let Some(param_body_raw) = param_body_raw { + let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(param_body_raw.as_bytes()); + + let param_body: Option = serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; + + param_body + } else { + None + }; + let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; + + + match api.update_pet(param_body, context).wait() { + Ok(rsp) => match rsp { + UpdatePetResponse::InvalidIDSupplied => { + + + let mut response = Response::with((status::Status::from_u16(400))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + UpdatePetResponse::PetNotFound => { + + + let mut response = Response::with((status::Status::from_u16(404))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + UpdatePetResponse::ValidationException => { + + + let mut response = Response::with((status::Status::from_u16(405))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "UpdatePet"); + + let api_clone = api.clone(); + router.post( + "/v2/pet/:petId", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + let authorization = context.authorization.as_ref().ok_or_else(|| { + Response::with(( + status::Forbidden, + "Unauthenticated".to_string() + )) + })?; + + // Authorization + if let Scopes::Some(ref scopes) = authorization.scopes { + let required_scopes: BTreeSet = vec![ + "write:pets".to_string(), // modify pets in your account + "read:pets".to_string(), // read your pets + ].into_iter().collect(); + + if !required_scopes.is_subset(scopes) { + let missing_scopes = required_scopes.difference(scopes); + return Err(Response::with(( + status::Forbidden, + missing_scopes.fold( + "Insufficient authorization, missing scopes".to_string(), + |s, scope| format!("{} {}", s, scope) + ) + ))); + } + } + + + // Path parameters + let param_pet_id = { + let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? + .find("petId").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter petId".to_string())))?; + percent_decode(param.as_bytes()).decode_utf8() + .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? + .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter petId: {}", e))))? + }; + + + // Form parameters + let param_name = Some("name_example".to_string()); + let param_status = Some("status_example".to_string()); + + match api.update_pet_with_form(param_pet_id, param_name, param_status, context).wait() { + Ok(rsp) => match rsp { + UpdatePetWithFormResponse::InvalidInput => { + + + let mut response = Response::with((status::Status::from_u16(405))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "UpdatePetWithForm"); + + let api_clone = api.clone(); + router.post( + "/v2/pet/:petId/uploadImage", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + let authorization = context.authorization.as_ref().ok_or_else(|| { + Response::with(( + status::Forbidden, + "Unauthenticated".to_string() + )) + })?; + + // Authorization + if let Scopes::Some(ref scopes) = authorization.scopes { + let required_scopes: BTreeSet = vec![ + "write:pets".to_string(), // modify pets in your account + "read:pets".to_string(), // read your pets + ].into_iter().collect(); + + if !required_scopes.is_subset(scopes) { + let missing_scopes = required_scopes.difference(scopes); + return Err(Response::with(( + status::Forbidden, + missing_scopes.fold( + "Insufficient authorization, missing scopes".to_string(), + |s, scope| format!("{} {}", s, scope) + ) + ))); + } + } + + + // Path parameters + let param_pet_id = { + let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? + .find("petId").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter petId".to_string())))?; + percent_decode(param.as_bytes()).decode_utf8() + .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? + .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter petId: {}", e))))? + }; + + + // Form parameters + + // Expecting a multipart form, extract and parse it now. + let mut entries = match Multipart::from_request(req) { + Ok(mut multipart) => { + + match multipart.save().temp() { + SaveResult::Full(entries) => { + Ok(entries) + }, + _ => { + Err(Response::with((status::InternalServerError, format!("Unable to process all message parts")))) + }, + } + }, + Err(e) => { + // Unable to parse as multipart + Err(Response::with((status::BadRequest, format!("Couldn't parse body as multipart")))) + } + }?; + + let param_additional_metadata = Some("additional_metadata_example".to_string()); + + + let param_file = entries.fields.remove("file"); + + let param_file = match param_file { + Some(body) => { + Ok({let bytes = body.as_bytes(); + Some( + Box::new(stream::once(Ok(bytes.to_vec()))) as Box, Error=Error> + Send> + )} + ) + } + None => {Err(Response::with((status::BadRequest, format!("Body part not found!"))))} + }?; + let param_file = Box::new(future::ok(param_file)); + + match api.upload_file(param_pet_id, param_additional_metadata, param_file, context).wait() { + Ok(rsp) => match rsp { + UploadFileResponse::SuccessfulOperation(body) => { + + let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + let mut response = Response::with((status::Status::from_u16(200), body_string)); + response.headers.set(ContentType(mimetypes::responses::UPLOAD_FILE_SUCCESSFUL_OPERATION.clone())); + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "UploadFile"); + + let api_clone = api.clone(); + router.delete( + "/v2/store/order/:order_id", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + // Path parameters + let param_order_id = { + let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? + .find("order_id").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter order_id".to_string())))?; + percent_decode(param.as_bytes()).decode_utf8() + .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? + .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter order_id: {}", e))))? + }; + + + + match api.delete_order(param_order_id, context).wait() { + Ok(rsp) => match rsp { + DeleteOrderResponse::InvalidIDSupplied => { + + + let mut response = Response::with((status::Status::from_u16(400))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + DeleteOrderResponse::OrderNotFound => { + + + let mut response = Response::with((status::Status::from_u16(404))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "DeleteOrder"); + + let api_clone = api.clone(); + router.get( + "/v2/store/inventory", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + let authorization = context.authorization.as_ref().ok_or_else(|| { + Response::with(( + status::Forbidden, + "Unauthenticated".to_string() + )) + })?; + + + + + + match api.get_inventory(context).wait() { + Ok(rsp) => match rsp { + GetInventoryResponse::SuccessfulOperation(body) => { + + let body_string = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + let mut response = Response::with((status::Status::from_u16(200), body_string)); + response.headers.set(ContentType(mimetypes::responses::GET_INVENTORY_SUCCESSFUL_OPERATION.clone())); + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "GetInventory"); + + let api_clone = api.clone(); + router.get( + "/v2/store/order/:order_id", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + // Path parameters + let param_order_id = { + let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? + .find("order_id").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter order_id".to_string())))?; + percent_decode(param.as_bytes()).decode_utf8() + .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? + .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter order_id: {}", e))))? + }; + + + + match api.get_order_by_id(param_order_id, context).wait() { + Ok(rsp) => match rsp { + GetOrderByIdResponse::SuccessfulOperation(body) => { + + let body_string = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + + let mut response = Response::with((status::Status::from_u16(200), body_string)); + response.headers.set(ContentType(mimetypes::responses::GET_ORDER_BY_ID_SUCCESSFUL_OPERATION.clone())); + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + GetOrderByIdResponse::InvalidIDSupplied => { + + + let mut response = Response::with((status::Status::from_u16(400))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + GetOrderByIdResponse::OrderNotFound => { + + + let mut response = Response::with((status::Status::from_u16(404))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "GetOrderById"); + + let api_clone = api.clone(); + router.post( + "/v2/store/order", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + + let param_body_raw = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; + let mut unused_elements = Vec::new(); + + let param_body = if let Some(param_body_raw) = param_body_raw { + let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); + + let param_body: Option = serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; + + param_body + } else { + None + }; + let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; + + + match api.place_order(param_body, context).wait() { + Ok(rsp) => match rsp { + PlaceOrderResponse::SuccessfulOperation(body) => { + + let body_string = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + + let mut response = Response::with((status::Status::from_u16(200), body_string)); + response.headers.set(ContentType(mimetypes::responses::PLACE_ORDER_SUCCESSFUL_OPERATION.clone())); + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + PlaceOrderResponse::InvalidOrder => { + + + let mut response = Response::with((status::Status::from_u16(400))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "PlaceOrder"); + + let api_clone = api.clone(); + router.post( + "/v2/user", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + + let param_body_raw = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; + let mut unused_elements = Vec::new(); + + let param_body = if let Some(param_body_raw) = param_body_raw { + let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); + + let param_body: Option = serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; + + param_body + } else { + None + }; + let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; + + + match api.create_user(param_body, context).wait() { + Ok(rsp) => match rsp { + CreateUserResponse::SuccessfulOperation => { + + + let mut response = Response::with((status::Status::from_u16(0))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "CreateUser"); + + let api_clone = api.clone(); + router.post( + "/v2/user/createWithArray", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + + let param_body_raw = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; + let mut unused_elements = Vec::new(); + + let param_body = if let Some(param_body_raw) = param_body_raw { + let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); + + let param_body: Option> = serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; + + param_body + } else { + None + }; + let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; + + + match api.create_users_with_array_input(param_body.as_ref(), context).wait() { + Ok(rsp) => match rsp { + CreateUsersWithArrayInputResponse::SuccessfulOperation => { + + + let mut response = Response::with((status::Status::from_u16(0))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "CreateUsersWithArrayInput"); + + let api_clone = api.clone(); + router.post( + "/v2/user/createWithList", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + + let param_body_raw = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; + let mut unused_elements = Vec::new(); + + let param_body = if let Some(param_body_raw) = param_body_raw { + let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); + + let param_body: Option> = serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; + + param_body + } else { + None + }; + let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; + + + match api.create_users_with_list_input(param_body.as_ref(), context).wait() { + Ok(rsp) => match rsp { + CreateUsersWithListInputResponse::SuccessfulOperation => { + + + let mut response = Response::with((status::Status::from_u16(0))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "CreateUsersWithListInput"); + + let api_clone = api.clone(); + router.delete( + "/v2/user/:username", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + // Path parameters + let param_username = { + let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? + .find("username").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter username".to_string())))?; + percent_decode(param.as_bytes()).decode_utf8() + .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? + .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter username: {}", e))))? + }; + + + + match api.delete_user(param_username, context).wait() { + Ok(rsp) => match rsp { + DeleteUserResponse::InvalidUsernameSupplied => { + + + let mut response = Response::with((status::Status::from_u16(400))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + DeleteUserResponse::UserNotFound => { + + + let mut response = Response::with((status::Status::from_u16(404))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "DeleteUser"); + + let api_clone = api.clone(); + router.get( + "/v2/user/:username", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + // Path parameters + let param_username = { + let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? + .find("username").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter username".to_string())))?; + percent_decode(param.as_bytes()).decode_utf8() + .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? + .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter username: {}", e))))? + }; + + + + match api.get_user_by_name(param_username, context).wait() { + Ok(rsp) => match rsp { + GetUserByNameResponse::SuccessfulOperation(body) => { + + let body_string = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + + let mut response = Response::with((status::Status::from_u16(200), body_string)); + response.headers.set(ContentType(mimetypes::responses::GET_USER_BY_NAME_SUCCESSFUL_OPERATION.clone())); + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + GetUserByNameResponse::InvalidUsernameSupplied => { + + + let mut response = Response::with((status::Status::from_u16(400))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + GetUserByNameResponse::UserNotFound => { + + + let mut response = Response::with((status::Status::from_u16(404))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "GetUserByName"); + + let api_clone = api.clone(); + router.get( + "/v2/user/login", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + + // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) + let query_params = req.get::().unwrap_or_default(); + let param_username = query_params.get("username") + .ok_or_else(|| Response::with((status::BadRequest, "Missing required query parameter username".to_string())))? + .first().ok_or_else(|| Response::with((status::BadRequest, "Required query parameter username was empty".to_string())))? + .parse::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse query parameter username - doesn't match schema: {}", e))))?; + let param_password = query_params.get("password") + .ok_or_else(|| Response::with((status::BadRequest, "Missing required query parameter password".to_string())))? + .first().ok_or_else(|| Response::with((status::BadRequest, "Required query parameter password was empty".to_string())))? + .parse::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse query parameter password - doesn't match schema: {}", e))))?; + + + match api.login_user(param_username, param_password, context).wait() { + Ok(rsp) => match rsp { + LoginUserResponse::SuccessfulOperation{ body, x_rate_limit, x_expires_after } => { + + let body_string = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + + let mut response = Response::with((status::Status::from_u16(200), body_string)); header! { (ResponseXRateLimit, "X-Rate-Limit") => [i32] } + response.headers.set(ResponseXRateLimit(x_rate_limit)); + header! { (ResponseXExpiresAfter, "X-Expires-After") => [chrono::DateTime] } + response.headers.set(ResponseXExpiresAfter(x_expires_after)); + + response.headers.set(ContentType(mimetypes::responses::LOGIN_USER_SUCCESSFUL_OPERATION.clone())); + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + LoginUserResponse::InvalidUsername => { + + + let mut response = Response::with((status::Status::from_u16(400))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "LoginUser"); + + let api_clone = api.clone(); + router.get( + "/v2/user/logout", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + + + match api.logout_user(context).wait() { + Ok(rsp) => match rsp { + LogoutUserResponse::SuccessfulOperation => { + + + let mut response = Response::with((status::Status::from_u16(0))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "LogoutUser"); + + let api_clone = api.clone(); + router.put( + "/v2/user/:username", + move |req: &mut Request| { + let mut context = Context::default(); + + // Helper function to provide a code block to use `?` in (to be replaced by the `catch` block when it exists). + fn handle_request(req: &mut Request, api: &T, context: &mut Context) -> Result where T: Api { + + context.x_span_id = Some(req.headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); + context.auth_data = req.extensions.remove::(); + context.authorization = req.extensions.remove::(); + + + + // Path parameters + let param_username = { + let param = req.extensions.get::().ok_or_else(|| Response::with((status::InternalServerError, "An internal error occurred".to_string())))? + .find("username").ok_or_else(|| Response::with((status::BadRequest, "Missing path parameter username".to_string())))?; + percent_decode(param.as_bytes()).decode_utf8() + .map_err(|_| Response::with((status::BadRequest, format!("Couldn't percent-decode path parameter as UTF-8: {}", param))))? + .parse().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse path parameter username: {}", e))))? + }; + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + + let param_body_raw = req.get::().map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - not valid UTF-8: {}", e))))?; + let mut unused_elements = Vec::new(); + + let param_body = if let Some(param_body_raw) = param_body_raw { + let deserializer = &mut serde_json::Deserializer::from_str(¶m_body_raw); + + let param_body: Option = serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }).map_err(|e| Response::with((status::BadRequest, format!("Couldn't parse body parameter body - doesn't match schema: {}", e))))?; + + param_body + } else { + None + }; + let param_body = param_body.ok_or_else(|| Response::with((status::BadRequest, "Missing required body parameter body".to_string())))?; + + + match api.update_user(param_username, param_body, context).wait() { + Ok(rsp) => match rsp { + UpdateUserResponse::InvalidUserSupplied => { + + + let mut response = Response::with((status::Status::from_u16(400))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + UpdateUserResponse::UserNotFound => { + + + let mut response = Response::with((status::Status::from_u16(404))); + + + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + if !unused_elements.is_empty() { + response.headers.set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + Ok(response) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + Err(Response::with((status::InternalServerError, "An internal error occurred".to_string()))) + } + } + } + + handle_request(req, &api_clone, &mut context).or_else(|mut response| { + context.x_span_id.as_ref().map(|header| response.headers.set(XSpanId(header.clone()))); + Ok(response) + }) + }, + "UpdateUser"); + +} + +/// Middleware to extract authentication data from request +pub struct ExtractAuthData; + +impl BeforeMiddleware for ExtractAuthData { + fn before(&self, req: &mut Request) -> IronResult<()> { + { + header! { (ApiKey1, "api_key") => [String] } + if let Some(header) = req.headers.get::() { + req.extensions.insert::(AuthData::ApiKey(header.0.clone())); + return Ok(()); + } + } + { + let header = match req.get_ref::() { + Ok(query) => query.get("api_key_query").map(|v| v[0].clone()), + _ => None + }; + if let Some(key) = header { + req.extensions.insert::(AuthData::ApiKey(key)); + return Ok(()); + } + } + { + use hyper::header::{Authorization, Basic, Bearer}; + use std::ops::Deref; + if let Some(basic) = req.headers.get::>() { + req.extensions.insert::(AuthData::Basic(basic.deref().clone())); + return Ok(()); + } + } + { + use hyper::header::{Authorization, Basic, Bearer}; + use std::ops::Deref; + if let Some(bearer) = req.headers.get::>() { + req.extensions.insert::(AuthData::Bearer(bearer.deref().clone())); + return Ok(()); + } + } + + Ok(()) + } +} diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/AnotherFakeApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/AnotherFakeApi.java index 8ad023f68d0..c2e845dce90 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/AnotherFakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/AnotherFakeApi.java @@ -6,10 +6,13 @@ package io.swagger.api; import io.swagger.model.Client; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,17 +21,32 @@ 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.io.IOException; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; +import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; @Api(value = "another-fake", description = "the another-fake API") public interface AnotherFakeApi { + Logger log = LoggerFactory.getLogger(AnotherFakeApi.class); + + default Optional getObjectMapper() { + return Optional.empty(); + } + + default Optional getRequest() { + return Optional.empty(); + } + + default Optional getAcceptHeader() { + return getRequest().map(r -> r.getHeader("Accept")); + } + @ApiOperation(value = "To test special tags", nickname = "testSpecialTags", notes = "To test special tags", response = Client.class, tags={ "$another-fake?", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) @@ -36,9 +54,20 @@ public interface AnotherFakeApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - default CompletableFuture> testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default AnotherFakeApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/AnotherFakeApiController.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/AnotherFakeApiController.java index 82f8a98cfee..c57e8ee5a06 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/AnotherFakeApiController.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/AnotherFakeApiController.java @@ -1,17 +1,31 @@ package io.swagger.api; -import org.springframework.stereotype.Controller; import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; -import javax.validation.constraints.*; -import javax.validation.Valid; +import org.springframework.stereotype.Controller; +import javax.servlet.http.HttpServletRequest; +import java.util.Optional; @Controller public class AnotherFakeApiController implements AnotherFakeApi { + private final ObjectMapper objectMapper; - public AnotherFakeApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public AnotherFakeApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; + } + + @Override + public Optional getObjectMapper() { + return Optional.ofNullable(objectMapper); + } + + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java index 867a58e7730..5c946bfb707 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java @@ -10,10 +10,13 @@ import io.swagger.model.Client; import java.time.LocalDate; import java.time.OffsetDateTime; import io.swagger.model.OuterComposite; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -22,25 +25,51 @@ 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.io.IOException; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; +import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; @Api(value = "fake", description = "the fake API") public interface FakeApi { + Logger log = LoggerFactory.getLogger(FakeApi.class); + + default Optional getObjectMapper() { + return Optional.empty(); + } + + default Optional getRequest() { + return Optional.empty(); + } + + default Optional getAcceptHeader() { + return getRequest().map(r -> r.getHeader("Accept")); + } + @ApiOperation(value = "", nickname = "fakeOuterBooleanSerialize", notes = "Test serialization of outer boolean types", response = Boolean.class, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Output boolean", response = Boolean.class) }) @RequestMapping(value = "/fake/outer/boolean", method = RequestMethod.POST) - default CompletableFuture> fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue("{ }", Boolean.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -49,9 +78,20 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output composite", response = OuterComposite.class) }) @RequestMapping(value = "/fake/outer/composite", method = RequestMethod.POST) - default CompletableFuture> fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue("{ \"my_string\" : { }, \"my_number\" : { }, \"my_boolean\" : { }}", OuterComposite.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -60,9 +100,20 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output number", response = BigDecimal.class) }) @RequestMapping(value = "/fake/outer/number", method = RequestMethod.POST) - default CompletableFuture> fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue("{ }", BigDecimal.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -71,9 +122,20 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output string", response = String.class) }) @RequestMapping(value = "/fake/outer/string", method = RequestMethod.POST) - default CompletableFuture> fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue("{ }", String.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -84,9 +146,20 @@ public interface FakeApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - default CompletableFuture> testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -100,9 +173,12 @@ public interface FakeApi { produces = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, consumes = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, method = RequestMethod.POST) - default CompletableFuture> testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -114,9 +190,27 @@ public interface FakeApi { produces = { "*/*" }, consumes = { "*/*" }, method = RequestMethod.GET) - default CompletableFuture> testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); + } + + + @ApiOperation(value = "test inline additionalProperties", nickname = "testInlineAdditionalProperties", notes = "", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation") }) + @RequestMapping(value = "/fake/inline-additionalProperties", + consumes = { "application/json" }, + method = RequestMethod.POST) + default CompletableFuture> testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Object param) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -126,9 +220,12 @@ public interface FakeApi { @RequestMapping(value = "/fake/jsonFormData", consumes = { "application/json" }, method = RequestMethod.GET) - default CompletableFuture> testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApiController.java index c9bf94efe6a..caf13795605 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApiController.java @@ -1,17 +1,31 @@ package io.swagger.api; -import org.springframework.stereotype.Controller; import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; -import javax.validation.constraints.*; -import javax.validation.Valid; +import org.springframework.stereotype.Controller; +import javax.servlet.http.HttpServletRequest; +import java.util.Optional; @Controller public class FakeApiController implements FakeApi { + private final ObjectMapper objectMapper; - public FakeApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public FakeApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; + } + + @Override + public Optional getObjectMapper() { + return Optional.ofNullable(objectMapper); + } + + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeClassnameTestApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeClassnameTestApi.java index bee88691e39..1382f6a44f9 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeClassnameTestApi.java @@ -6,10 +6,13 @@ package io.swagger.api; import io.swagger.model.Client; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,17 +21,32 @@ 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.io.IOException; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; +import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; @Api(value = "fake_classname_test", description = "the fake_classname_test API") public interface FakeClassnameTestApi { + Logger log = LoggerFactory.getLogger(FakeClassnameTestApi.class); + + default Optional getObjectMapper() { + return Optional.empty(); + } + + default Optional getRequest() { + return Optional.empty(); + } + + default Optional getAcceptHeader() { + return getRequest().map(r -> r.getHeader("Accept")); + } + @ApiOperation(value = "To test class name in snake case", nickname = "testClassname", notes = "", response = Client.class, authorizations = { @Authorization(value = "api_key_query") }, tags={ "fake_classname_tags 123#$%^", }) @@ -38,9 +56,20 @@ public interface FakeClassnameTestApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - default CompletableFuture> testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeClassnameTestApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeClassnameTestApiController.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeClassnameTestApiController.java index 3957401c9b2..692712ad25e 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeClassnameTestApiController.java @@ -1,17 +1,31 @@ package io.swagger.api; -import org.springframework.stereotype.Controller; import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; -import javax.validation.constraints.*; -import javax.validation.Valid; +import org.springframework.stereotype.Controller; +import javax.servlet.http.HttpServletRequest; +import java.util.Optional; @Controller public class FakeClassnameTestApiController implements FakeClassnameTestApi { + private final ObjectMapper objectMapper; - public FakeClassnameTestApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public FakeClassnameTestApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; + } + + @Override + public Optional getObjectMapper() { + return Optional.ofNullable(objectMapper); + } + + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } 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 d322c3004dd..4681a226115 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 @@ -8,10 +8,13 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -20,17 +23,32 @@ 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.io.IOException; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; +import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; @Api(value = "pet", description = "the pet API") public interface PetApi { + Logger log = LoggerFactory.getLogger(PetApi.class); + + default Optional getObjectMapper() { + return Optional.empty(); + } + + default Optional getRequest() { + return Optional.empty(); + } + + default Optional getAcceptHeader() { + return getRequest().map(r -> r.getHeader("Accept")); + } + @ApiOperation(value = "Add a new pet to the store", nickname = "addPet", notes = "", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @@ -43,9 +61,12 @@ public interface PetApi { produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.POST) - default CompletableFuture> addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default PetApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -60,9 +81,12 @@ public interface PetApi { @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - default CompletableFuture> deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default PetApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -78,9 +102,28 @@ public interface PetApi { @RequestMapping(value = "/pet/findByStatus", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default CompletableFuture>> findPetsByStatus( @NotNull@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity>(HttpStatus.OK)); + default CompletableFuture>> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/xml")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + if (getAcceptHeader().get().contains("application/json")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default PetApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -96,9 +139,28 @@ public interface PetApi { @RequestMapping(value = "/pet/findByTags", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default CompletableFuture>> findPetsByTags( @NotNull@ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity>(HttpStatus.OK)); + default CompletableFuture>> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/xml")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + if (getAcceptHeader().get().contains("application/json")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default PetApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -112,9 +174,28 @@ public interface PetApi { @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default CompletableFuture> getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/xml")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue(" 123456789 doggie aeiou aeiou", Pet.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + if (getAcceptHeader().get().contains("application/json")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue("{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}", Pet.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default PetApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -132,9 +213,12 @@ public interface PetApi { produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.PUT) - default CompletableFuture> updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default PetApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -150,9 +234,12 @@ public interface PetApi { produces = { "application/xml", "application/json" }, consumes = { "application/x-www-form-urlencoded" }, method = RequestMethod.POST) - default CompletableFuture> 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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> 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) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default PetApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -168,9 +255,20 @@ public interface PetApi { produces = { "application/json" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST) - default CompletableFuture> 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") @Valid @RequestPart("file") MultipartFile file, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> 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") @Valid @RequestPart("file") MultipartFile file) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue("{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\"}", ModelApiResponse.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default PetApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApiController.java index 5dd78a0e768..d90808e4ae4 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApiController.java @@ -1,17 +1,31 @@ package io.swagger.api; -import org.springframework.stereotype.Controller; import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; -import javax.validation.constraints.*; -import javax.validation.Valid; +import org.springframework.stereotype.Controller; +import javax.servlet.http.HttpServletRequest; +import java.util.Optional; @Controller public class PetApiController implements PetApi { + private final ObjectMapper objectMapper; - public PetApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public PetApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; + } + + @Override + public Optional getObjectMapper() { + return Optional.ofNullable(objectMapper); + } + + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } 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 dc7778018fe..e77f2de7f70 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 @@ -7,10 +7,13 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -19,17 +22,32 @@ 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.io.IOException; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; +import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; @Api(value = "store", description = "the store API") public interface StoreApi { + Logger log = LoggerFactory.getLogger(StoreApi.class); + + default Optional getObjectMapper() { + return Optional.empty(); + } + + default Optional getRequest() { + return Optional.empty(); + } + + default Optional getAcceptHeader() { + return getRequest().map(r -> r.getHeader("Accept")); + } + @ApiOperation(value = "Delete purchase order by ID", nickname = "deleteOrder", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied"), @@ -37,9 +55,12 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{order_id}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - default CompletableFuture> deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("order_id") String orderId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default StoreApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -51,9 +72,20 @@ public interface StoreApi { @RequestMapping(value = "/store/inventory", produces = { "application/json" }, method = RequestMethod.GET) - default CompletableFuture>> getInventory( @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity>(HttpStatus.OK)); + default CompletableFuture>> getInventory() { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue("{ \"key\" : 0}", Map.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default StoreApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -65,9 +97,28 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{order_id}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default CompletableFuture> getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("order_id") Long orderId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> getOrderById(@Min(1) @Max(5) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/xml")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + if (getAcceptHeader().get().contains("application/json")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default StoreApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -78,9 +129,28 @@ public interface StoreApi { @RequestMapping(value = "/store/order", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - default CompletableFuture> placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/xml")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + if (getAcceptHeader().get().contains("application/json")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default StoreApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApiController.java index 652923c800b..93cb65b21aa 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApiController.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApiController.java @@ -1,17 +1,31 @@ package io.swagger.api; -import org.springframework.stereotype.Controller; import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; -import javax.validation.constraints.*; -import javax.validation.Valid; +import org.springframework.stereotype.Controller; +import javax.servlet.http.HttpServletRequest; +import java.util.Optional; @Controller public class StoreApiController implements StoreApi { + private final ObjectMapper objectMapper; - public StoreApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public StoreApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; + } + + @Override + public Optional getObjectMapper() { + return Optional.ofNullable(objectMapper); + } + + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } 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 1bb90cbfa0b..4e755a2a73d 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 @@ -7,10 +7,13 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -19,26 +22,44 @@ 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.io.IOException; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; +import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; @Api(value = "user", description = "the user API") public interface UserApi { + Logger log = LoggerFactory.getLogger(UserApi.class); + + default Optional getObjectMapper() { + return Optional.empty(); + } + + default Optional getRequest() { + return Optional.empty(); + } + + default Optional getAcceptHeader() { + return getRequest().map(r -> r.getHeader("Accept")); + } + @ApiOperation(value = "Create user", nickname = "createUser", notes = "This can only be done by the logged in user.", tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/user", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - default CompletableFuture> createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default UserApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -48,9 +69,12 @@ public interface UserApi { @RequestMapping(value = "/user/createWithArray", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - default CompletableFuture> createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default UserApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -60,9 +84,12 @@ public interface UserApi { @RequestMapping(value = "/user/createWithList", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - default CompletableFuture> createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default UserApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -73,9 +100,12 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - default CompletableFuture> deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default UserApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -87,9 +117,28 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default CompletableFuture> getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathVariable("username") String username) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/xml")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue(" 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123", User.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + if (getAcceptHeader().get().contains("application/json")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue("{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\"}", User.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default UserApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -100,9 +149,28 @@ public interface UserApi { @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default CompletableFuture> loginUser( @NotNull@ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, @NotNull@ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/xml")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue("aeiou", String.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + if (getAcceptHeader().get().contains("application/json")) { + try { + return CompletableFuture.completedFuture(new ResponseEntity<>(getObjectMapper().get().readValue("\"\"", String.class), HttpStatus.NOT_IMPLEMENTED)); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default UserApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -112,9 +180,12 @@ public interface UserApi { @RequestMapping(value = "/user/logout", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default CompletableFuture> logoutUser( @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> logoutUser() { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default UserApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -125,9 +196,12 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.PUT) - default CompletableFuture> updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); + default CompletableFuture> updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default UserApi interface so no example is generated"); + } + return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApiController.java index 5afeac776dd..319d98d4deb 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApiController.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApiController.java @@ -1,17 +1,31 @@ package io.swagger.api; -import org.springframework.stereotype.Controller; import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; -import javax.validation.constraints.*; -import javax.validation.Valid; +import org.springframework.stereotype.Controller; +import javax.servlet.http.HttpServletRequest; +import java.util.Optional; @Controller public class UserApiController implements UserApi { + private final ObjectMapper objectMapper; - public UserApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public UserApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; + } + + @Override + public Optional getObjectMapper() { + return Optional.ofNullable(objectMapper); + } + + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/FormatTest.java index e809ba3ca62..c73949ecf4f 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/FormatTest.java @@ -71,7 +71,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Min(10) @Max(100) +@Min(10) @Max(100) public Integer getInteger() { return integer; } @@ -93,7 +93,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Min(20) @Max(200) +@Min(20) @Max(200) public Integer getInt32() { return int32; } @@ -137,7 +137,7 @@ public class FormatTest { @NotNull @Valid - @DecimalMin("32.1") @DecimalMax("543.2") +@DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @@ -159,7 +159,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @DecimalMin("54.3") @DecimalMax("987.6") +@DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -181,7 +181,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @DecimalMin("67.8") @DecimalMax("123.4") +@DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -201,7 +201,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Pattern(regexp="/[a-z]/i") +@Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -222,7 +222,7 @@ public class FormatTest { @ApiModelProperty(required = true, value = "") @NotNull - @Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") +@Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") public byte[] getByte() { return _byte; } @@ -327,7 +327,7 @@ public class FormatTest { @ApiModelProperty(required = true, value = "") @NotNull - @Size(min=10,max=64) +@Size(min=10,max=64) public String getPassword() { return password; } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/AnotherFakeApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/AnotherFakeApi.java index a3fcfabaf12..6f6dd920913 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/AnotherFakeApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/AnotherFakeApi.java @@ -6,9 +6,9 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -17,12 +17,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "another-fake", description = "the another-fake API") public interface AnotherFakeApi { @@ -34,6 +32,6 @@ public interface AnotherFakeApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/AnotherFakeApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/AnotherFakeApiController.java index 02fe84a126e..1f969f15713 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/AnotherFakeApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/AnotherFakeApiController.java @@ -1,9 +1,10 @@ package io.swagger.api; import io.swagger.model.Client; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -14,29 +15,39 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class AnotherFakeApiController implements AnotherFakeApi { + + private static final Logger log = LoggerFactory.getLogger(AnotherFakeApiController.class); + private final ObjectMapper objectMapper; - public AnotherFakeApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public AnotherFakeApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java index db6e0e39f59..92b47fb2a37 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java @@ -10,9 +10,9 @@ import io.swagger.model.Client; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import io.swagger.model.OuterComposite; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -21,12 +21,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "fake", description = "the fake API") public interface FakeApi { @@ -36,7 +34,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output boolean", response = Boolean.class) }) @RequestMapping(value = "/fake/outer/boolean", method = RequestMethod.POST) - ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body); @ApiOperation(value = "", nickname = "fakeOuterCompositeSerialize", notes = "Test serialization of object with outer number type", response = OuterComposite.class, tags={ "fake", }) @@ -44,7 +42,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output composite", response = OuterComposite.class) }) @RequestMapping(value = "/fake/outer/composite", method = RequestMethod.POST) - ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body); @ApiOperation(value = "", nickname = "fakeOuterNumberSerialize", notes = "Test serialization of outer number types", response = BigDecimal.class, tags={ "fake", }) @@ -52,7 +50,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output number", response = BigDecimal.class) }) @RequestMapping(value = "/fake/outer/number", method = RequestMethod.POST) - ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body); @ApiOperation(value = "", nickname = "fakeOuterStringSerialize", notes = "Test serialization of outer string types", response = String.class, tags={ "fake", }) @@ -60,7 +58,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output string", response = String.class) }) @RequestMapping(value = "/fake/outer/string", method = RequestMethod.POST) - ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body); @ApiOperation(value = "To test \"client\" model", nickname = "testClientModel", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) @@ -70,7 +68,7 @@ public interface FakeApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", nickname = "testEndpointParameters", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", authorizations = { @@ -83,7 +81,7 @@ public interface FakeApi { produces = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, consumes = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, method = RequestMethod.POST) - ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback); @ApiOperation(value = "To test enum parameters", nickname = "testEnumParameters", notes = "To test enum parameters", tags={ "fake", }) @@ -94,7 +92,16 @@ public interface FakeApi { produces = { "*/*" }, consumes = { "*/*" }, method = RequestMethod.GET) - ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble); + + + @ApiOperation(value = "test inline additionalProperties", nickname = "testInlineAdditionalProperties", notes = "", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation") }) + @RequestMapping(value = "/fake/inline-additionalProperties", + consumes = { "application/json" }, + method = RequestMethod.POST) + ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Object param); @ApiOperation(value = "test json serialization of form data", nickname = "testJsonFormData", notes = "", tags={ "fake", }) @@ -103,6 +110,6 @@ public interface FakeApi { @RequestMapping(value = "/fake/jsonFormData", consumes = { "application/json" }, method = RequestMethod.GET) - ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java index dc7c60f9790..360e1d910d7 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java @@ -5,9 +5,10 @@ import io.swagger.model.Client; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import io.swagger.model.OuterComposite; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -18,112 +19,115 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class FakeApiController implements FakeApi { + + private static final Logger log = LoggerFactory.getLogger(FakeApiController.class); + private final ObjectMapper objectMapper; - public FakeApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public FakeApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ }", Boolean.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ }", Boolean.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"my_string\" : { }, \"my_number\" : { }, \"my_boolean\" : { }}", OuterComposite.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"my_string\" : { }, \"my_number\" : { }, \"my_boolean\" : { }}", OuterComposite.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ }", BigDecimal.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ }", BigDecimal.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ }", String.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ }", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number, - @ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double, - @ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter, - @ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte, - @ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer, - @ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32, - @ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64, - @ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float, - @ApiParam(value = "None") @RequestPart(value="string", required=false) String string, - @ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary, - @ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date, - @ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime, - @ApiParam(value = "None") @RequestPart(value="password", required=false) String password, - @ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray, - @ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString, - @ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, - @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, - @ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray, - @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger, - @ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param, - @ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Object param) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); + } + + public ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeClassnameTestApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeClassnameTestApi.java index 00fffe8a123..8316190673c 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeClassnameTestApi.java @@ -6,9 +6,9 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -17,12 +17,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "fake_classname_test", description = "the fake_classname_test API") public interface FakeClassnameTestApi { @@ -36,6 +34,6 @@ public interface FakeClassnameTestApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeClassnameTestApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeClassnameTestApiController.java index ea2c0016470..37288b4c860 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeClassnameTestApiController.java @@ -1,9 +1,10 @@ package io.swagger.api; import io.swagger.model.Client; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -14,29 +15,39 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class FakeClassnameTestApiController implements FakeClassnameTestApi { + + private static final Logger log = LoggerFactory.getLogger(FakeClassnameTestApiController.class); + private final ObjectMapper objectMapper; - public FakeClassnameTestApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public FakeClassnameTestApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index e8e51f438d6..d4604e9380e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -8,9 +8,9 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -19,12 +19,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "pet", description = "the pet API") public interface PetApi { @@ -41,7 +39,7 @@ public interface PetApi { produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.POST) - ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); @ApiOperation(value = "Deletes a pet", nickname = "deletePet", notes = "", authorizations = { @@ -55,7 +53,7 @@ public interface PetApi { @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "findPetsByStatus", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @@ -70,7 +68,7 @@ public interface PetApi { @RequestMapping(value = "/pet/findByStatus", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByStatus( @NotNull@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status); @ApiOperation(value = "Finds Pets by tags", nickname = "findPetsByTags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -85,7 +83,7 @@ public interface PetApi { @RequestMapping(value = "/pet/findByTags", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByTags( @NotNull@ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags); @ApiOperation(value = "Find pet by ID", nickname = "getPetById", notes = "Returns a single pet", response = Pet.class, authorizations = { @@ -98,7 +96,7 @@ public interface PetApi { @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId); @ApiOperation(value = "Update an existing pet", nickname = "updatePet", notes = "", authorizations = { @@ -115,7 +113,7 @@ public interface PetApi { produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.PUT) - ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); @ApiOperation(value = "Updates a pet in the store with form data", nickname = "updatePetWithForm", notes = "", authorizations = { @@ -130,7 +128,7 @@ public interface PetApi { produces = { "application/xml", "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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "uploadFile", notes = "", response = ModelApiResponse.class, authorizations = { @@ -145,6 +143,6 @@ public interface PetApi { 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") @Valid @RequestPart("file") MultipartFile file, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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") @Valid @RequestPart("file") MultipartFile file); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java index 2153b86a87a..a3890cf787d 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java @@ -3,9 +3,10 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -16,106 +17,128 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class PetApiController implements PetApi { + + private static final Logger log = LoggerFactory.getLogger(PetApiController.class); + private final ObjectMapper objectMapper; - public PetApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public PetApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - 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, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity> findPetsByStatus( @NotNull@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity>(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity> findPetsByTags( @NotNull@ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity>(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 doggie aeiou aeiou", Pet.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 doggie aeiou aeiou", Pet.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}", Pet.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}", Pet.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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 ) @Valid @RequestBody Pet body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - 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, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - 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") @Valid @RequestPart("file") MultipartFile file, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + 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") @Valid @RequestPart("file") MultipartFile file) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\"}", ModelApiResponse.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\"}", ModelApiResponse.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java index 50abaa03dff..f23d712511f 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java @@ -7,9 +7,9 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,12 +18,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "store", description = "the store API") public interface StoreApi { @@ -35,7 +33,7 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{order_id}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("order_id") String orderId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId); @ApiOperation(value = "Returns pet inventories by status", nickname = "getInventory", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @@ -46,7 +44,7 @@ public interface StoreApi { @RequestMapping(value = "/store/inventory", produces = { "application/json" }, method = RequestMethod.GET) - ResponseEntity> getInventory( @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> getInventory(); @ApiOperation(value = "Find purchase order by ID", nickname = "getOrderById", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @@ -57,7 +55,7 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{order_id}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("order_id") Long orderId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity getOrderById(@Min(1) @Max(5) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId); @ApiOperation(value = "Place an order for a pet", nickname = "placeOrder", notes = "", response = Order.class, tags={ "store", }) @@ -67,6 +65,6 @@ public interface StoreApi { @RequestMapping(value = "/store/order", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApiController.java index 6e596b41279..6e463e1307f 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApiController.java @@ -2,9 +2,10 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -15,66 +16,90 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class StoreApiController implements StoreApi { + + private static final Logger log = LoggerFactory.getLogger(StoreApiController.class); + private final ObjectMapper objectMapper; - public StoreApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public StoreApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("order_id") String orderId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity> getInventory(@RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity> getInventory() { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity>(objectMapper.readValue("{ \"key\" : 0}", Map.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue("{ \"key\" : 0}", Map.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity>(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("order_id") Long orderId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity getOrderById(@Min(1) @Max(5) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java index 7264a3bc9cc..3dbcf7293cd 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java @@ -7,9 +7,9 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,12 +18,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "user", description = "the user API") public interface UserApi { @@ -34,7 +32,7 @@ public interface UserApi { @RequestMapping(value = "/user", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body); @ApiOperation(value = "Creates list of users with given input array", nickname = "createUsersWithArrayInput", notes = "", tags={ "user", }) @@ -43,7 +41,7 @@ public interface UserApi { @RequestMapping(value = "/user/createWithArray", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); @ApiOperation(value = "Creates list of users with given input array", nickname = "createUsersWithListInput", notes = "", tags={ "user", }) @@ -52,7 +50,7 @@ public interface UserApi { @RequestMapping(value = "/user/createWithList", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); @ApiOperation(value = "Delete user", nickname = "deleteUser", notes = "This can only be done by the logged in user.", tags={ "user", }) @@ -62,7 +60,7 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username); @ApiOperation(value = "Get user by user name", nickname = "getUserByName", notes = "", response = User.class, tags={ "user", }) @@ -73,7 +71,7 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "loginUser", notes = "", response = String.class, tags={ "user", }) @@ -83,7 +81,7 @@ public interface UserApi { @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity loginUser( @NotNull@ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, @NotNull@ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password); @ApiOperation(value = "Logs out current logged in user session", nickname = "logoutUser", notes = "", tags={ "user", }) @@ -92,7 +90,7 @@ public interface UserApi { @RequestMapping(value = "/user/logout", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity logoutUser( @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity logoutUser(); @ApiOperation(value = "Updated user", nickname = "updateUser", notes = "This can only be done by the logged in user.", tags={ "user", }) @@ -102,6 +100,6 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "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 ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApiController.java index c0f360c3543..e96dfe648b4 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApiController.java @@ -2,9 +2,10 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -15,87 +16,101 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class UserApiController implements UserApi { + + private static final Logger log = LoggerFactory.getLogger(UserApiController.class); + private final ObjectMapper objectMapper; - public UserApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public UserApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathVariable("username") String username) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123", User.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123", User.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\"}", User.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\"}", User.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity loginUser( @NotNull@ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, - @NotNull@ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue("aeiou", String.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("aeiou", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("\"\"", String.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("\"\"", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity logoutUser(@RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity logoutUser() { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, - @ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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 ) @Valid @RequestBody User body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/FormatTest.java index 9d47a2e4245..9a7f3ff8be1 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/FormatTest.java @@ -71,7 +71,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Min(10) @Max(100) +@Min(10) @Max(100) public Integer getInteger() { return integer; } @@ -93,7 +93,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Min(20) @Max(200) +@Min(20) @Max(200) public Integer getInt32() { return int32; } @@ -137,7 +137,7 @@ public class FormatTest { @NotNull @Valid - @DecimalMin("32.1") @DecimalMax("543.2") +@DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @@ -159,7 +159,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @DecimalMin("54.3") @DecimalMax("987.6") +@DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -181,7 +181,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @DecimalMin("67.8") @DecimalMax("123.4") +@DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -201,7 +201,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Pattern(regexp="/[a-z]/i") +@Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -222,7 +222,7 @@ public class FormatTest { @ApiModelProperty(required = true, value = "") @NotNull - @Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") +@Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") public byte[] getByte() { return _byte; } @@ -327,7 +327,7 @@ public class FormatTest { @ApiModelProperty(required = true, value = "") @NotNull - @Size(min=10,max=64) +@Size(min=10,max=64) public String getPassword() { return password; } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/AnotherFakeApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/AnotherFakeApi.java index a3fcfabaf12..6f6dd920913 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/AnotherFakeApi.java @@ -6,9 +6,9 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -17,12 +17,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "another-fake", description = "the another-fake API") public interface AnotherFakeApi { @@ -34,6 +32,6 @@ public interface AnotherFakeApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/AnotherFakeApiController.java index 02fe84a126e..1f969f15713 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/AnotherFakeApiController.java @@ -1,9 +1,10 @@ package io.swagger.api; import io.swagger.model.Client; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -14,29 +15,39 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class AnotherFakeApiController implements AnotherFakeApi { + + private static final Logger log = LoggerFactory.getLogger(AnotherFakeApiController.class); + private final ObjectMapper objectMapper; - public AnotherFakeApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public AnotherFakeApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/FakeApi.java index db6e0e39f59..92b47fb2a37 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/FakeApi.java @@ -10,9 +10,9 @@ import io.swagger.model.Client; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import io.swagger.model.OuterComposite; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -21,12 +21,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "fake", description = "the fake API") public interface FakeApi { @@ -36,7 +34,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output boolean", response = Boolean.class) }) @RequestMapping(value = "/fake/outer/boolean", method = RequestMethod.POST) - ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body); @ApiOperation(value = "", nickname = "fakeOuterCompositeSerialize", notes = "Test serialization of object with outer number type", response = OuterComposite.class, tags={ "fake", }) @@ -44,7 +42,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output composite", response = OuterComposite.class) }) @RequestMapping(value = "/fake/outer/composite", method = RequestMethod.POST) - ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body); @ApiOperation(value = "", nickname = "fakeOuterNumberSerialize", notes = "Test serialization of outer number types", response = BigDecimal.class, tags={ "fake", }) @@ -52,7 +50,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output number", response = BigDecimal.class) }) @RequestMapping(value = "/fake/outer/number", method = RequestMethod.POST) - ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body); @ApiOperation(value = "", nickname = "fakeOuterStringSerialize", notes = "Test serialization of outer string types", response = String.class, tags={ "fake", }) @@ -60,7 +58,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output string", response = String.class) }) @RequestMapping(value = "/fake/outer/string", method = RequestMethod.POST) - ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body); @ApiOperation(value = "To test \"client\" model", nickname = "testClientModel", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) @@ -70,7 +68,7 @@ public interface FakeApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", nickname = "testEndpointParameters", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", authorizations = { @@ -83,7 +81,7 @@ public interface FakeApi { produces = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, consumes = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, method = RequestMethod.POST) - ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback); @ApiOperation(value = "To test enum parameters", nickname = "testEnumParameters", notes = "To test enum parameters", tags={ "fake", }) @@ -94,7 +92,16 @@ public interface FakeApi { produces = { "*/*" }, consumes = { "*/*" }, method = RequestMethod.GET) - ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble); + + + @ApiOperation(value = "test inline additionalProperties", nickname = "testInlineAdditionalProperties", notes = "", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation") }) + @RequestMapping(value = "/fake/inline-additionalProperties", + consumes = { "application/json" }, + method = RequestMethod.POST) + ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Object param); @ApiOperation(value = "test json serialization of form data", nickname = "testJsonFormData", notes = "", tags={ "fake", }) @@ -103,6 +110,6 @@ public interface FakeApi { @RequestMapping(value = "/fake/jsonFormData", consumes = { "application/json" }, method = RequestMethod.GET) - ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2); } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/FakeApiController.java index dc7c60f9790..360e1d910d7 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/FakeApiController.java @@ -5,9 +5,10 @@ import io.swagger.model.Client; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import io.swagger.model.OuterComposite; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -18,112 +19,115 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class FakeApiController implements FakeApi { + + private static final Logger log = LoggerFactory.getLogger(FakeApiController.class); + private final ObjectMapper objectMapper; - public FakeApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public FakeApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ }", Boolean.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ }", Boolean.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"my_string\" : { }, \"my_number\" : { }, \"my_boolean\" : { }}", OuterComposite.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"my_string\" : { }, \"my_number\" : { }, \"my_boolean\" : { }}", OuterComposite.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ }", BigDecimal.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ }", BigDecimal.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ }", String.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ }", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number, - @ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double, - @ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter, - @ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte, - @ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer, - @ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32, - @ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64, - @ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float, - @ApiParam(value = "None") @RequestPart(value="string", required=false) String string, - @ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary, - @ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date, - @ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime, - @ApiParam(value = "None") @RequestPart(value="password", required=false) String password, - @ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray, - @ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString, - @ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, - @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, - @ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray, - @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger, - @ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param, - @ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Object param) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); + } + + public ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/FakeClassnameTestApi.java index 00fffe8a123..8316190673c 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/FakeClassnameTestApi.java @@ -6,9 +6,9 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -17,12 +17,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "fake_classname_test", description = "the fake_classname_test API") public interface FakeClassnameTestApi { @@ -36,6 +34,6 @@ public interface FakeClassnameTestApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/FakeClassnameTestApiController.java index ea2c0016470..37288b4c860 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/FakeClassnameTestApiController.java @@ -1,9 +1,10 @@ package io.swagger.api; import io.swagger.model.Client; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -14,29 +15,39 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class FakeClassnameTestApiController implements FakeClassnameTestApi { + + private static final Logger log = LoggerFactory.getLogger(FakeClassnameTestApiController.class); + private final ObjectMapper objectMapper; - public FakeClassnameTestApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public FakeClassnameTestApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/PetApi.java index e8e51f438d6..d4604e9380e 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/PetApi.java @@ -8,9 +8,9 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -19,12 +19,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "pet", description = "the pet API") public interface PetApi { @@ -41,7 +39,7 @@ public interface PetApi { produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.POST) - ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); @ApiOperation(value = "Deletes a pet", nickname = "deletePet", notes = "", authorizations = { @@ -55,7 +53,7 @@ public interface PetApi { @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "findPetsByStatus", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @@ -70,7 +68,7 @@ public interface PetApi { @RequestMapping(value = "/pet/findByStatus", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByStatus( @NotNull@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status); @ApiOperation(value = "Finds Pets by tags", nickname = "findPetsByTags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -85,7 +83,7 @@ public interface PetApi { @RequestMapping(value = "/pet/findByTags", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByTags( @NotNull@ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags); @ApiOperation(value = "Find pet by ID", nickname = "getPetById", notes = "Returns a single pet", response = Pet.class, authorizations = { @@ -98,7 +96,7 @@ public interface PetApi { @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId); @ApiOperation(value = "Update an existing pet", nickname = "updatePet", notes = "", authorizations = { @@ -115,7 +113,7 @@ public interface PetApi { produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.PUT) - ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); @ApiOperation(value = "Updates a pet in the store with form data", nickname = "updatePetWithForm", notes = "", authorizations = { @@ -130,7 +128,7 @@ public interface PetApi { produces = { "application/xml", "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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "uploadFile", notes = "", response = ModelApiResponse.class, authorizations = { @@ -145,6 +143,6 @@ public interface PetApi { 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") @Valid @RequestPart("file") MultipartFile file, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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") @Valid @RequestPart("file") MultipartFile file); } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/PetApiController.java index 2153b86a87a..a3890cf787d 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/PetApiController.java @@ -3,9 +3,10 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -16,106 +17,128 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class PetApiController implements PetApi { + + private static final Logger log = LoggerFactory.getLogger(PetApiController.class); + private final ObjectMapper objectMapper; - public PetApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public PetApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - 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, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity> findPetsByStatus( @NotNull@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity>(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity> findPetsByTags( @NotNull@ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity>(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 doggie aeiou aeiou", Pet.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 doggie aeiou aeiou", Pet.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}", Pet.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}", Pet.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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 ) @Valid @RequestBody Pet body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - 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, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - 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") @Valid @RequestPart("file") MultipartFile file, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + 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") @Valid @RequestPart("file") MultipartFile file) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\"}", ModelApiResponse.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\"}", ModelApiResponse.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/StoreApi.java index 50abaa03dff..f23d712511f 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/StoreApi.java @@ -7,9 +7,9 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,12 +18,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "store", description = "the store API") public interface StoreApi { @@ -35,7 +33,7 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{order_id}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("order_id") String orderId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId); @ApiOperation(value = "Returns pet inventories by status", nickname = "getInventory", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @@ -46,7 +44,7 @@ public interface StoreApi { @RequestMapping(value = "/store/inventory", produces = { "application/json" }, method = RequestMethod.GET) - ResponseEntity> getInventory( @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> getInventory(); @ApiOperation(value = "Find purchase order by ID", nickname = "getOrderById", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @@ -57,7 +55,7 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{order_id}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("order_id") Long orderId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity getOrderById(@Min(1) @Max(5) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId); @ApiOperation(value = "Place an order for a pet", nickname = "placeOrder", notes = "", response = Order.class, tags={ "store", }) @@ -67,6 +65,6 @@ public interface StoreApi { @RequestMapping(value = "/store/order", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body); } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/StoreApiController.java index 6e596b41279..6e463e1307f 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/StoreApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/StoreApiController.java @@ -2,9 +2,10 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -15,66 +16,90 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class StoreApiController implements StoreApi { + + private static final Logger log = LoggerFactory.getLogger(StoreApiController.class); + private final ObjectMapper objectMapper; - public StoreApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public StoreApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("order_id") String orderId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity> getInventory(@RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity> getInventory() { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity>(objectMapper.readValue("{ \"key\" : 0}", Map.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue("{ \"key\" : 0}", Map.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity>(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("order_id") Long orderId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity getOrderById(@Min(1) @Max(5) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/UserApi.java index 7264a3bc9cc..3dbcf7293cd 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/UserApi.java @@ -7,9 +7,9 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,12 +18,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "user", description = "the user API") public interface UserApi { @@ -34,7 +32,7 @@ public interface UserApi { @RequestMapping(value = "/user", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body); @ApiOperation(value = "Creates list of users with given input array", nickname = "createUsersWithArrayInput", notes = "", tags={ "user", }) @@ -43,7 +41,7 @@ public interface UserApi { @RequestMapping(value = "/user/createWithArray", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); @ApiOperation(value = "Creates list of users with given input array", nickname = "createUsersWithListInput", notes = "", tags={ "user", }) @@ -52,7 +50,7 @@ public interface UserApi { @RequestMapping(value = "/user/createWithList", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); @ApiOperation(value = "Delete user", nickname = "deleteUser", notes = "This can only be done by the logged in user.", tags={ "user", }) @@ -62,7 +60,7 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username); @ApiOperation(value = "Get user by user name", nickname = "getUserByName", notes = "", response = User.class, tags={ "user", }) @@ -73,7 +71,7 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "loginUser", notes = "", response = String.class, tags={ "user", }) @@ -83,7 +81,7 @@ public interface UserApi { @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity loginUser( @NotNull@ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, @NotNull@ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password); @ApiOperation(value = "Logs out current logged in user session", nickname = "logoutUser", notes = "", tags={ "user", }) @@ -92,7 +90,7 @@ public interface UserApi { @RequestMapping(value = "/user/logout", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity logoutUser( @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity logoutUser(); @ApiOperation(value = "Updated user", nickname = "updateUser", notes = "This can only be done by the logged in user.", tags={ "user", }) @@ -102,6 +100,6 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "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 ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body); } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/UserApiController.java index c0f360c3543..e96dfe648b4 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/UserApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/api/UserApiController.java @@ -2,9 +2,10 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -15,87 +16,101 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class UserApiController implements UserApi { + + private static final Logger log = LoggerFactory.getLogger(UserApiController.class); + private final ObjectMapper objectMapper; - public UserApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public UserApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathVariable("username") String username) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123", User.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123", User.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\"}", User.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\"}", User.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity loginUser( @NotNull@ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, - @NotNull@ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue("aeiou", String.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("aeiou", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("\"\"", String.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("\"\"", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity logoutUser(@RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity logoutUser() { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, - @ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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 ) @Valid @RequestBody User body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/model/FormatTest.java index 9d47a2e4245..9a7f3ff8be1 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/io/swagger/model/FormatTest.java @@ -71,7 +71,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Min(10) @Max(100) +@Min(10) @Max(100) public Integer getInteger() { return integer; } @@ -93,7 +93,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Min(20) @Max(200) +@Min(20) @Max(200) public Integer getInt32() { return int32; } @@ -137,7 +137,7 @@ public class FormatTest { @NotNull @Valid - @DecimalMin("32.1") @DecimalMax("543.2") +@DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @@ -159,7 +159,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @DecimalMin("54.3") @DecimalMax("987.6") +@DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -181,7 +181,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @DecimalMin("67.8") @DecimalMax("123.4") +@DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -201,7 +201,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Pattern(regexp="/[a-z]/i") +@Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -222,7 +222,7 @@ public class FormatTest { @ApiModelProperty(required = true, value = "") @NotNull - @Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") +@Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") public byte[] getByte() { return _byte; } @@ -327,7 +327,7 @@ public class FormatTest { @ApiModelProperty(required = true, value = "") @NotNull - @Size(min=10,max=64) +@Size(min=10,max=64) public String getPassword() { return password; } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/AnotherFakeApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/AnotherFakeApi.java index a54382d9a2f..3c73a0fc9e8 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/AnotherFakeApi.java @@ -6,10 +6,9 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,16 +17,16 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "another-fake", description = "the another-fake API") public interface AnotherFakeApi { + AnotherFakeApiDelegate getDelegate(); + @ApiOperation(value = "To test special tags", nickname = "testSpecialTags", notes = "To test special tags", response = Client.class, tags={ "$another-fake?", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) @@ -35,9 +34,8 @@ public interface AnotherFakeApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - default ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + return getDelegate().testSpecialTags(body); } } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/AnotherFakeApiController.java index b1b9e947700..e3570fece01 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/AnotherFakeApiController.java @@ -1,32 +1,9 @@ package io.swagger.api; -import io.swagger.model.Client; - -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; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; -import javax.validation.constraints.*; -import javax.validation.Valid; @Controller public class AnotherFakeApiController implements AnotherFakeApi { - private final ObjectMapper objectMapper; - - public AnotherFakeApiController(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } private final AnotherFakeApiDelegate delegate; @@ -35,10 +12,8 @@ public class AnotherFakeApiController implements AnotherFakeApi { this.delegate = delegate; } - public ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.testSpecialTags(body); + @Override + public AnotherFakeApiDelegate getDelegate() { + return delegate; } - } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/AnotherFakeApiDelegate.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/AnotherFakeApiDelegate.java index 2ff944839dc..f90bc38b5a4 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/AnotherFakeApiDelegate.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/AnotherFakeApiDelegate.java @@ -1,28 +1,57 @@ package io.swagger.api; import io.swagger.model.Client; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; +import java.io.IOException; +import javax.servlet.http.HttpServletRequest; import java.util.List; +import java.util.Optional; /** * A delegate to be called by the {@link AnotherFakeApiController}}. - * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. - * Instead, use spring to autowire this class into the {@link AnotherFakeApiController}. + * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class. */ public interface AnotherFakeApiDelegate { + Logger log = LoggerFactory.getLogger(AnotherFakeApi.class); + + default Optional getObjectMapper() { + return Optional.empty(); + } + + default Optional getRequest() { + return Optional.empty(); + } + + default Optional getAcceptHeader() { + return getRequest().map(r -> r.getHeader("Accept")); + } + /** * @see AnotherFakeApi#testSpecialTags */ default ResponseEntity testSpecialTags(Client body) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default AnotherFakeApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApi.java index 79cc25c16b0..3b0cb73a377 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApi.java @@ -10,10 +10,9 @@ import io.swagger.model.Client; import java.time.LocalDate; import java.time.OffsetDateTime; import io.swagger.model.OuterComposite; - import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -22,24 +21,23 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "fake", description = "the fake API") public interface FakeApi { + FakeApiDelegate getDelegate(); + @ApiOperation(value = "", nickname = "fakeOuterBooleanSerialize", notes = "Test serialization of outer boolean types", response = Boolean.class, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Output boolean", response = Boolean.class) }) @RequestMapping(value = "/fake/outer/boolean", method = RequestMethod.POST) - default ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { + return getDelegate().fakeOuterBooleanSerialize(body); } @@ -48,9 +46,8 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output composite", response = OuterComposite.class) }) @RequestMapping(value = "/fake/outer/composite", method = RequestMethod.POST) - default ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { + return getDelegate().fakeOuterCompositeSerialize(body); } @@ -59,9 +56,8 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output number", response = BigDecimal.class) }) @RequestMapping(value = "/fake/outer/number", method = RequestMethod.POST) - default ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { + return getDelegate().fakeOuterNumberSerialize(body); } @@ -70,9 +66,8 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output string", response = String.class) }) @RequestMapping(value = "/fake/outer/string", method = RequestMethod.POST) - default ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { + return getDelegate().fakeOuterStringSerialize(body); } @@ -83,9 +78,8 @@ public interface FakeApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - default ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + return getDelegate().testClientModel(body); } @@ -99,9 +93,8 @@ public interface FakeApi { produces = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, consumes = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, method = RequestMethod.POST) - default ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback) { + return getDelegate().testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); } @@ -113,9 +106,19 @@ public interface FakeApi { produces = { "*/*" }, consumes = { "*/*" }, method = RequestMethod.GET) - default ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble) { + return getDelegate().testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + } + + + @ApiOperation(value = "test inline additionalProperties", nickname = "testInlineAdditionalProperties", notes = "", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation") }) + @RequestMapping(value = "/fake/inline-additionalProperties", + consumes = { "application/json" }, + method = RequestMethod.POST) + default ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Object param) { + return getDelegate().testInlineAdditionalProperties(param); } @@ -125,9 +128,8 @@ public interface FakeApi { @RequestMapping(value = "/fake/jsonFormData", consumes = { "application/json" }, method = RequestMethod.GET) - default ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2) { + return getDelegate().testJsonFormData(param, param2); } } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiController.java index fd75b3ed154..360cfa12ad7 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiController.java @@ -1,36 +1,9 @@ package io.swagger.api; -import java.math.BigDecimal; -import io.swagger.model.Client; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import io.swagger.model.OuterComposite; - -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; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; -import javax.validation.constraints.*; -import javax.validation.Valid; @Controller public class FakeApiController implements FakeApi { - private final ObjectMapper objectMapper; - - public FakeApiController(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } private final FakeApiDelegate delegate; @@ -39,73 +12,8 @@ public class FakeApiController implements FakeApi { this.delegate = delegate; } - public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.fakeOuterBooleanSerialize(body); + @Override + public FakeApiDelegate getDelegate() { + return delegate; } - - public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.fakeOuterCompositeSerialize(body); - } - - public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.fakeOuterNumberSerialize(body); - } - - public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.fakeOuterStringSerialize(body); - } - - public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.testClientModel(body); - } - - public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number, - @ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double, - @ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter, - @ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte, - @ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer, - @ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32, - @ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64, - @ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float, - @ApiParam(value = "None") @RequestPart(value="string", required=false) String string, - @ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary, - @ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date, - @ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime, - @ApiParam(value = "None") @RequestPart(value="password", required=false) String password, - @ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); - } - - public ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray, - @ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString, - @ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, - @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, - @ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray, - @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger, - @ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); - } - - public ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param, - @ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.testJsonFormData(param, param2); - } - } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiDelegate.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiDelegate.java index 6029e71010b..c58dc82e5b9 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiDelegate.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiDelegate.java @@ -5,60 +5,133 @@ import io.swagger.model.Client; import java.time.LocalDate; import java.time.OffsetDateTime; import io.swagger.model.OuterComposite; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; +import java.io.IOException; +import javax.servlet.http.HttpServletRequest; import java.util.List; +import java.util.Optional; /** * A delegate to be called by the {@link FakeApiController}}. - * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. - * Instead, use spring to autowire this class into the {@link FakeApiController}. + * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class. */ public interface FakeApiDelegate { + Logger log = LoggerFactory.getLogger(FakeApi.class); + + default Optional getObjectMapper() { + return Optional.empty(); + } + + default Optional getRequest() { + return Optional.empty(); + } + + default Optional getAcceptHeader() { + return getRequest().map(r -> r.getHeader("Accept")); + } + /** * @see FakeApi#fakeOuterBooleanSerialize */ default ResponseEntity fakeOuterBooleanSerialize(Boolean body) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue("{ }", Boolean.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** * @see FakeApi#fakeOuterCompositeSerialize */ default ResponseEntity fakeOuterCompositeSerialize(OuterComposite body) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue("{ \"my_string\" : { }, \"my_number\" : { }, \"my_boolean\" : { }}", OuterComposite.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** * @see FakeApi#fakeOuterNumberSerialize */ default ResponseEntity fakeOuterNumberSerialize(BigDecimal body) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue("{ }", BigDecimal.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** * @see FakeApi#fakeOuterStringSerialize */ default ResponseEntity fakeOuterStringSerialize(String body) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue("{ }", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** * @see FakeApi#testClientModel */ default ResponseEntity testClientModel(Client body) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** @@ -78,8 +151,11 @@ public interface FakeApiDelegate { OffsetDateTime dateTime, String password, String paramCallback) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** @@ -93,8 +169,22 @@ public interface FakeApiDelegate { String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + } + + /** + * @see FakeApi#testInlineAdditionalProperties + */ + default ResponseEntity testInlineAdditionalProperties(Object param) { + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** @@ -102,8 +192,11 @@ public interface FakeApiDelegate { */ default ResponseEntity testJsonFormData(String param, String param2) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeClassnameTestApi.java index 9473d86b65e..ef017ee1dc8 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeClassnameTestApi.java @@ -6,10 +6,9 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,16 +17,16 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "fake_classname_test", description = "the fake_classname_test API") public interface FakeClassnameTestApi { + FakeClassnameTestApiDelegate getDelegate(); + @ApiOperation(value = "To test class name in snake case", nickname = "testClassname", notes = "", response = Client.class, authorizations = { @Authorization(value = "api_key_query") }, tags={ "fake_classname_tags 123#$%^", }) @@ -37,9 +36,8 @@ public interface FakeClassnameTestApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - default ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + return getDelegate().testClassname(body); } } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeClassnameTestApiController.java index cd4c0acd562..865fcb34720 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeClassnameTestApiController.java @@ -1,32 +1,9 @@ package io.swagger.api; -import io.swagger.model.Client; - -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; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; -import javax.validation.constraints.*; -import javax.validation.Valid; @Controller public class FakeClassnameTestApiController implements FakeClassnameTestApi { - private final ObjectMapper objectMapper; - - public FakeClassnameTestApiController(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } private final FakeClassnameTestApiDelegate delegate; @@ -35,10 +12,8 @@ public class FakeClassnameTestApiController implements FakeClassnameTestApi { this.delegate = delegate; } - public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.testClassname(body); + @Override + public FakeClassnameTestApiDelegate getDelegate() { + return delegate; } - } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeClassnameTestApiDelegate.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeClassnameTestApiDelegate.java index 4177e820636..32cb063e052 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeClassnameTestApiDelegate.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeClassnameTestApiDelegate.java @@ -1,28 +1,57 @@ package io.swagger.api; import io.swagger.model.Client; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; +import java.io.IOException; +import javax.servlet.http.HttpServletRequest; import java.util.List; +import java.util.Optional; /** * A delegate to be called by the {@link FakeClassnameTestApiController}}. - * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. - * Instead, use spring to autowire this class into the {@link FakeClassnameTestApiController}. + * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class. */ public interface FakeClassnameTestApiDelegate { + Logger log = LoggerFactory.getLogger(FakeClassnameTestApi.class); + + default Optional getObjectMapper() { + return Optional.empty(); + } + + default Optional getRequest() { + return Optional.empty(); + } + + default Optional getAcceptHeader() { + return getRequest().map(r -> r.getHeader("Accept")); + } + /** * @see FakeClassnameTestApi#testClassname */ default ResponseEntity testClassname(Client body) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default FakeClassnameTestApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApi.java index 239a5e189d6..b892573f52c 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApi.java @@ -8,10 +8,9 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -20,16 +19,16 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "pet", description = "the pet API") public interface PetApi { + PetApiDelegate getDelegate(); + @ApiOperation(value = "Add a new pet to the store", nickname = "addPet", notes = "", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @@ -42,9 +41,8 @@ public interface PetApi { produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.POST) - default ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { + return getDelegate().addPet(body); } @@ -59,9 +57,8 @@ public interface PetApi { @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - default ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { + return getDelegate().deletePet(petId, apiKey); } @@ -77,9 +74,8 @@ public interface PetApi { @RequestMapping(value = "/pet/findByStatus", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default ResponseEntity> findPetsByStatus( @NotNull@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity>(HttpStatus.OK); + default ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status) { + return getDelegate().findPetsByStatus(status); } @@ -95,9 +91,8 @@ public interface PetApi { @RequestMapping(value = "/pet/findByTags", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default ResponseEntity> findPetsByTags( @NotNull@ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity>(HttpStatus.OK); + default ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags) { + return getDelegate().findPetsByTags(tags); } @@ -111,9 +106,8 @@ public interface PetApi { @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId) { + return getDelegate().getPetById(petId); } @@ -131,9 +125,8 @@ public interface PetApi { produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.PUT) - default ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { + return getDelegate().updatePet(body); } @@ -149,9 +142,8 @@ public interface PetApi { produces = { "application/xml", "application/json" }, consumes = { "application/x-www-form-urlencoded" }, method = RequestMethod.POST) - default 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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default 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) { + return getDelegate().updatePetWithForm(petId, name, status); } @@ -167,9 +159,8 @@ public interface PetApi { produces = { "application/json" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST) - default 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") @Valid @RequestPart("file") MultipartFile file, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default 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") @Valid @RequestPart("file") MultipartFile file) { + return getDelegate().uploadFile(petId, additionalMetadata, file); } } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiController.java index 62d04acc8fc..bbcd9229039 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiController.java @@ -1,34 +1,9 @@ package io.swagger.api; -import io.swagger.model.ModelApiResponse; -import io.swagger.model.Pet; -import org.springframework.core.io.Resource; - -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; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; -import javax.validation.constraints.*; -import javax.validation.Valid; @Controller public class PetApiController implements PetApi { - private final ObjectMapper objectMapper; - - public PetApiController(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } private final PetApiDelegate delegate; @@ -37,57 +12,8 @@ public class PetApiController implements PetApi { this.delegate = delegate; } - public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.addPet(body); + @Override + public PetApiDelegate getDelegate() { + return delegate; } - - 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, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.deletePet(petId, apiKey); - } - - public ResponseEntity> findPetsByStatus( @NotNull@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.findPetsByStatus(status); - } - - public ResponseEntity> findPetsByTags( @NotNull@ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.findPetsByTags(tags); - } - - public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.getPetById(petId); - } - - public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.updatePet(body); - } - - 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, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.updatePetWithForm(petId, name, status); - } - - 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") @Valid @RequestPart("file") MultipartFile file, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.uploadFile(petId, additionalMetadata, file); - } - } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiDelegate.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiDelegate.java index 265e7046956..065e3d60441 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiDelegate.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiDelegate.java @@ -3,28 +3,49 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; +import java.io.IOException; +import javax.servlet.http.HttpServletRequest; import java.util.List; +import java.util.Optional; /** * A delegate to be called by the {@link PetApiController}}. - * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. - * Instead, use spring to autowire this class into the {@link PetApiController}. + * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class. */ public interface PetApiDelegate { + Logger log = LoggerFactory.getLogger(PetApi.class); + + default Optional getObjectMapper() { + return Optional.empty(); + } + + default Optional getRequest() { + return Optional.empty(); + } + + default Optional getAcceptHeader() { + return getRequest().map(r -> r.getHeader("Accept")); + } + /** * @see PetApi#addPet */ default ResponseEntity addPet(Pet body) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default PetApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** @@ -32,40 +53,103 @@ public interface PetApiDelegate { */ default ResponseEntity deletePet(Long petId, String apiKey) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default PetApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** * @see PetApi#findPetsByStatus */ default ResponseEntity> findPetsByStatus(List status) { - // do some magic! - return new ResponseEntity>(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/xml")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + if (getAcceptHeader().get().contains("application/json")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default PetApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** * @see PetApi#findPetsByTags */ default ResponseEntity> findPetsByTags(List tags) { - // do some magic! - return new ResponseEntity>(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/xml")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + if (getAcceptHeader().get().contains("application/json")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default PetApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** * @see PetApi#getPetById */ default ResponseEntity getPetById(Long petId) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/xml")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue(" 123456789 doggie aeiou aeiou", Pet.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + if (getAcceptHeader().get().contains("application/json")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue("{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}", Pet.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default PetApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** * @see PetApi#updatePet */ default ResponseEntity updatePet(Pet body) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default PetApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** @@ -74,8 +158,11 @@ public interface PetApiDelegate { default ResponseEntity updatePetWithForm(Long petId, String name, String status) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default PetApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** @@ -84,8 +171,19 @@ public interface PetApiDelegate { default ResponseEntity uploadFile(Long petId, String additionalMetadata, MultipartFile file) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue("{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\"}", ModelApiResponse.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default PetApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApi.java index 2361343fe79..40a3b4f23f3 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApi.java @@ -7,10 +7,9 @@ package io.swagger.api; 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.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -19,16 +18,16 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "store", description = "the store API") public interface StoreApi { + StoreApiDelegate getDelegate(); + @ApiOperation(value = "Delete purchase order by ID", nickname = "deleteOrder", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied"), @@ -36,9 +35,8 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{order_id}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - default ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("order_id") String orderId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId) { + return getDelegate().deleteOrder(orderId); } @@ -50,9 +48,8 @@ public interface StoreApi { @RequestMapping(value = "/store/inventory", produces = { "application/json" }, method = RequestMethod.GET) - default ResponseEntity> getInventory( @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity>(HttpStatus.OK); + default ResponseEntity> getInventory() { + return getDelegate().getInventory(); } @@ -64,9 +61,8 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{order_id}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("order_id") Long orderId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity getOrderById(@Min(1) @Max(5) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId) { + return getDelegate().getOrderById(orderId); } @@ -77,9 +73,8 @@ public interface StoreApi { @RequestMapping(value = "/store/order", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - default ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body) { + return getDelegate().placeOrder(body); } } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiController.java index dff545adaba..a47931a4f70 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiController.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiController.java @@ -1,33 +1,9 @@ package io.swagger.api; -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; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; -import javax.validation.constraints.*; -import javax.validation.Valid; @Controller public class StoreApiController implements StoreApi { - private final ObjectMapper objectMapper; - - public StoreApiController(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } private final StoreApiDelegate delegate; @@ -36,27 +12,8 @@ public class StoreApiController implements StoreApi { this.delegate = delegate; } - public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("order_id") String orderId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.deleteOrder(orderId); + @Override + public StoreApiDelegate getDelegate() { + return delegate; } - - public ResponseEntity> getInventory(@RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.getInventory(); - } - - public ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("order_id") Long orderId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.getOrderById(orderId); - } - - public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.placeOrder(body); - } - } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiDelegate.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiDelegate.java index 17a4dfc2a9d..17583c39939 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiDelegate.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiDelegate.java @@ -2,52 +2,122 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; +import java.io.IOException; +import javax.servlet.http.HttpServletRequest; import java.util.List; +import java.util.Optional; /** * A delegate to be called by the {@link StoreApiController}}. - * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. - * Instead, use spring to autowire this class into the {@link StoreApiController}. + * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class. */ public interface StoreApiDelegate { + Logger log = LoggerFactory.getLogger(StoreApi.class); + + default Optional getObjectMapper() { + return Optional.empty(); + } + + default Optional getRequest() { + return Optional.empty(); + } + + default Optional getAcceptHeader() { + return getRequest().map(r -> r.getHeader("Accept")); + } + /** * @see StoreApi#deleteOrder */ default ResponseEntity deleteOrder(String orderId) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default StoreApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** * @see StoreApi#getInventory */ default ResponseEntity> getInventory() { - // do some magic! - return new ResponseEntity>(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/json")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue("{ \"key\" : 0}", Map.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default StoreApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** * @see StoreApi#getOrderById */ default ResponseEntity getOrderById(Long orderId) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/xml")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + if (getAcceptHeader().get().contains("application/json")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default StoreApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** * @see StoreApi#placeOrder */ default ResponseEntity placeOrder(Order body) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/xml")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + if (getAcceptHeader().get().contains("application/json")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default StoreApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApi.java index aeb4b57e667..db6ab0443be 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApi.java @@ -7,10 +7,9 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -19,25 +18,24 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "user", description = "the user API") public interface UserApi { + UserApiDelegate getDelegate(); + @ApiOperation(value = "Create user", nickname = "createUser", notes = "This can only be done by the logged in user.", tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/user", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - default ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body) { + return getDelegate().createUser(body); } @@ -47,9 +45,8 @@ public interface UserApi { @RequestMapping(value = "/user/createWithArray", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - default ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + return getDelegate().createUsersWithArrayInput(body); } @@ -59,9 +56,8 @@ public interface UserApi { @RequestMapping(value = "/user/createWithList", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - default ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + return getDelegate().createUsersWithListInput(body); } @@ -72,9 +68,8 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - default ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username) { + return getDelegate().deleteUser(username); } @@ -86,9 +81,8 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathVariable("username") String username) { + return getDelegate().getUserByName(username); } @@ -99,9 +93,8 @@ public interface UserApi { @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default ResponseEntity loginUser( @NotNull@ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, @NotNull@ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password) { + return getDelegate().loginUser(username, password); } @@ -111,9 +104,8 @@ public interface UserApi { @RequestMapping(value = "/user/logout", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default ResponseEntity logoutUser( @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity logoutUser() { + return getDelegate().logoutUser(); } @@ -124,9 +116,8 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.PUT) - default ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + default ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body) { + return getDelegate().updateUser(username, body); } } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiController.java index 9f013c42217..3690e9ad6ab 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiController.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiController.java @@ -1,33 +1,9 @@ package io.swagger.api; -import java.util.List; -import io.swagger.model.User; - -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; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; -import javax.validation.constraints.*; -import javax.validation.Valid; @Controller public class UserApiController implements UserApi { - private final ObjectMapper objectMapper; - - public UserApiController(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } private final UserApiDelegate delegate; @@ -36,53 +12,8 @@ public class UserApiController implements UserApi { this.delegate = delegate; } - public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.createUser(body); + @Override + public UserApiDelegate getDelegate() { + return delegate; } - - public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.createUsersWithArrayInput(body); - } - - public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.createUsersWithListInput(body); - } - - public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.deleteUser(username); - } - - public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.getUserByName(username); - } - - public ResponseEntity loginUser( @NotNull@ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, - @NotNull@ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.loginUser(username, password); - } - - public ResponseEntity logoutUser(@RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.logoutUser(); - } - - public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, - @ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return delegate.updateUser(username, body); - } - } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiDelegate.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiDelegate.java index 435efd58a8e..4e56d2e9252 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiDelegate.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiDelegate.java @@ -2,60 +2,109 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; +import java.io.IOException; +import javax.servlet.http.HttpServletRequest; import java.util.List; +import java.util.Optional; /** * A delegate to be called by the {@link UserApiController}}. - * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. - * Instead, use spring to autowire this class into the {@link UserApiController}. + * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class. */ public interface UserApiDelegate { + Logger log = LoggerFactory.getLogger(UserApi.class); + + default Optional getObjectMapper() { + return Optional.empty(); + } + + default Optional getRequest() { + return Optional.empty(); + } + + default Optional getAcceptHeader() { + return getRequest().map(r -> r.getHeader("Accept")); + } + /** * @see UserApi#createUser */ default ResponseEntity createUser(User body) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default UserApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** * @see UserApi#createUsersWithArrayInput */ default ResponseEntity createUsersWithArrayInput(List body) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default UserApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** * @see UserApi#createUsersWithListInput */ default ResponseEntity createUsersWithListInput(List body) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default UserApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** * @see UserApi#deleteUser */ default ResponseEntity deleteUser(String username) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default UserApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** * @see UserApi#getUserByName */ default ResponseEntity getUserByName(String username) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/xml")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue(" 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123", User.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + if (getAcceptHeader().get().contains("application/json")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue("{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\"}", User.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default UserApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** @@ -63,16 +112,38 @@ public interface UserApiDelegate { */ default ResponseEntity loginUser(String username, String password) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + if (getAcceptHeader().get().contains("application/xml")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue("aeiou", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + if (getAcceptHeader().get().contains("application/json")) { + try { + return new ResponseEntity<>(getObjectMapper().get().readValue("\"\"", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default UserApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** * @see UserApi#logoutUser */ default ResponseEntity logoutUser() { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default UserApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** @@ -80,8 +151,11 @@ public interface UserApiDelegate { */ default ResponseEntity updateUser(String username, User body) { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) { + } else { + log.warn("ObjectMapper or HttpServletRequest not configured in default UserApi interface so no example is generated"); + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/FormatTest.java index e809ba3ca62..c73949ecf4f 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/FormatTest.java @@ -71,7 +71,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Min(10) @Max(100) +@Min(10) @Max(100) public Integer getInteger() { return integer; } @@ -93,7 +93,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Min(20) @Max(200) +@Min(20) @Max(200) public Integer getInt32() { return int32; } @@ -137,7 +137,7 @@ public class FormatTest { @NotNull @Valid - @DecimalMin("32.1") @DecimalMax("543.2") +@DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @@ -159,7 +159,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @DecimalMin("54.3") @DecimalMax("987.6") +@DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -181,7 +181,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @DecimalMin("67.8") @DecimalMax("123.4") +@DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -201,7 +201,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Pattern(regexp="/[a-z]/i") +@Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -222,7 +222,7 @@ public class FormatTest { @ApiModelProperty(required = true, value = "") @NotNull - @Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") +@Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") public byte[] getByte() { return _byte; } @@ -327,7 +327,7 @@ public class FormatTest { @ApiModelProperty(required = true, value = "") @NotNull - @Size(min=10,max=64) +@Size(min=10,max=64) public String getPassword() { return password; } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/AnotherFakeApi.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/AnotherFakeApi.java index a3fcfabaf12..6f6dd920913 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/AnotherFakeApi.java @@ -6,9 +6,9 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -17,12 +17,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "another-fake", description = "the another-fake API") public interface AnotherFakeApi { @@ -34,6 +32,6 @@ public interface AnotherFakeApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/AnotherFakeApiController.java index b1b9e947700..a6ed5ef62c8 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/AnotherFakeApiController.java @@ -1,9 +1,9 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -14,19 +14,12 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import java.util.List; @Controller public class AnotherFakeApiController implements AnotherFakeApi { - private final ObjectMapper objectMapper; - - public AnotherFakeApiController(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } private final AnotherFakeApiDelegate delegate; @@ -34,10 +27,7 @@ public class AnotherFakeApiController implements AnotherFakeApi { public AnotherFakeApiController(AnotherFakeApiDelegate delegate) { this.delegate = delegate; } - - public ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { return delegate.testSpecialTags(body); } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/AnotherFakeApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/AnotherFakeApiDelegate.java index b2b85be5817..78d22f6d607 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/AnotherFakeApiDelegate.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/AnotherFakeApiDelegate.java @@ -1,7 +1,6 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; @@ -10,8 +9,7 @@ import java.util.List; /** * A delegate to be called by the {@link AnotherFakeApiController}}. - * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. - * Instead, use spring to autowire this class into the {@link AnotherFakeApiController}. + * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class. */ public interface AnotherFakeApiDelegate { diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApi.java index db6e0e39f59..92b47fb2a37 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApi.java @@ -10,9 +10,9 @@ import io.swagger.model.Client; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import io.swagger.model.OuterComposite; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -21,12 +21,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "fake", description = "the fake API") public interface FakeApi { @@ -36,7 +34,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output boolean", response = Boolean.class) }) @RequestMapping(value = "/fake/outer/boolean", method = RequestMethod.POST) - ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body); @ApiOperation(value = "", nickname = "fakeOuterCompositeSerialize", notes = "Test serialization of object with outer number type", response = OuterComposite.class, tags={ "fake", }) @@ -44,7 +42,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output composite", response = OuterComposite.class) }) @RequestMapping(value = "/fake/outer/composite", method = RequestMethod.POST) - ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body); @ApiOperation(value = "", nickname = "fakeOuterNumberSerialize", notes = "Test serialization of outer number types", response = BigDecimal.class, tags={ "fake", }) @@ -52,7 +50,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output number", response = BigDecimal.class) }) @RequestMapping(value = "/fake/outer/number", method = RequestMethod.POST) - ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body); @ApiOperation(value = "", nickname = "fakeOuterStringSerialize", notes = "Test serialization of outer string types", response = String.class, tags={ "fake", }) @@ -60,7 +58,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output string", response = String.class) }) @RequestMapping(value = "/fake/outer/string", method = RequestMethod.POST) - ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body); @ApiOperation(value = "To test \"client\" model", nickname = "testClientModel", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) @@ -70,7 +68,7 @@ public interface FakeApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", nickname = "testEndpointParameters", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", authorizations = { @@ -83,7 +81,7 @@ public interface FakeApi { produces = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, consumes = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, method = RequestMethod.POST) - ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback); @ApiOperation(value = "To test enum parameters", nickname = "testEnumParameters", notes = "To test enum parameters", tags={ "fake", }) @@ -94,7 +92,16 @@ public interface FakeApi { produces = { "*/*" }, consumes = { "*/*" }, method = RequestMethod.GET) - ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble); + + + @ApiOperation(value = "test inline additionalProperties", nickname = "testInlineAdditionalProperties", notes = "", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation") }) + @RequestMapping(value = "/fake/inline-additionalProperties", + consumes = { "application/json" }, + method = RequestMethod.POST) + ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Object param); @ApiOperation(value = "test json serialization of form data", nickname = "testJsonFormData", notes = "", tags={ "fake", }) @@ -103,6 +110,6 @@ public interface FakeApi { @RequestMapping(value = "/fake/jsonFormData", consumes = { "application/json" }, method = RequestMethod.GET) - ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2); } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiController.java index 1936ebcc6b8..6e05955afe3 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiController.java @@ -5,9 +5,9 @@ import io.swagger.model.Client; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import io.swagger.model.OuterComposite; - import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -18,19 +18,12 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import java.util.List; @Controller public class FakeApiController implements FakeApi { - private final ObjectMapper objectMapper; - - public FakeApiController(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } private final FakeApiDelegate delegate; @@ -38,73 +31,39 @@ public class FakeApiController implements FakeApi { public FakeApiController(FakeApiDelegate delegate) { this.delegate = delegate; } - - public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { return delegate.fakeOuterBooleanSerialize(body); } - public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { return delegate.fakeOuterCompositeSerialize(body); } - public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { return delegate.fakeOuterNumberSerialize(body); } - public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { return delegate.fakeOuterStringSerialize(body); } - public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { return delegate.testClientModel(body); } - public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number, - @ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double, - @ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter, - @ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte, - @ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer, - @ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32, - @ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64, - @ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float, - @ApiParam(value = "None") @RequestPart(value="string", required=false) String string, - @ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary, - @ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date, - @ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime, - @ApiParam(value = "None") @RequestPart(value="password", required=false) String password, - @ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback) { return delegate.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); } - public ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray, - @ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString, - @ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, - @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, - @ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray, - @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger, - @ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble) { return delegate.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); } - public ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param, - @ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Object param) { + return delegate.testInlineAdditionalProperties(param); + } + + public ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2) { return delegate.testJsonFormData(param, param2); } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiDelegate.java index 141576280a9..297dfe50ea2 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiDelegate.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiDelegate.java @@ -5,7 +5,6 @@ import io.swagger.model.Client; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import io.swagger.model.OuterComposite; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; @@ -14,8 +13,7 @@ import java.util.List; /** * A delegate to be called by the {@link FakeApiController}}. - * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. - * Instead, use spring to autowire this class into the {@link FakeApiController}. + * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class. */ public interface FakeApiDelegate { @@ -75,6 +73,11 @@ public interface FakeApiDelegate { Integer enumQueryInteger, Double enumQueryDouble); + /** + * @see FakeApi#testInlineAdditionalProperties + */ + ResponseEntity testInlineAdditionalProperties(Object param); + /** * @see FakeApi#testJsonFormData */ diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeClassnameTestApi.java index 00fffe8a123..8316190673c 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeClassnameTestApi.java @@ -6,9 +6,9 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -17,12 +17,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "fake_classname_test", description = "the fake_classname_test API") public interface FakeClassnameTestApi { @@ -36,6 +34,6 @@ public interface FakeClassnameTestApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeClassnameTestApiController.java index cd4c0acd562..1db51794a68 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeClassnameTestApiController.java @@ -1,9 +1,9 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -14,19 +14,12 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import java.util.List; @Controller public class FakeClassnameTestApiController implements FakeClassnameTestApi { - private final ObjectMapper objectMapper; - - public FakeClassnameTestApiController(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } private final FakeClassnameTestApiDelegate delegate; @@ -34,10 +27,7 @@ public class FakeClassnameTestApiController implements FakeClassnameTestApi { public FakeClassnameTestApiController(FakeClassnameTestApiDelegate delegate) { this.delegate = delegate; } - - public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { return delegate.testClassname(body); } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeClassnameTestApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeClassnameTestApiDelegate.java index 35615202ad3..e17c67de45e 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeClassnameTestApiDelegate.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeClassnameTestApiDelegate.java @@ -1,7 +1,6 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; @@ -10,8 +9,7 @@ import java.util.List; /** * A delegate to be called by the {@link FakeClassnameTestApiController}}. - * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. - * Instead, use spring to autowire this class into the {@link FakeClassnameTestApiController}. + * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class. */ public interface FakeClassnameTestApiDelegate { diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApi.java index e8e51f438d6..d4604e9380e 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApi.java @@ -8,9 +8,9 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -19,12 +19,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "pet", description = "the pet API") public interface PetApi { @@ -41,7 +39,7 @@ public interface PetApi { produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.POST) - ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); @ApiOperation(value = "Deletes a pet", nickname = "deletePet", notes = "", authorizations = { @@ -55,7 +53,7 @@ public interface PetApi { @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "findPetsByStatus", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @@ -70,7 +68,7 @@ public interface PetApi { @RequestMapping(value = "/pet/findByStatus", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByStatus( @NotNull@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status); @ApiOperation(value = "Finds Pets by tags", nickname = "findPetsByTags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -85,7 +83,7 @@ public interface PetApi { @RequestMapping(value = "/pet/findByTags", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByTags( @NotNull@ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags); @ApiOperation(value = "Find pet by ID", nickname = "getPetById", notes = "Returns a single pet", response = Pet.class, authorizations = { @@ -98,7 +96,7 @@ public interface PetApi { @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId); @ApiOperation(value = "Update an existing pet", nickname = "updatePet", notes = "", authorizations = { @@ -115,7 +113,7 @@ public interface PetApi { produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.PUT) - ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); @ApiOperation(value = "Updates a pet in the store with form data", nickname = "updatePetWithForm", notes = "", authorizations = { @@ -130,7 +128,7 @@ public interface PetApi { produces = { "application/xml", "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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "uploadFile", notes = "", response = ModelApiResponse.class, authorizations = { @@ -145,6 +143,6 @@ public interface PetApi { 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") @Valid @RequestPart("file") MultipartFile file, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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") @Valid @RequestPart("file") MultipartFile file); } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiController.java index 62d04acc8fc..e688818e64e 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiController.java @@ -3,9 +3,9 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -16,19 +16,12 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import java.util.List; @Controller public class PetApiController implements PetApi { - private final ObjectMapper objectMapper; - - public PetApiController(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } private final PetApiDelegate delegate; @@ -36,57 +29,35 @@ public class PetApiController implements PetApi { public PetApiController(PetApiDelegate delegate) { this.delegate = delegate; } - - public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { return delegate.addPet(body); } - 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, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + 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) { return delegate.deletePet(petId, apiKey); } - public ResponseEntity> findPetsByStatus( @NotNull@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status) { return delegate.findPetsByStatus(status); } - public ResponseEntity> findPetsByTags( @NotNull@ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags) { return delegate.findPetsByTags(tags); } - public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId) { return delegate.getPetById(petId); } - public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { return delegate.updatePet(body); } - 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, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + 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) { return delegate.updatePetWithForm(petId, name, status); } - 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") @Valid @RequestPart("file") MultipartFile file, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + 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") @Valid @RequestPart("file") MultipartFile file) { return delegate.uploadFile(petId, additionalMetadata, file); } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiDelegate.java index fef5d600cc4..33e49dca56a 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiDelegate.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiDelegate.java @@ -3,7 +3,6 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; @@ -12,8 +11,7 @@ import java.util.List; /** * A delegate to be called by the {@link PetApiController}}. - * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. - * Instead, use spring to autowire this class into the {@link PetApiController}. + * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class. */ public interface PetApiDelegate { diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApi.java index 50abaa03dff..f23d712511f 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApi.java @@ -7,9 +7,9 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,12 +18,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "store", description = "the store API") public interface StoreApi { @@ -35,7 +33,7 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{order_id}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("order_id") String orderId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId); @ApiOperation(value = "Returns pet inventories by status", nickname = "getInventory", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @@ -46,7 +44,7 @@ public interface StoreApi { @RequestMapping(value = "/store/inventory", produces = { "application/json" }, method = RequestMethod.GET) - ResponseEntity> getInventory( @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> getInventory(); @ApiOperation(value = "Find purchase order by ID", nickname = "getOrderById", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @@ -57,7 +55,7 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{order_id}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("order_id") Long orderId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity getOrderById(@Min(1) @Max(5) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId); @ApiOperation(value = "Place an order for a pet", nickname = "placeOrder", notes = "", response = Order.class, tags={ "store", }) @@ -67,6 +65,6 @@ public interface StoreApi { @RequestMapping(value = "/store/order", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body); } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiController.java index dff545adaba..58c433d2f64 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiController.java @@ -2,9 +2,9 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; - import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -15,19 +15,12 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import java.util.List; @Controller public class StoreApiController implements StoreApi { - private final ObjectMapper objectMapper; - - public StoreApiController(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } private final StoreApiDelegate delegate; @@ -35,27 +28,19 @@ public class StoreApiController implements StoreApi { public StoreApiController(StoreApiDelegate delegate) { this.delegate = delegate; } - - public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("order_id") String orderId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId) { return delegate.deleteOrder(orderId); } - public ResponseEntity> getInventory(@RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity> getInventory() { return delegate.getInventory(); } - public ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("order_id") Long orderId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity getOrderById(@Min(1) @Max(5) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId) { return delegate.getOrderById(orderId); } - public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body) { return delegate.placeOrder(body); } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiDelegate.java index ddf2901926a..beb95d79367 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiDelegate.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiDelegate.java @@ -2,7 +2,6 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; @@ -11,8 +10,7 @@ import java.util.List; /** * A delegate to be called by the {@link StoreApiController}}. - * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. - * Instead, use spring to autowire this class into the {@link StoreApiController}. + * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class. */ public interface StoreApiDelegate { diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApi.java index 7264a3bc9cc..3dbcf7293cd 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApi.java @@ -7,9 +7,9 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,12 +18,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "user", description = "the user API") public interface UserApi { @@ -34,7 +32,7 @@ public interface UserApi { @RequestMapping(value = "/user", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body); @ApiOperation(value = "Creates list of users with given input array", nickname = "createUsersWithArrayInput", notes = "", tags={ "user", }) @@ -43,7 +41,7 @@ public interface UserApi { @RequestMapping(value = "/user/createWithArray", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); @ApiOperation(value = "Creates list of users with given input array", nickname = "createUsersWithListInput", notes = "", tags={ "user", }) @@ -52,7 +50,7 @@ public interface UserApi { @RequestMapping(value = "/user/createWithList", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); @ApiOperation(value = "Delete user", nickname = "deleteUser", notes = "This can only be done by the logged in user.", tags={ "user", }) @@ -62,7 +60,7 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username); @ApiOperation(value = "Get user by user name", nickname = "getUserByName", notes = "", response = User.class, tags={ "user", }) @@ -73,7 +71,7 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "loginUser", notes = "", response = String.class, tags={ "user", }) @@ -83,7 +81,7 @@ public interface UserApi { @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity loginUser( @NotNull@ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, @NotNull@ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password); @ApiOperation(value = "Logs out current logged in user session", nickname = "logoutUser", notes = "", tags={ "user", }) @@ -92,7 +90,7 @@ public interface UserApi { @RequestMapping(value = "/user/logout", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity logoutUser( @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity logoutUser(); @ApiOperation(value = "Updated user", nickname = "updateUser", notes = "This can only be done by the logged in user.", tags={ "user", }) @@ -102,6 +100,6 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "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 ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body); } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiController.java index 9f013c42217..41425f19af1 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiController.java @@ -2,9 +2,9 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -15,19 +15,12 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import java.util.List; @Controller public class UserApiController implements UserApi { - private final ObjectMapper objectMapper; - - public UserApiController(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } private final UserApiDelegate delegate; @@ -35,53 +28,35 @@ public class UserApiController implements UserApi { public UserApiController(UserApiDelegate delegate) { this.delegate = delegate; } - - public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body) { return delegate.createUser(body); } - public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { return delegate.createUsersWithArrayInput(body); } - public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { return delegate.createUsersWithListInput(body); } - public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username) { return delegate.deleteUser(username); } - public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathVariable("username") String username) { return delegate.getUserByName(username); } - public ResponseEntity loginUser( @NotNull@ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, - @NotNull@ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password) { return delegate.loginUser(username, password); } - public ResponseEntity logoutUser(@RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity logoutUser() { return delegate.logoutUser(); } - public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, - @ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! + public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body) { return delegate.updateUser(username, body); } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiDelegate.java index 7c2e86e1a95..4c4d0905c8b 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiDelegate.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiDelegate.java @@ -2,7 +2,6 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; @@ -11,8 +10,7 @@ import java.util.List; /** * A delegate to be called by the {@link UserApiController}}. - * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. - * Instead, use spring to autowire this class into the {@link UserApiController}. + * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class. */ public interface UserApiDelegate { diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/FormatTest.java index 9d47a2e4245..9a7f3ff8be1 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/FormatTest.java @@ -71,7 +71,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Min(10) @Max(100) +@Min(10) @Max(100) public Integer getInteger() { return integer; } @@ -93,7 +93,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Min(20) @Max(200) +@Min(20) @Max(200) public Integer getInt32() { return int32; } @@ -137,7 +137,7 @@ public class FormatTest { @NotNull @Valid - @DecimalMin("32.1") @DecimalMax("543.2") +@DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @@ -159,7 +159,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @DecimalMin("54.3") @DecimalMax("987.6") +@DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -181,7 +181,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @DecimalMin("67.8") @DecimalMax("123.4") +@DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -201,7 +201,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Pattern(regexp="/[a-z]/i") +@Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -222,7 +222,7 @@ public class FormatTest { @ApiModelProperty(required = true, value = "") @NotNull - @Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") +@Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") public byte[] getByte() { return _byte; } @@ -327,7 +327,7 @@ public class FormatTest { @ApiModelProperty(required = true, value = "") @NotNull - @Size(min=10,max=64) +@Size(min=10,max=64) public String getPassword() { return password; } diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/AnotherFakeApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/AnotherFakeApi.java index f4111f3fbd2..b64d01acfd1 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/AnotherFakeApi.java @@ -6,9 +6,9 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -17,12 +17,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "another-fake", description = "the another-fake API") public interface AnotherFakeApi { @@ -31,12 +29,11 @@ public interface AnotherFakeApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) @ApiImplicitParams({ - }) @RequestMapping(value = "/another-fake/dummy", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); } diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/AnotherFakeApiController.java index 02fe84a126e..1f969f15713 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/AnotherFakeApiController.java @@ -1,9 +1,10 @@ package io.swagger.api; import io.swagger.model.Client; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -14,29 +15,39 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class AnotherFakeApiController implements AnotherFakeApi { + + private static final Logger log = LoggerFactory.getLogger(AnotherFakeApiController.class); + private final ObjectMapper objectMapper; - public AnotherFakeApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public AnotherFakeApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/FakeApi.java index 8ce5280a6f2..9c60fd29bea 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/FakeApi.java @@ -10,9 +10,9 @@ import io.swagger.model.Client; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import io.swagger.model.OuterComposite; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -21,12 +21,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "fake", description = "the fake API") public interface FakeApi { @@ -35,57 +33,52 @@ public interface FakeApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "Output boolean", response = Boolean.class) }) @ApiImplicitParams({ - }) @RequestMapping(value = "/fake/outer/boolean", method = RequestMethod.POST) - ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body); @ApiOperation(value = "", nickname = "fakeOuterCompositeSerialize", notes = "Test serialization of object with outer number type", response = OuterComposite.class, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Output composite", response = OuterComposite.class) }) @ApiImplicitParams({ - }) @RequestMapping(value = "/fake/outer/composite", method = RequestMethod.POST) - ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body); @ApiOperation(value = "", nickname = "fakeOuterNumberSerialize", notes = "Test serialization of outer number types", response = BigDecimal.class, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Output number", response = BigDecimal.class) }) @ApiImplicitParams({ - }) @RequestMapping(value = "/fake/outer/number", method = RequestMethod.POST) - ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body); @ApiOperation(value = "", nickname = "fakeOuterStringSerialize", notes = "Test serialization of outer string types", response = String.class, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Output string", response = String.class) }) @ApiImplicitParams({ - }) @RequestMapping(value = "/fake/outer/string", method = RequestMethod.POST) - ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body); @ApiOperation(value = "To test \"client\" model", nickname = "testClientModel", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) @ApiImplicitParams({ - }) @RequestMapping(value = "/fake", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", nickname = "testEndpointParameters", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", authorizations = { @@ -95,13 +88,12 @@ public interface FakeApi { @ApiResponse(code = 400, message = "Invalid username supplied"), @ApiResponse(code = 404, message = "User not found") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/fake", produces = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, consumes = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, method = RequestMethod.POST) - ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback); @ApiOperation(value = "To test enum parameters", nickname = "testEnumParameters", notes = "To test enum parameters", tags={ "fake", }) @@ -109,24 +101,35 @@ public interface FakeApi { @ApiResponse(code = 400, message = "Invalid request"), @ApiResponse(code = 404, message = "Not found") }) @ApiImplicitParams({ - @ApiImplicitParam(name = "enumHeaderStringArray", value = "Header parameter enum test (string array)", dataType = "List", paramType = "header"),@ApiImplicitParam(name = "enumHeaderString", value = "Header parameter enum test (string)", dataType = "String", paramType = "header") + @ApiImplicitParam(name = "enumHeaderStringArray", value = "Header parameter enum test (string array)", dataType = "List", paramType = "header"), + @ApiImplicitParam(name = "enumHeaderString", value = "Header parameter enum test (string)", dataType = "String", paramType = "header") }) @RequestMapping(value = "/fake", produces = { "*/*" }, consumes = { "*/*" }, method = RequestMethod.GET) - ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble); + + + @ApiOperation(value = "test inline additionalProperties", nickname = "testInlineAdditionalProperties", notes = "", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation") }) + @ApiImplicitParams({ + }) + @RequestMapping(value = "/fake/inline-additionalProperties", + consumes = { "application/json" }, + method = RequestMethod.POST) + ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Object param); @ApiOperation(value = "test json serialization of form data", nickname = "testJsonFormData", notes = "", tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/fake/jsonFormData", consumes = { "application/json" }, method = RequestMethod.GET) - ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2); } diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/FakeApiController.java index 4e774234877..9d135bee8d7 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/FakeApiController.java @@ -5,9 +5,10 @@ import io.swagger.model.Client; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import io.swagger.model.OuterComposite; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -18,110 +19,115 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class FakeApiController implements FakeApi { + + private static final Logger log = LoggerFactory.getLogger(FakeApiController.class); + private final ObjectMapper objectMapper; - public FakeApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public FakeApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ }", Boolean.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ }", Boolean.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"my_string\" : { }, \"my_number\" : { }, \"my_boolean\" : { }}", OuterComposite.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"my_string\" : { }, \"my_number\" : { }, \"my_boolean\" : { }}", OuterComposite.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ }", BigDecimal.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ }", BigDecimal.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ }", String.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ }", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number, - @ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double, - @ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter, - @ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte, - @ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer, - @ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32, - @ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64, - @ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float, - @ApiParam(value = "None") @RequestPart(value="string", required=false) String string, - @ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary, - @ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date, - @ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime, - @ApiParam(value = "None") @RequestPart(value="password", required=false) String password, - @ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray, - @ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString, - @ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray, - @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger, - @ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param, - @ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Object param) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); + } + + public ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/FakeClassnameTestApi.java index 8780b066c18..6fd233b0e39 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/FakeClassnameTestApi.java @@ -6,9 +6,9 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -17,12 +17,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "fake_classname_test", description = "the fake_classname_test API") public interface FakeClassnameTestApi { @@ -33,12 +31,11 @@ public interface FakeClassnameTestApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) @ApiImplicitParams({ - }) @RequestMapping(value = "/fake_classname_test", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); } diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/FakeClassnameTestApiController.java index ea2c0016470..37288b4c860 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/FakeClassnameTestApiController.java @@ -1,9 +1,10 @@ package io.swagger.api; import io.swagger.model.Client; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -14,29 +15,39 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class FakeClassnameTestApiController implements FakeClassnameTestApi { + + private static final Logger log = LoggerFactory.getLogger(FakeClassnameTestApiController.class); + private final ObjectMapper objectMapper; - public FakeClassnameTestApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public FakeClassnameTestApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/PetApi.java index e787d55f2a8..81a60b11f13 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/PetApi.java @@ -8,9 +8,9 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -19,12 +19,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "pet", description = "the pet API") public interface PetApi { @@ -38,13 +36,12 @@ public interface PetApi { @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/pet", produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.POST) - ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); @ApiOperation(value = "Deletes a pet", nickname = "deletePet", notes = "", authorizations = { @@ -61,7 +58,7 @@ public interface PetApi { @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathVariable("petId") Long petId); @ApiOperation(value = "Finds Pets by status", nickname = "findPetsByStatus", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @@ -74,12 +71,11 @@ public interface PetApi { @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @ApiResponse(code = 400, message = "Invalid status value") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/pet/findByStatus", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByStatus( @NotNull@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status); @ApiOperation(value = "Finds Pets by tags", nickname = "findPetsByTags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -92,12 +88,11 @@ public interface PetApi { @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @ApiResponse(code = 400, message = "Invalid tag value") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/pet/findByTags", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByTags( @NotNull@ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags); @ApiOperation(value = "Find pet by ID", nickname = "getPetById", notes = "Returns a single pet", response = Pet.class, authorizations = { @@ -108,12 +103,11 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Pet not found") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId); @ApiOperation(value = "Update an existing pet", nickname = "updatePet", notes = "", authorizations = { @@ -127,13 +121,12 @@ public interface PetApi { @ApiResponse(code = 404, message = "Pet not found"), @ApiResponse(code = 405, message = "Validation exception") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/pet", produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.PUT) - ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); @ApiOperation(value = "Updates a pet in the store with form data", nickname = "updatePetWithForm", notes = "", authorizations = { @@ -145,13 +138,12 @@ public interface PetApi { @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "uploadFile", notes = "", response = ModelApiResponse.class, authorizations = { @@ -163,12 +155,11 @@ public interface PetApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) @ApiImplicitParams({ - }) @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") @Valid @RequestPart("file") MultipartFile file, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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") @Valid @RequestPart("file") MultipartFile file); } diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/PetApiController.java index 8dfade4628e..9bf771741b8 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/PetApiController.java @@ -3,9 +3,10 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -16,105 +17,128 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class PetApiController implements PetApi { + + private static final Logger log = LoggerFactory.getLogger(PetApiController.class); + private final ObjectMapper objectMapper; - public PetApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public PetApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathVariable("petId") Long petId) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity> findPetsByStatus( @NotNull@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity>(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity> findPetsByTags( @NotNull@ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity>(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 doggie aeiou aeiou", Pet.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 doggie aeiou aeiou", Pet.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}", Pet.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}", Pet.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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 ) @Valid @RequestBody Pet body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - 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, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - 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") @Valid @RequestPart("file") MultipartFile file, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + 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") @Valid @RequestPart("file") MultipartFile file) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\"}", ModelApiResponse.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\"}", ModelApiResponse.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/StoreApi.java index 6206381ca92..f6d21087d1b 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/StoreApi.java @@ -7,9 +7,9 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,12 +18,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "store", description = "the store API") public interface StoreApi { @@ -33,12 +31,11 @@ public interface StoreApi { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Order not found") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/store/order/{order_id}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("order_id") String orderId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId); @ApiOperation(value = "Returns pet inventories by status", nickname = "getInventory", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @@ -47,12 +44,11 @@ public interface StoreApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Map.class, responseContainer = "Map") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/store/inventory", produces = { "application/json" }, method = RequestMethod.GET) - ResponseEntity> getInventory( @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> getInventory(); @ApiOperation(value = "Find purchase order by ID", nickname = "getOrderById", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @@ -61,12 +57,11 @@ public interface StoreApi { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Order not found") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/store/order/{order_id}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("order_id") Long orderId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity getOrderById(@Min(1) @Max(5) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId); @ApiOperation(value = "Place an order for a pet", nickname = "placeOrder", notes = "", response = Order.class, tags={ "store", }) @@ -74,11 +69,10 @@ public interface StoreApi { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid Order") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/store/order", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body); } diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/StoreApiController.java index 6e596b41279..6e463e1307f 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/StoreApiController.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/StoreApiController.java @@ -2,9 +2,10 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -15,66 +16,90 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class StoreApiController implements StoreApi { + + private static final Logger log = LoggerFactory.getLogger(StoreApiController.class); + private final ObjectMapper objectMapper; - public StoreApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public StoreApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("order_id") String orderId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity> getInventory(@RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity> getInventory() { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity>(objectMapper.readValue("{ \"key\" : 0}", Map.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue("{ \"key\" : 0}", Map.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity>(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("order_id") Long orderId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity getOrderById(@Min(1) @Max(5) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/UserApi.java index 9b3e8feb6b3..04bd05d9973 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/UserApi.java @@ -7,9 +7,9 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,12 +18,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "user", description = "the user API") public interface UserApi { @@ -32,36 +30,33 @@ public interface UserApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/user", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body); @ApiOperation(value = "Creates list of users with given input array", nickname = "createUsersWithArrayInput", notes = "", tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/user/createWithArray", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); @ApiOperation(value = "Creates list of users with given input array", nickname = "createUsersWithListInput", notes = "", tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/user/createWithList", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); @ApiOperation(value = "Delete user", nickname = "deleteUser", notes = "This can only be done by the logged in user.", tags={ "user", }) @@ -69,12 +64,11 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid username supplied"), @ApiResponse(code = 404, message = "User not found") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username); @ApiOperation(value = "Get user by user name", nickname = "getUserByName", notes = "", response = User.class, tags={ "user", }) @@ -83,12 +77,11 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid username supplied"), @ApiResponse(code = 404, message = "User not found") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/user/{username}", produces = { "application/xml", "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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "loginUser", notes = "", response = String.class, tags={ "user", }) @@ -96,24 +89,22 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation", response = String.class), @ApiResponse(code = 400, message = "Invalid username/password supplied") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity loginUser( @NotNull@ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, @NotNull@ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password); @ApiOperation(value = "Logs out current logged in user session", nickname = "logoutUser", notes = "", tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/user/logout", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity logoutUser( @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity logoutUser(); @ApiOperation(value = "Updated user", nickname = "updateUser", notes = "This can only be done by the logged in user.", tags={ "user", }) @@ -121,11 +112,10 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid user supplied"), @ApiResponse(code = 404, message = "User not found") }) @ApiImplicitParams({ - }) @RequestMapping(value = "/user/{username}", produces = { "application/xml", "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 ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body); } diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/UserApiController.java index c0f360c3543..e96dfe648b4 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/UserApiController.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/api/UserApiController.java @@ -2,9 +2,10 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -15,87 +16,101 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class UserApiController implements UserApi { + + private static final Logger log = LoggerFactory.getLogger(UserApiController.class); + private final ObjectMapper objectMapper; - public UserApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public UserApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathVariable("username") String username) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123", User.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123", User.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\"}", User.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\"}", User.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity loginUser( @NotNull@ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, - @NotNull@ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue("aeiou", String.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("aeiou", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("\"\"", String.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("\"\"", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity logoutUser(@RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity logoutUser() { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, - @ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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 ) @Valid @RequestBody User body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/model/FormatTest.java index 9d47a2e4245..9a7f3ff8be1 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/io/swagger/model/FormatTest.java @@ -71,7 +71,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Min(10) @Max(100) +@Min(10) @Max(100) public Integer getInteger() { return integer; } @@ -93,7 +93,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Min(20) @Max(200) +@Min(20) @Max(200) public Integer getInt32() { return int32; } @@ -137,7 +137,7 @@ public class FormatTest { @NotNull @Valid - @DecimalMin("32.1") @DecimalMax("543.2") +@DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @@ -159,7 +159,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @DecimalMin("54.3") @DecimalMax("987.6") +@DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -181,7 +181,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @DecimalMin("67.8") @DecimalMax("123.4") +@DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -201,7 +201,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Pattern(regexp="/[a-z]/i") +@Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -222,7 +222,7 @@ public class FormatTest { @ApiModelProperty(required = true, value = "") @NotNull - @Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") +@Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") public byte[] getByte() { return _byte; } @@ -327,7 +327,7 @@ public class FormatTest { @ApiModelProperty(required = true, value = "") @NotNull - @Size(min=10,max=64) +@Size(min=10,max=64) public String getPassword() { return password; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/AnotherFakeApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/AnotherFakeApi.java index 62ca3f0eaa2..8364594a3ee 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/AnotherFakeApi.java @@ -6,9 +6,9 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -17,13 +17,11 @@ 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.io.IOException; +import javax.validation.Valid; +import javax.validation.constraints.*; import java.util.List; import java.util.Optional; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; -import javax.validation.Valid; @Api(value = "another-fake", description = "the another-fake API") public interface AnotherFakeApi { @@ -35,6 +33,6 @@ public interface AnotherFakeApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/AnotherFakeApiController.java index 6868090b4db..a730e5898f0 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/AnotherFakeApiController.java @@ -1,9 +1,10 @@ package io.swagger.api; import io.swagger.model.Client; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -14,30 +15,40 @@ 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 java.util.Optional; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.util.Optional; +import java.io.IOException; +import java.util.List; @Controller public class AnotherFakeApiController implements AnotherFakeApi { + + private static final Logger log = LoggerFactory.getLogger(AnotherFakeApiController.class); + private final ObjectMapper objectMapper; - public AnotherFakeApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public AnotherFakeApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/FakeApi.java index 97e16f68d86..4daad28bdb5 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/FakeApi.java @@ -10,9 +10,9 @@ import io.swagger.model.Client; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import io.swagger.model.OuterComposite; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -21,13 +21,11 @@ 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.io.IOException; +import javax.validation.Valid; +import javax.validation.constraints.*; import java.util.List; import java.util.Optional; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; -import javax.validation.Valid; @Api(value = "fake", description = "the fake API") public interface FakeApi { @@ -37,7 +35,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output boolean", response = Boolean.class) }) @RequestMapping(value = "/fake/outer/boolean", method = RequestMethod.POST) - ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body); @ApiOperation(value = "", nickname = "fakeOuterCompositeSerialize", notes = "Test serialization of object with outer number type", response = OuterComposite.class, tags={ "fake", }) @@ -45,7 +43,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output composite", response = OuterComposite.class) }) @RequestMapping(value = "/fake/outer/composite", method = RequestMethod.POST) - ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body); @ApiOperation(value = "", nickname = "fakeOuterNumberSerialize", notes = "Test serialization of outer number types", response = BigDecimal.class, tags={ "fake", }) @@ -53,7 +51,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output number", response = BigDecimal.class) }) @RequestMapping(value = "/fake/outer/number", method = RequestMethod.POST) - ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body); @ApiOperation(value = "", nickname = "fakeOuterStringSerialize", notes = "Test serialization of outer string types", response = String.class, tags={ "fake", }) @@ -61,7 +59,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output string", response = String.class) }) @RequestMapping(value = "/fake/outer/string", method = RequestMethod.POST) - ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body); @ApiOperation(value = "To test \"client\" model", nickname = "testClientModel", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) @@ -71,7 +69,7 @@ public interface FakeApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", nickname = "testEndpointParameters", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", authorizations = { @@ -84,7 +82,7 @@ public interface FakeApi { produces = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, consumes = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, method = RequestMethod.POST) - ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback); @ApiOperation(value = "To test enum parameters", nickname = "testEnumParameters", notes = "To test enum parameters", tags={ "fake", }) @@ -95,7 +93,16 @@ public interface FakeApi { produces = { "*/*" }, consumes = { "*/*" }, method = RequestMethod.GET) - ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) Optional> enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) Optional enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) Optional> enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") Optional enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Optional enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) Optional> enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) Optional enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) Optional> enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") Optional enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Optional enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble); + + + @ApiOperation(value = "test inline additionalProperties", nickname = "testInlineAdditionalProperties", notes = "", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation") }) + @RequestMapping(value = "/fake/inline-additionalProperties", + consumes = { "application/json" }, + method = RequestMethod.POST) + ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Object param); @ApiOperation(value = "test json serialization of form data", nickname = "testJsonFormData", notes = "", tags={ "fake", }) @@ -104,6 +111,6 @@ public interface FakeApi { @RequestMapping(value = "/fake/jsonFormData", consumes = { "application/json" }, method = RequestMethod.GET) - ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2); } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/FakeApiController.java index 64337b2530f..55c9b827cc7 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/FakeApiController.java @@ -5,9 +5,10 @@ import io.swagger.model.Client; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import io.swagger.model.OuterComposite; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -18,113 +19,116 @@ 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 java.util.Optional; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.util.Optional; +import java.io.IOException; +import java.util.List; @Controller public class FakeApiController implements FakeApi { + + private static final Logger log = LoggerFactory.getLogger(FakeApiController.class); + private final ObjectMapper objectMapper; - public FakeApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public FakeApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ }", Boolean.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ }", Boolean.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"my_string\" : { }, \"my_number\" : { }, \"my_boolean\" : { }}", OuterComposite.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"my_string\" : { }, \"my_number\" : { }, \"my_boolean\" : { }}", OuterComposite.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ }", BigDecimal.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ }", BigDecimal.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ }", String.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ }", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number, - @ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double, - @ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter, - @ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte, - @ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer, - @ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32, - @ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64, - @ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float, - @ApiParam(value = "None") @RequestPart(value="string", required=false) String string, - @ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary, - @ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date, - @ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime, - @ApiParam(value = "None") @RequestPart(value="password", required=false) String password, - @ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray, - @ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString, - @ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) Optional> enumHeaderStringArray, - @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) Optional enumHeaderString, - @ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) Optional> enumQueryStringArray, - @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") Optional enumQueryString, - @ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Optional enumQueryInteger, - @ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) Optional> enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) Optional enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) Optional> enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") Optional enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Optional enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param, - @ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Object param) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); + } + + public ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/FakeClassnameTestApi.java index 18477c21ccf..a2041e4522a 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/FakeClassnameTestApi.java @@ -6,9 +6,9 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -17,13 +17,11 @@ 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.io.IOException; +import javax.validation.Valid; +import javax.validation.constraints.*; import java.util.List; import java.util.Optional; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; -import javax.validation.Valid; @Api(value = "fake_classname_test", description = "the fake_classname_test API") public interface FakeClassnameTestApi { @@ -37,6 +35,6 @@ public interface FakeClassnameTestApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/FakeClassnameTestApiController.java index 211f2f7487c..a87bffa6586 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/FakeClassnameTestApiController.java @@ -1,9 +1,10 @@ package io.swagger.api; import io.swagger.model.Client; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -14,30 +15,40 @@ 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 java.util.Optional; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.util.Optional; +import java.io.IOException; +import java.util.List; @Controller public class FakeClassnameTestApiController implements FakeClassnameTestApi { + + private static final Logger log = LoggerFactory.getLogger(FakeClassnameTestApiController.class); + private final ObjectMapper objectMapper; - public FakeClassnameTestApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public FakeClassnameTestApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/PetApi.java index d5723ddec2a..3fe21700e12 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/PetApi.java @@ -8,9 +8,9 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -19,13 +19,11 @@ 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.io.IOException; +import javax.validation.Valid; +import javax.validation.constraints.*; import java.util.List; import java.util.Optional; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; -import javax.validation.Valid; @Api(value = "pet", description = "the pet API") public interface PetApi { @@ -42,7 +40,7 @@ public interface PetApi { produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.POST) - ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); @ApiOperation(value = "Deletes a pet", nickname = "deletePet", notes = "", authorizations = { @@ -56,7 +54,7 @@ public interface PetApi { @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "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) Optional apiKey, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) Optional apiKey); @ApiOperation(value = "Finds Pets by status", nickname = "findPetsByStatus", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @@ -71,7 +69,7 @@ public interface PetApi { @RequestMapping(value = "/pet/findByStatus", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByStatus( @NotNull@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status); @ApiOperation(value = "Finds Pets by tags", nickname = "findPetsByTags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -86,7 +84,7 @@ public interface PetApi { @RequestMapping(value = "/pet/findByTags", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByTags( @NotNull@ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags); @ApiOperation(value = "Find pet by ID", nickname = "getPetById", notes = "Returns a single pet", response = Pet.class, authorizations = { @@ -99,7 +97,7 @@ public interface PetApi { @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId); @ApiOperation(value = "Update an existing pet", nickname = "updatePet", notes = "", authorizations = { @@ -116,7 +114,7 @@ public interface PetApi { produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.PUT) - ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); @ApiOperation(value = "Updates a pet in the store with form data", nickname = "updatePetWithForm", notes = "", authorizations = { @@ -131,7 +129,7 @@ public interface PetApi { produces = { "application/xml", "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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "uploadFile", notes = "", response = ModelApiResponse.class, authorizations = { @@ -146,6 +144,6 @@ public interface PetApi { 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") @Valid @RequestPart("file") MultipartFile file, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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") @Valid @RequestPart("file") MultipartFile file); } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/PetApiController.java index ee3aa428362..9e97a9347ff 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/PetApiController.java @@ -3,9 +3,10 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -16,107 +17,129 @@ 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 java.util.Optional; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.util.Optional; +import java.io.IOException; +import java.util.List; @Controller public class PetApiController implements PetApi { + + private static final Logger log = LoggerFactory.getLogger(PetApiController.class); + private final ObjectMapper objectMapper; - public PetApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public PetApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) Optional apiKey, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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) Optional apiKey) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity> findPetsByStatus( @NotNull@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity>(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity> findPetsByTags( @NotNull@ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity>(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 doggie aeiou aeiou", Pet.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 doggie aeiou aeiou", Pet.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}", Pet.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}", Pet.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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 ) @Valid @RequestBody Pet body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - 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, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - 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") @Valid @RequestPart("file") MultipartFile file, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + 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") @Valid @RequestPart("file") MultipartFile file) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\"}", ModelApiResponse.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\"}", ModelApiResponse.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/StoreApi.java index 461faf4522a..021b7830489 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/StoreApi.java @@ -7,9 +7,9 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,13 +18,11 @@ 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.io.IOException; +import javax.validation.Valid; +import javax.validation.constraints.*; import java.util.List; import java.util.Optional; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; -import javax.validation.Valid; @Api(value = "store", description = "the store API") public interface StoreApi { @@ -36,7 +34,7 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{order_id}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("order_id") String orderId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId); @ApiOperation(value = "Returns pet inventories by status", nickname = "getInventory", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @@ -47,7 +45,7 @@ public interface StoreApi { @RequestMapping(value = "/store/inventory", produces = { "application/json" }, method = RequestMethod.GET) - ResponseEntity> getInventory( @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> getInventory(); @ApiOperation(value = "Find purchase order by ID", nickname = "getOrderById", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @@ -58,7 +56,7 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{order_id}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("order_id") Long orderId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity getOrderById(@Min(1) @Max(5) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId); @ApiOperation(value = "Place an order for a pet", nickname = "placeOrder", notes = "", response = Order.class, tags={ "store", }) @@ -68,6 +66,6 @@ public interface StoreApi { @RequestMapping(value = "/store/order", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body); } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/StoreApiController.java index d534a47a020..1ee1125dc1b 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/StoreApiController.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/StoreApiController.java @@ -2,9 +2,10 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -15,67 +16,91 @@ 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 java.util.Optional; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.util.Optional; +import java.io.IOException; +import java.util.List; @Controller public class StoreApiController implements StoreApi { + + private static final Logger log = LoggerFactory.getLogger(StoreApiController.class); + private final ObjectMapper objectMapper; - public StoreApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public StoreApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("order_id") String orderId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity> getInventory(@RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity> getInventory() { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity>(objectMapper.readValue("{ \"key\" : 0}", Map.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue("{ \"key\" : 0}", Map.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity>(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("order_id") Long orderId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity getOrderById(@Min(1) @Max(5) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/UserApi.java index 40ac1add4bd..bf116aa378c 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/UserApi.java @@ -7,9 +7,9 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,13 +18,11 @@ 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.io.IOException; +import javax.validation.Valid; +import javax.validation.constraints.*; import java.util.List; import java.util.Optional; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; -import javax.validation.Valid; @Api(value = "user", description = "the user API") public interface UserApi { @@ -35,7 +33,7 @@ public interface UserApi { @RequestMapping(value = "/user", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body); @ApiOperation(value = "Creates list of users with given input array", nickname = "createUsersWithArrayInput", notes = "", tags={ "user", }) @@ -44,7 +42,7 @@ public interface UserApi { @RequestMapping(value = "/user/createWithArray", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); @ApiOperation(value = "Creates list of users with given input array", nickname = "createUsersWithListInput", notes = "", tags={ "user", }) @@ -53,7 +51,7 @@ public interface UserApi { @RequestMapping(value = "/user/createWithList", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); @ApiOperation(value = "Delete user", nickname = "deleteUser", notes = "This can only be done by the logged in user.", tags={ "user", }) @@ -63,7 +61,7 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username); @ApiOperation(value = "Get user by user name", nickname = "getUserByName", notes = "", response = User.class, tags={ "user", }) @@ -74,7 +72,7 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "loginUser", notes = "", response = String.class, tags={ "user", }) @@ -84,7 +82,7 @@ public interface UserApi { @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity loginUser( @NotNull@ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, @NotNull@ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password); @ApiOperation(value = "Logs out current logged in user session", nickname = "logoutUser", notes = "", tags={ "user", }) @@ -93,7 +91,7 @@ public interface UserApi { @RequestMapping(value = "/user/logout", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity logoutUser( @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity logoutUser(); @ApiOperation(value = "Updated user", nickname = "updateUser", notes = "This can only be done by the logged in user.", tags={ "user", }) @@ -103,6 +101,6 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "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 ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body); } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/UserApiController.java index a2f4a5478f1..cf47c9ce282 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/UserApiController.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/api/UserApiController.java @@ -2,9 +2,10 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -15,88 +16,102 @@ 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 java.util.Optional; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.util.Optional; +import java.io.IOException; +import java.util.List; @Controller public class UserApiController implements UserApi { + + private static final Logger log = LoggerFactory.getLogger(UserApiController.class); + private final ObjectMapper objectMapper; - public UserApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public UserApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathVariable("username") String username) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123", User.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123", User.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\"}", User.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\"}", User.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity loginUser( @NotNull@ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, - @NotNull@ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue("aeiou", String.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("aeiou", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("\"\"", String.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("\"\"", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity logoutUser(@RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity logoutUser() { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, - @ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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 ) @Valid @RequestBody User body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/model/FormatTest.java index 9d47a2e4245..9a7f3ff8be1 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/io/swagger/model/FormatTest.java @@ -71,7 +71,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Min(10) @Max(100) +@Min(10) @Max(100) public Integer getInteger() { return integer; } @@ -93,7 +93,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Min(20) @Max(200) +@Min(20) @Max(200) public Integer getInt32() { return int32; } @@ -137,7 +137,7 @@ public class FormatTest { @NotNull @Valid - @DecimalMin("32.1") @DecimalMax("543.2") +@DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @@ -159,7 +159,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @DecimalMin("54.3") @DecimalMax("987.6") +@DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -181,7 +181,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @DecimalMin("67.8") @DecimalMax("123.4") +@DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -201,7 +201,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Pattern(regexp="/[a-z]/i") +@Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -222,7 +222,7 @@ public class FormatTest { @ApiModelProperty(required = true, value = "") @NotNull - @Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") +@Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") public byte[] getByte() { return _byte; } @@ -327,7 +327,7 @@ public class FormatTest { @ApiModelProperty(required = true, value = "") @NotNull - @Size(min=10,max=64) +@Size(min=10,max=64) public String getPassword() { return password; } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/AnotherFakeApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/AnotherFakeApi.java index a3fcfabaf12..6f6dd920913 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/AnotherFakeApi.java @@ -6,9 +6,9 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -17,12 +17,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "another-fake", description = "the another-fake API") public interface AnotherFakeApi { @@ -34,6 +32,6 @@ public interface AnotherFakeApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/AnotherFakeApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/AnotherFakeApiController.java index 02fe84a126e..1f969f15713 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/AnotherFakeApiController.java @@ -1,9 +1,10 @@ package io.swagger.api; import io.swagger.model.Client; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -14,29 +15,39 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class AnotherFakeApiController implements AnotherFakeApi { + + private static final Logger log = LoggerFactory.getLogger(AnotherFakeApiController.class); + private final ObjectMapper objectMapper; - public AnotherFakeApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public AnotherFakeApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java index db6e0e39f59..92b47fb2a37 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java @@ -10,9 +10,9 @@ import io.swagger.model.Client; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import io.swagger.model.OuterComposite; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -21,12 +21,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "fake", description = "the fake API") public interface FakeApi { @@ -36,7 +34,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output boolean", response = Boolean.class) }) @RequestMapping(value = "/fake/outer/boolean", method = RequestMethod.POST) - ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body); @ApiOperation(value = "", nickname = "fakeOuterCompositeSerialize", notes = "Test serialization of object with outer number type", response = OuterComposite.class, tags={ "fake", }) @@ -44,7 +42,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output composite", response = OuterComposite.class) }) @RequestMapping(value = "/fake/outer/composite", method = RequestMethod.POST) - ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body); @ApiOperation(value = "", nickname = "fakeOuterNumberSerialize", notes = "Test serialization of outer number types", response = BigDecimal.class, tags={ "fake", }) @@ -52,7 +50,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output number", response = BigDecimal.class) }) @RequestMapping(value = "/fake/outer/number", method = RequestMethod.POST) - ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body); @ApiOperation(value = "", nickname = "fakeOuterStringSerialize", notes = "Test serialization of outer string types", response = String.class, tags={ "fake", }) @@ -60,7 +58,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output string", response = String.class) }) @RequestMapping(value = "/fake/outer/string", method = RequestMethod.POST) - ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body); @ApiOperation(value = "To test \"client\" model", nickname = "testClientModel", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) @@ -70,7 +68,7 @@ public interface FakeApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", nickname = "testEndpointParameters", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", authorizations = { @@ -83,7 +81,7 @@ public interface FakeApi { produces = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, consumes = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, method = RequestMethod.POST) - ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback); @ApiOperation(value = "To test enum parameters", nickname = "testEnumParameters", notes = "To test enum parameters", tags={ "fake", }) @@ -94,7 +92,16 @@ public interface FakeApi { produces = { "*/*" }, consumes = { "*/*" }, method = RequestMethod.GET) - ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble); + + + @ApiOperation(value = "test inline additionalProperties", nickname = "testInlineAdditionalProperties", notes = "", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation") }) + @RequestMapping(value = "/fake/inline-additionalProperties", + consumes = { "application/json" }, + method = RequestMethod.POST) + ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Object param); @ApiOperation(value = "test json serialization of form data", nickname = "testJsonFormData", notes = "", tags={ "fake", }) @@ -103,6 +110,6 @@ public interface FakeApi { @RequestMapping(value = "/fake/jsonFormData", consumes = { "application/json" }, method = RequestMethod.GET) - ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java index dc7c60f9790..360e1d910d7 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java @@ -5,9 +5,10 @@ import io.swagger.model.Client; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import io.swagger.model.OuterComposite; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -18,112 +19,115 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class FakeApiController implements FakeApi { + + private static final Logger log = LoggerFactory.getLogger(FakeApiController.class); + private final ObjectMapper objectMapper; - public FakeApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public FakeApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ }", Boolean.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ }", Boolean.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"my_string\" : { }, \"my_number\" : { }, \"my_boolean\" : { }}", OuterComposite.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"my_string\" : { }, \"my_number\" : { }, \"my_boolean\" : { }}", OuterComposite.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ }", BigDecimal.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ }", BigDecimal.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ }", String.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ }", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number, - @ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double, - @ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter, - @ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte, - @ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer, - @ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32, - @ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64, - @ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float, - @ApiParam(value = "None") @RequestPart(value="string", required=false) String string, - @ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary, - @ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date, - @ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime, - @ApiParam(value = "None") @RequestPart(value="password", required=false) String password, - @ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @RequestPart(value="number", required=true) BigDecimal number,@ApiParam(value = "None", required=true) @RequestPart(value="double", required=true) Double _double,@ApiParam(value = "None", required=true) @RequestPart(value="pattern_without_delimiter", required=true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @RequestPart(value="byte", required=true) byte[] _byte,@ApiParam(value = "None") @RequestPart(value="integer", required=false) Integer integer,@ApiParam(value = "None") @RequestPart(value="int32", required=false) Integer int32,@ApiParam(value = "None") @RequestPart(value="int64", required=false) Long int64,@ApiParam(value = "None") @RequestPart(value="float", required=false) Float _float,@ApiParam(value = "None") @RequestPart(value="string", required=false) String string,@ApiParam(value = "None") @RequestPart(value="binary", required=false) byte[] binary,@ApiParam(value = "None") @RequestPart(value="date", required=false) LocalDate date,@ApiParam(value = "None") @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime,@ApiParam(value = "None") @RequestPart(value="password", required=false) String password,@ApiParam(value = "None") @RequestPart(value="callback", required=false) String paramCallback) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray, - @ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString, - @ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, - @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, - @ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray, - @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger, - @ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @RequestPart(value="enum_form_string_array", required=false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestPart(value="enum_form_string", required=false) String enumFormString,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @RequestPart(value="enum_query_double", required=false) Double enumQueryDouble) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param, - @ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Object param) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); + } + + public ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @RequestPart(value="param", required=true) String param,@ApiParam(value = "field2", required=true) @RequestPart(value="param2", required=true) String param2) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeClassnameTestApi.java index 00fffe8a123..8316190673c 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeClassnameTestApi.java @@ -6,9 +6,9 @@ package io.swagger.api; import io.swagger.model.Client; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -17,12 +17,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "fake_classname_test", description = "the fake_classname_test API") public interface FakeClassnameTestApi { @@ -36,6 +34,6 @@ public interface FakeClassnameTestApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) - ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeClassnameTestApiController.java index ea2c0016470..37288b4c860 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeClassnameTestApiController.java @@ -1,9 +1,10 @@ package io.swagger.api; import io.swagger.model.Client; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -14,29 +15,39 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class FakeClassnameTestApiController implements FakeClassnameTestApi { + + private static final Logger log = LoggerFactory.getLogger(FakeClassnameTestApiController.class); + private final ObjectMapper objectMapper; - public FakeClassnameTestApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public FakeClassnameTestApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"client\" : \"client\"}", Client.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } 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 e8e51f438d6..d4604e9380e 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 @@ -8,9 +8,9 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -19,12 +19,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "pet", description = "the pet API") public interface PetApi { @@ -41,7 +39,7 @@ public interface PetApi { produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.POST) - ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); @ApiOperation(value = "Deletes a pet", nickname = "deletePet", notes = "", authorizations = { @@ -55,7 +53,7 @@ public interface PetApi { @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "findPetsByStatus", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @@ -70,7 +68,7 @@ public interface PetApi { @RequestMapping(value = "/pet/findByStatus", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByStatus( @NotNull@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status); @ApiOperation(value = "Finds Pets by tags", nickname = "findPetsByTags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -85,7 +83,7 @@ public interface PetApi { @RequestMapping(value = "/pet/findByTags", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByTags( @NotNull@ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags); @ApiOperation(value = "Find pet by ID", nickname = "getPetById", notes = "Returns a single pet", response = Pet.class, authorizations = { @@ -98,7 +96,7 @@ public interface PetApi { @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId); @ApiOperation(value = "Update an existing pet", nickname = "updatePet", notes = "", authorizations = { @@ -115,7 +113,7 @@ public interface PetApi { produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.PUT) - ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); @ApiOperation(value = "Updates a pet in the store with form data", nickname = "updatePetWithForm", notes = "", authorizations = { @@ -130,7 +128,7 @@ public interface PetApi { produces = { "application/xml", "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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "uploadFile", notes = "", response = ModelApiResponse.class, authorizations = { @@ -145,6 +143,6 @@ public interface PetApi { 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") @Valid @RequestPart("file") MultipartFile file, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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") @Valid @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 index 2153b86a87a..a3890cf787d 100644 --- 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 @@ -3,9 +3,10 @@ package io.swagger.api; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import org.springframework.core.io.Resource; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -16,106 +17,128 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class PetApiController implements PetApi { + + private static final Logger log = LoggerFactory.getLogger(PetApiController.class); + private final ObjectMapper objectMapper; - public PetApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public PetApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - 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, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity> findPetsByStatus( @NotNull@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity>(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity> findPetsByTags( @NotNull@ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue(" 123456789 doggie aeiou aeiou", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue("[ { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}, { \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"} ]", List.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity>(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 doggie aeiou aeiou", Pet.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 doggie aeiou aeiou", Pet.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}", Pet.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\"}", Pet.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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 ) @Valid @RequestBody Pet body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - 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, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - 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") @Valid @RequestPart("file") MultipartFile file, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + 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") @Valid @RequestPart("file") MultipartFile file) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\"}", ModelApiResponse.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\"}", ModelApiResponse.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } 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 50abaa03dff..f23d712511f 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,9 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,12 +18,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "store", description = "the store API") public interface StoreApi { @@ -35,7 +33,7 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{order_id}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("order_id") String orderId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId); @ApiOperation(value = "Returns pet inventories by status", nickname = "getInventory", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @@ -46,7 +44,7 @@ public interface StoreApi { @RequestMapping(value = "/store/inventory", produces = { "application/json" }, method = RequestMethod.GET) - ResponseEntity> getInventory( @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity> getInventory(); @ApiOperation(value = "Find purchase order by ID", nickname = "getOrderById", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @@ -57,7 +55,7 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{order_id}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("order_id") Long orderId, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity getOrderById(@Min(1) @Max(5) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId); @ApiOperation(value = "Place an order for a pet", nickname = "placeOrder", notes = "", response = Order.class, tags={ "store", }) @@ -67,6 +65,6 @@ public interface StoreApi { @RequestMapping(value = "/store/order", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @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 index 6e596b41279..6e463e1307f 100644 --- 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 @@ -2,9 +2,10 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -15,66 +16,90 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class StoreApiController implements StoreApi { + + private static final Logger log = LoggerFactory.getLogger(StoreApiController.class); + private final ObjectMapper objectMapper; - public StoreApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public StoreApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("order_id") String orderId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity> getInventory(@RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity> getInventory() { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { - return new ResponseEntity>(objectMapper.readValue("{ \"key\" : 0}", Map.class), HttpStatus.OK); + try { + return new ResponseEntity>(objectMapper.readValue("{ \"key\" : 0}", Map.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity>(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity>(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("order_id") Long orderId, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity getOrderById(@Min(1) @Max(5) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\"}", Order.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } 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 7264a3bc9cc..3dbcf7293cd 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,9 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,12 +18,10 @@ 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.io.IOException; -import java.util.List; -import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; @Api(value = "user", description = "the user API") public interface UserApi { @@ -34,7 +32,7 @@ public interface UserApi { @RequestMapping(value = "/user", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body); @ApiOperation(value = "Creates list of users with given input array", nickname = "createUsersWithArrayInput", notes = "", tags={ "user", }) @@ -43,7 +41,7 @@ public interface UserApi { @RequestMapping(value = "/user/createWithArray", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); @ApiOperation(value = "Creates list of users with given input array", nickname = "createUsersWithListInput", notes = "", tags={ "user", }) @@ -52,7 +50,7 @@ public interface UserApi { @RequestMapping(value = "/user/createWithList", produces = { "application/xml", "application/json" }, method = RequestMethod.POST) - ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); @ApiOperation(value = "Delete user", nickname = "deleteUser", notes = "This can only be done by the logged in user.", tags={ "user", }) @@ -62,7 +60,7 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username); @ApiOperation(value = "Get user by user name", nickname = "getUserByName", notes = "", response = User.class, tags={ "user", }) @@ -73,7 +71,7 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "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, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + 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", nickname = "loginUser", notes = "", response = String.class, tags={ "user", }) @@ -83,7 +81,7 @@ public interface UserApi { @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity loginUser( @NotNull@ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, @NotNull@ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password); @ApiOperation(value = "Logs out current logged in user session", nickname = "logoutUser", notes = "", tags={ "user", }) @@ -92,7 +90,7 @@ public interface UserApi { @RequestMapping(value = "/user/logout", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity logoutUser( @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity logoutUser(); @ApiOperation(value = "Updated user", nickname = "updateUser", notes = "This can only be done by the logged in user.", tags={ "user", }) @@ -102,6 +100,6 @@ public interface UserApi { @RequestMapping(value = "/user/{username}", produces = { "application/xml", "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 ) @Valid @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception; + ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @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 index c0f360c3543..e96dfe648b4 100644 --- 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 @@ -2,9 +2,10 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; - +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -15,87 +16,101 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import javax.validation.constraints.*; import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; @Controller public class UserApiController implements UserApi { + + private static final Logger log = LoggerFactory.getLogger(UserApiController.class); + private final ObjectMapper objectMapper; - public UserApiController(ObjectMapper objectMapper) { + private final HttpServletRequest request; + + @org.springframework.beans.factory.annotation.Autowired + public UserApiController(ObjectMapper objectMapper, HttpServletRequest request) { this.objectMapper = objectMapper; + this.request = request; } - public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathVariable("username") String username) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue(" 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123", User.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue(" 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123", User.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\"}", User.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\"}", User.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity loginUser( @NotNull@ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, - @NotNull@ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - + public ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password) { + String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/xml")) { - return new ResponseEntity(objectMapper.readValue("aeiou", String.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("aeiou", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/xml", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - if (accept != null && accept.contains("application/json")) { - return new ResponseEntity(objectMapper.readValue("\"\"", String.class), HttpStatus.OK); + try { + return new ResponseEntity(objectMapper.readValue("\"\"", String.class), HttpStatus.NOT_IMPLEMENTED); + } catch (IOException e) { + log.error("Couldn't serialize response for content type application/json", e); + return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); + } } - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity logoutUser(@RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // do some magic! - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity logoutUser() { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } - public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, - @ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body, - @RequestHeader(value = "Accept", required = false) String accept) throws Exception { - // 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 ) @Valid @RequestBody User body) { + String accept = request.getHeader("Accept"); + return new ResponseEntity(HttpStatus.NOT_IMPLEMENTED); } } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/FormatTest.java index 9d47a2e4245..9a7f3ff8be1 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/FormatTest.java @@ -71,7 +71,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Min(10) @Max(100) +@Min(10) @Max(100) public Integer getInteger() { return integer; } @@ -93,7 +93,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Min(20) @Max(200) +@Min(20) @Max(200) public Integer getInt32() { return int32; } @@ -137,7 +137,7 @@ public class FormatTest { @NotNull @Valid - @DecimalMin("32.1") @DecimalMax("543.2") +@DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @@ -159,7 +159,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @DecimalMin("54.3") @DecimalMax("987.6") +@DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -181,7 +181,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @DecimalMin("67.8") @DecimalMax("123.4") +@DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -201,7 +201,7 @@ public class FormatTest { **/ @ApiModelProperty(value = "") - @Pattern(regexp="/[a-z]/i") +@Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -222,7 +222,7 @@ public class FormatTest { @ApiModelProperty(required = true, value = "") @NotNull - @Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") +@Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") public byte[] getByte() { return _byte; } @@ -327,7 +327,7 @@ public class FormatTest { @ApiModelProperty(required = true, value = "") @NotNull - @Size(min=10,max=64) +@Size(min=10,max=64) public String getPassword() { return password; }